我希望你能帮助我。我使用的是Symfony 2.x和Doctrine 2.x的,以及,我想创建一种由两个实体组成的形式。通过填写这一表格,我想将数据保留到两个学说实体中。

为简单起见,我举了一个例子。一个多语言的网上商店需要有英文和法文的名称和产品描述。我想使用一种形式来创建新产品。该创建表单将包含来自Product实体(id; productTranslations;价格,productTranslations)以及ProductTranslation实体(id;名称;描述;语言,产品)的数据。生成的创建产品表单具有以下字段(名称;描述;语言(EN/FR);价格)。

Product和ProductTranslation实体通过双向一对多关系相互关联。关系的拥有站点是ProductTranslation。

提交表单后,我想将数据持久保存到两个实体(Product和ProductTranslation)。这是出问题的地方。我无法保留数据。

到目前为止,我已经尝试了以下方法:

产品实体:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Product
 *
 * @ORM\Table(name="product")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository")
 */
class Product
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="price", type="decimal", precision=10, scale=0)
     */
    private $price;

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\ProductTranslation", mappedBy="product")
     */
    private $productTranslations;

    public function __construct()
    {
        $this->productTranslations = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set price
     *
     * @param string $price
     *
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return string
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set productTranslations
     *
     * @param \stdClass $productTranslations
     *
     * @return Product
     */
    public function setProductTranslations($productTranslations)
    {
        $this->productTranslations = $productTranslations;

        return $this;
    }

    /**
     * Get productTranslations
     *
     * @return \stdClass
     */
    public function getProductTranslations()
    {
        return $this->productTranslations;
    }

    /**
     * Add productTranslation
     *
     * @param \AppBundle\Entity\ProductTranslation $productTranslation
     *
     * @return Product
     */
    public function addProductTranslation(\AppBundle\Entity\ProductTranslation $productTranslation)
    {
        $this->productTranslations[] = $productTranslation;

        return $this;
    }

    /**
     * Remove productTranslation
     *
     * @param \AppBundle\Entity\ProductTranslation $productTranslation
     */
    public function removeProductTranslation(\AppBundle\Entity\ProductTranslation $productTranslation)
    {
        $this->productTranslations->removeElement($productTranslation);
    }
}

产品翻译实体:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ProductTranslation
 *
 * @ORM\Table(name="product_translation")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ProductTranslationRepository")
 */
class ProductTranslation
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * @var string
     *
     * @ORM\Column(name="language", type="string", length=5)
     */
    private $language;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product", inversedBy="productTranslations",cascade={"persist"})
     * @ORM\JoinColumn(name="product_translation_id", referencedColumnName="id")
     *
     */
    private $product;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return ProductTranslation
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return ProductTranslation
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set language
     *
     * @param string $language
     *
     * @return ProductTranslation
     */
    public function setLanguage($language)
    {
        $this->language = $language;

        return $this;
    }

    /**
     * Get language
     *
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * Set product
     *
     * @param \AppBundle\Entity\Product $product
     *
     * @return ProductTranslation
     */
    public function setProduct(\AppBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \AppBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }
}

产品类型:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;

class ProductType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('productTranslations', ProductTranslationType::class, array('label' => false, 'data_class' => null));
        $builder
                ->add('price', MoneyType::class)
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product'
        ));
    }

}

ProductTranslationType :
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class ProductTranslationType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('description', TextareaType::class )
            ->add('language', ChoiceType::class, array('choices' => array('en' => 'EN', 'fr' => 'FR')))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\ProductTranslation'
        ));
    }
}

ProductController :
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Entity\Product;
use AppBundle\Form\ProductType;
use AppBundle\Entity\ProductTranslation;

/**
 * Product controller.
 *
 */
class ProductController extends Controller {

    /**
     * Creates a new Product entity.
     *
     */
    public function newAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $product = new Product();

        $productTranslation = new ProductTranslation();

        $form = $this->createForm('AppBundle\Form\ProductType', $product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $product->getProductTranslations()->add($product);

            $productTranslation->setProduct($product);

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

            return $this->redirectToRoute('product_show', array('id' => $product->getId()));
        }

        return $this->render('product/new.html.twig', array(
                    'product' => $product,
                    'form' => $form->createView(),
        ));
    }
}

错误:
Warning: spl_object_hash() expects parameter 1 to be object, string given
500 Internal Server Error - ContextErrorException

我在菜谱上寻求帮助:http://symfony.com/doc/current/book/forms.html#embedded-forms,但是我无法使其正常运行。

更新1

我尚未找到问题的答案。在下面的评论之后,我看了看这些关联。我已经对ProductController进行了调整,这使我能够测试数据是否以正确的方式插入数据库。数据已正确插入,但无法通过表格插入。希望有人可以帮助我。

ProductController :
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AppBundle\Entity\Product;
use AppBundle\Form\ProductType;

/**
 * Creates a new Product entity.
 *
 */
public function newAction(Request $request) {
    $em = $this->getDoctrine()->getManager();
    $product = new Product();

    $productTranslation = new ProductTranslation();

    /* Sample data insertion */
    $productTranslation->setProduct($product);
    $productTranslation->setName('Product Q');
    $productTranslation->setDescription('This is product Q');
    $productTranslation->setLanguage('EN');

    $product->setPrice(95);
    $product->addProductTranslation($productTranslation);

    $em->persist($product);
    $em->persist($productTranslation);
    $em->flush();
    /* End sample data insertion */

    $form = $this->createForm('AppBundle\Form\ProductType', $product);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $product->getProductTranslations()->add($product);

        $productTranslation->setProduct($product);

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

        return $this->redirectToRoute('product_show', array('id' => $product->getId()));
    }

    return $this->render('product/new.html.twig', array(
                'product' => $product,
                'form' => $form->createView(),
    ));
}

我现在收到以下错误消息:
Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "AppBundle\Entity\Product#$productTranslations", got "string" instead.

更新2

在持久保存数据之前,ProductController newAction中的变量product中的var_dump()显示:
object(AppBundle\Entity\Product)[493]
  private 'id' => null
  private 'price' => float 3
  private 'productTranslations' =>
    object(Doctrine\Common\Collections\ArrayCollection)[494]
      private 'elements' =>
        array (size=4)
          'name' => string 'abc' (length=45)
          'description' => string 'alphabet' (length=35)
          'language' => string 'en' (length=2)
          0 =>
            object(AppBundle\Entity\ProductTranslation)[495]
              ...

最佳答案

该错误是不言自明的。 productTranslations必须是Array或arrayCollection。它是一个“字符串”。

因此在Product的构造函数中:

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

对于setter/getter,您可以使用:
public function addProductTranslation(AppBundle\Entity\ProductTranslation $pt)
{
    $this->productTranslations[] = $pt;
    $pt->setProduct($this);
    return $this;
}


public function removeProductTranslation(AppBundle\Entity\ProductTranslation  $pt)
{
    $this->productTranslations->removeElement($pt);
}

public function getProductTranslations()
{
    return $this->productTranslations;
}

编辑:
在带有Symfony2.3的YAML中,这是我正在使用的对象映射配置(以强调应在级联持久化的位置添加)。
//Product entity
oneToMany:
      productTranslations:
        mappedBy: product
        targetEntity: App\Bundle\...Bundle\Entity\ProductTranslation
        cascade:      [persist]

// ProductTranslation entity
manyToOne:
      product:
        targetEntity: App\Bundle\..Bundle\Entity\Product
        inversedBy: productTranslations
        joinColumn:
          name: product_id
          type: integer
          referencedColumnName: id
          onDelete: cascade

另外,请注意,由于setProductTranslation()add旨在替换它,因此在Product实体中不需要remove setter。

编辑2:

在Symfony2中,这是我处理带有集合的表单的方式:
class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('productPrice','number',array('required' => false))
                ->add('productTranslations', 'collection', array(
                    'type' => new ProducatTranslationType()

                    ))

            ;

        }

我不知道为什么您不在formType中指定collection。是Symfony的新版本吗?

09-25 16:57
查看更多