【问题标题】:Embedding a single object in form在表单中嵌入单个对象
【发布时间】:2016-01-27 10:11:06
【问题描述】:

我设法创建了一个嵌入另一个表单的表单,但我认为我做的不对。这是我的代码

类别

   class Category
    {
        private $id;

        private $name;

        /**
         * @ORM\OneToMany(targetEntity="Category", mappedBy="category")
         */
        private $subcategorues;

        public function __construct()
        {
            $this->subcategorues = new \Doctrine\Common\Collections\ArrayCollection();
        }


        public function getId()
        {
            return $this->id;
        }

        public function setName($name)
        {
            $this->name = $name;

            return $this;
        }

        public function getName()
        {
            return $this->name;
        }


        public function addSubcategorue(\AppBundle\Entity\Category $subcategorues)
        {
            $this->subcategorues[] = $subcategorues;

            return $this;
        }

        public function removeSubcategorue(\AppBundle\Entity\Category $subcategorues)
        {
            $this->subcategorues->removeElement($subcategorues);
        }

        public function getSubcategorues()
        {
            return $this->subcategorues;
        }

    }

子类别

class Subcategory
{
    private $id;

    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="subcategories")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category;

    /**
     * @return mixed
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param mixed $category
     */
    public function setCategory($category)
    {
        $this->category = $category;
    }
    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }


    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function getName()
    {
        return $this->name;
    }
}

类别类型

.......
 public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'entity', [
                'class' => 'AppBundle\Entity\Category',
                'choice_label' => 'name'
            ]);
    }

 public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => 'AppBundle\Entity\Category'
    ]);
}
......

子类别类型

 $builder
            ->add('category', new CategoryType(), [
                'label' => false
            ])
            ->add('name', 'text')
            ->add('save', 'submit')
            ;    


  public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => 'AppBundle\Entity\Subcategory'
    ]);
}

默认控制器

public function indexAction(Request $request)
    {

        $subcategory = new Subcategory();

        $form = $this->createForm(new SubcategoryType(), $subcategory);

        $form->handleRequest($request);

        if($form->isValid()){

            $em = $this->getDoctrine()->getManager();
            $subcategory->setCategory($subcategory->getCategory()->getName());

            $em->persist($subcategory);
            $em->flush();

            return new Response(sprintf('ID %d', $subcategory->getId()));
        }

        return $this->render('AppBundle::layout.html.twig', [
          'form' => $form->createView(),
        ]);
    }

请注意这行代码$subcategory->setCategory($subcategory->getCategory()->getName()); 我需要该行才能将实体保存到数据库中,否则会出错。所以我的问题是有没有办法跳过这行代码并将类别对象即时传递给 subcategory->category 属性,而不是手动执行?

//编辑

这是 dump($form->getData()); 的输出

DefaultController.php on line 33:
Subcategory {#467 ▼
  -id: null
  -name: "Uncharted"
  -category: Category {#588 ▼
    -id: null
    -name: Category {#685 ▼
      -id: 2
      -name: "Games"
      -subcategorues: PersistentCollection {#686 ▶}
    }
    -subcategorues: ArrayCollection {#660 ▶}
  }
}

【问题讨论】:

    标签: php symfony orm doctrine


    【解决方案1】:

    与您的 Category 实体相比,您的 CategoryType 未正确映射。实际上,在您的情况下,您不需要有一个带有name 字段的子表单CategoryType,因为您在SubCategory 中有一个category 字段,这是与Category 的关系。

    只需替换:

    ->add('category', new CategoryType(), [
                'label' => false
            ])
    

    作者:

    ->add('category', 'entity', [
                'class' => 'AppBundle\Entity\Category',
                'choice_label' => 'name'
            ]);
    

    【讨论】:

      【解决方案2】:

      你可以这样尝试吗(对于Category实体类):

      public function addSubcategorue(\AppBundle\Entity\Category $subcategorues)
      {
          if ($this->subcategorues->contains($subcategorues)) {
              $this->subcategorues->add($subcategorues);
              $subcategorues->setCategory($this);
          }
      
          return $this;
      }
      

      【讨论】:

      • 由于某种原因 addSubcategoue 永远不会被调用。有什么想法吗?
      • 您能否提供一些关于提交和验证后从表单中获得的信息?类似于输出var_dump($form->getData());,删除对象,只留下一个带有 ClassPath/ClassName 的字符串。而选项(例如 setDefaultOptions/ConfigureOptions)方法体,可能不完整,我只需要 data_class 选项,用于您的类别/子类别表单。
      • 我通过在 *type 类中添加 configureOptions 方法和表单数据的转储来更新我的原始问题。请看一看。
      • 看过了。现在我不明白:为什么您需要带有$subcategory->setCategory($subcategory->getCategory()->getName()) 的奇怪字符串?))您能否提供不带该字符串的错误。也许这是关于级联持久/合并/更新的事情?
      • 如果我错过了那行代码,则会出现错误通过关系“AppBundle\Entity\Subcategory#category”找到一个新实体,该关系未配置为实体的级联持久操作:AppBundle\Entity\类别@0000000017424a18000000017b95e21e。要解决此问题:在此未知实体上显式调用 EntityManager#persist() 或配置级联在映射中保持此关联,例如 @ManyToOne(..,cascade={"persist"})。如果您找不到导致问题的实体,请执行“AppBundle\Entity\Category#__toString()”以获取线索。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多