0

我正在处理一个使用额外参数(额外字段/列)处理 N:M 关系的表单。这是我到目前为止所做的:

形式上OrdersType.php

class OrdersType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // $builder fields

        // $builder fields only need on edit form not in create
        if ($options['curr_action'] !== NULL)
        {
            $builder
                    // other $builder fields
                    ->add("orderProducts", "collection", array(
                        'type' => new OrdersHasProductType(),
                        'allow_add' => true,
                        'allow_delete' => true,
                        'by_reference' => false
            ));
        }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Tanane\FrontendBundle\Entity\Orders',
            'render_fieldset' => FALSE,
            'show_legend' => FALSE,
            'intention' => 'orders_form',
            'curr_action' => NULL
        ));
    }

    public function getName()
    {
        return 'orders';
    }

}

OrderHasProductType.php

class OrdersHasProductType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('product', 'text', array(
                    'required' => FALSE,
                    'label' => FALSE
                ))
                ->add('amount', 'text', array(
                    'required' => TRUE,
                    'label' => FALSE
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Tanane\FrontendBundle\Entity\OrderHasProduct',
            'intention' => 'order_has_product'
        ));
    }

    public function getName()
    {
        return 'order_has_product';
    }

}

最后是Orders.php实体OrdersHasProduct.php

class Orders {
    use IdentifiedAutogeneratedEntityTrait;
    // rest of fields for the entity 

    /**
     * @ORM\OneToMany(targetEntity="OrderHasProduct", mappedBy="order", cascade={"all"}) 
     */
    protected $orderProducts;

    protected $products;

    /**
     * @ORM\Column(name="deletedAt", type="datetime", nullable=true)
     */
    protected $deletedAt;

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

    public function getOrderProducts()
    {
        return $this->orderProducts;
    }

    public function getDeletedAt()
    {
        return $this->deletedAt;
    }

    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;
    }

    public function getProduct()
    {
        $products = new ArrayCollection();

        foreach ($this->orderProducts as $op)
        {
            $products[] = $op->getProduct();
        }

        return $products;
    }

    public function setProduct($products)
    {
        foreach ($products as $p)
        {
            $ohp = new OrderHasProduct();
            $ohp->setOrder($this);
            $ohp->setProduct($p);

            $this->addPo($ohp);
        }
    }

    public function getOrder()
    {
        return $this;
    }

    public function addPo($ProductOrder)
    {
        $this->orderProducts[] = $ProductOrder;
    }

    public function removePo($ProductOrder)
    {
        return $this->orderProducts->removeElement($ProductOrder);
    }

}

/**
 * @ORM\Entity
 * @ORM\Table(name="order_has_product")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @UniqueEntity(fields={"order", "product"})
 */
class OrderHasProduct {
    use IdentifiedAutogeneratedEntityTrait;

    /**
     * Hook timestampable behavior
     * updates createdAt, updatedAt fields
     */
    use TimestampableEntity;

    /**
     * @ORM\ManyToOne(targetEntity="\Tanane\FrontendBundle\Entity\Orders", inversedBy="orderProducts")
     * @ORM\JoinColumn(name="general_orders_id", referencedColumnName="id")
     */
    protected $order;

    /**
     * @ORM\ManyToOne(targetEntity="\Tanane\ProductBundle\Entity\Product", inversedBy="orderProducts")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     */
    protected $product;

    /**
     * @ORM\Column(type="integer", nullable=false)
     */
    protected $amount;

    /**
     * @ORM\Column(name="deletedAt", type="datetime", nullable=true)
     */
    protected $deletedAt;

    public function setOrder(\Tanane\FrontendBundle\Entity\Orders $order)
    {
        $this->order = $order;
    }

    public function getOrder()
    {
        return $this->order;
    }

    public function setProduct(\Tanane\ProductBundle\Entity\Product $product)
    {
        $this->product = $product;
    }

    public function getProduct()
    {
        return $this->product;
    }

    public function setAmount($amount)
    {
        $this->amount = $amount;
    }

    public function getAmount()
    {
        return $this->amount;
    }

    public function getDeletedAt()
    {
        return $this->deletedAt;
    }

    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;
    }

}

但是,当我尝试在控制器中使用此代码编辑订单时:

public function editAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();
    $order = $em->getRepository('FrontendBundle:Orders')->find($id);
    $type = $order->getPerson()->getPersonType() === 1 ? "natural" : "legal";

    $params = explode('::', $request->attributes->get('_controller'));
    $actionName = substr($params[1], 0, -6);

    $orderForm = $this->createForm(new OrdersType(), $order, array('action' => '#', 'method' => 'POST', 'register_type' => $type, 'curr_action' => $actionName));

    return array(
        "form" => $orderForm->createView(),
        'id' => $id,
        'entity' => $order
    );
}

我收到此错误:

表单的视图数据应为标量、数组或 \ArrayAccess 的实例类型,但它是 Proxies__CG__\Tanane\ProductBundle\Entity\Product 类的实例。您可以通过将“data_class”选项设置为“Proxies__CG__\Tanane\ProductBundle\Entity\Product”或添加将 Proxies__CG__\Tanane\ProductBundle\Entity\Product 类的实例转换为标量、数组或\ArrayAccess 的一个实例。

而且我找不到或不知道如何解决它,可以给我一些帮助吗?

4

1 回答 1

1

我认为这是因为这段代码

class OrdersHasProductType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('product', 'text', array(
                    'required' => FALSE,
                    'label' => FALSE
                ))
        ));
    }
    //...
}

意味着 Symfony 期望“产品”是“文本”类型的字段,但是当它调用getProduct()OrderHasProduct 时,它会得到一个产品对象(或产品的 Doctrine 代理,因为那时它还没有被加载)。Symfony Fields 继承自 Form/AbstractType,因此它们本质上就是 Forms,只有一个字段,因此会出现错误消息。

解决方案是将该字段设置为“实体”类型,或者创建一个仅给出产品名称的不同方法,例如getProductName()在 OrderHasProduct 上,然后将其用作字段后面的数据。

于 2014-09-22T13:03:37.503 回答