Symfony2 Custom Form Type or Extension

Entity order exists with the Product property.

An OrderType form has been created that allows you to add a Product to an order.

It works, however it is not very interesting.

Instead of showing a simple product, it should be autocomplete.

However, when you select an autocomplete value, some additional fields must be populated with product information.

Choosing a product from autocomplete should fill in two additional fields with a price and a code.

A controller method for returning data has been created, and jquery has some convenient autocomplete functions available.

I know how to hack a solution directly into a form template, but I would like to make a reusable component.

The question is how to create a custom form or extension with this behavior?

class Order {
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="orders", cascade={"persist"})
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     */
    protected $product;  

    protected $quantity;
}

class Product {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="product")
     */
    protected $orders;

    protected $name;
    protected $price;
    protected $code;
}

class OrderType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('quantity')
            ->add('product');    
    }
}

OrderType :

    $builder
        ->add('ppprice', 'text', array('mapped' => false, 'data' => 2));

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA, function (FormEvent $event) use($builder) {
        $form = $event->getForm();
        $order = $event->getData();
        $builder
            ->add('ppprice', 'text', array('mapped' => false, 'data' => 21));
        $builder
            ->add('test', 'text', array('mapped' => false, 'data' => 21));
    }
    );

PRE_SET_DATA, , ppprice .

PRE_SET_DATA ?

0
1

FormEvent, POST_SUBMIT . ( jQuery ajax):
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

FormType. EventListener, , Closures .

Update:

, , PRE_SET_DATA. , $builder Closure. ( ) $form ->add Closure :

$builder->addEventListener(
        FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $form = $event->getForm();
        $order = $event->getData();

        $form->add('ppprice', 'text', array('mapped' => false, 'data' => 21));
        $form->add('test', 'text', array('mapped' => false, 'data' => 21));
    }
    );
+1

Source: https://habr.com/ru/post/1543577/


All Articles