ReynierPM
ReynierPM

Reputation: 18660

Form edition for a N:M relationship with extra fields is not working

I'm working on a form that handle N:M relationship with an extra parameter (extra field/column). This is what I've done until now:

In OrdersType.php form:

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';
    }

}

In 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';
    }

}

And finally this is Orders.php and OrdersHasProduct.php entities:

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;
    }

}

But when I try to edit a order with this code in my controller:

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
    );
}

I get this error:

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class Proxies__CG__\Tanane\ProductBundle\Entity\Product. You can avoid this error by setting the "data_class" option to "Proxies__CG__\Tanane\ProductBundle\Entity\Product" or by adding a view transformer that transforms an instance of class Proxies__CG__\Tanane\ProductBundle\Entity\Product to scalar, array or an instance of \ArrayAccess.

And I don't find or know how to fix it, can any give me some help?

Upvotes: 0

Views: 100

Answers (1)

frumious
frumious

Reputation: 1575

I think this is happening because this code

class OrdersHasProductType extends AbstractType {

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

means that Symfony is expecting "product" to be a field of type "text", but when it calls getProduct() on the OrderHasProduct it gets a Product object (or a Doctrine Proxy to a Product, since it's not been loaded at that point). Symfony Fields inherit from Form/AbstractType, so they're essentially Forms in their own right, with just one field, hence the error message.

The solution is either to make that field of type "entity", or to create a different method which only gives the name of the Product, e.g. getProductName() on OrderHasProduct, and then use that as the data behind the field.

Upvotes: 1

Related Questions