简体   繁体   中英

Symfony2 Remove empty field in FormType

I have a onPreSubmit in my Symfony2 FormType.

public function onPreSubmit(FormEvent $event)
{
    $data = $event->getData();

    // Avoid sending empty RegisterProduct
    foreach ($data['registerProducts'] as $key => $registerProduct) {

        if (empty($registerProduct['quantity'])) {
            unset($data['registerProducts'][ $key ]);
        }
    }

    $event->setData($data);
}

The purpose is to remove an array value if a certain fiels in this one is empty (which works)

But when I set the data I have this error:

An exception occurred while executing 'INSERT INTO register_product ..... 
Integrity constraint violation: 1048 Column 'register_id' cannot be null

I don't understand why.

EDIT: I tried with onPostSubmit, but still have the same error

public function onPostSubmit(FormEvent $event)
{
    /** @var Register $register */
    $register = $event->getForm()->getData();

    foreach ($register->getRegisterProducts() as $registerProduct) {

        if ($registerProduct->getQuantity() < 1) {
            $register->removeRegisterProduct($registerProduct);
        }
    }
}

As say in comments, you should do it in postSubmit instead of preSubmit .

Example :

public function onPostSubmit(FormEvent $event) {
    $data = $event->getData();

    foreach ($data['registerProducts'] as $key => $registerProduct) {

        if (empty($registerProduct['quantity'])) {
            unset($data['registerProducts'][$key]);
        }
    }
});

If the SQL error persists, try to replace $event->getData() by $event->getForm()->getData() , the first returns data from the client.

EDIT

Unfortunately, the FormEvent doesn't work.

Also, I'll propose to use the prePersist and preUpdate hooks in your Entity.
It may not be an alternative for you if your question is only about the form context.

Usage :

/**
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity
 */
class YourEntity
{
    // ...

    /**
     *
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function manageProducts()
    {
        foreach ($this->getRegisterProducts() as $registerProduct) {
            if ($registerProduct->getQuantity() < 1) {
                $this->removeRegisterProduct($registerProduct);
            }
        }
    }
}

See the Events part of doctrine documentation.

I hope you can use this solution and that it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM