Jiew Meng
Jiew Meng

Reputation: 88207

Symfony 2 Form Validation Groups

I am trying to use a form class for add & edit. In add mode, iconFile is required. In edit mode, iconFile is optional (to replace the current icon). How can I acheive this?

I tried setting a mode in the constructor

class ItemForm extends AbstractType {
    public function __construct($mode) {
        $this->mode = $mode;
    }

    public function getDefaultOptions(array $opts) {
        if ($mode == 'add') {
            return array('validation_groups' => array('Default', 'add'));
        } else {
            return array('validation_groups' => array('Default'));
        }
    }
}

// doctrine entity, data_class of form
class Item {
    /**
     * @Assert\NotBlank(groups={"add"})
     * @Assert\Image
     */
    protected $iconFile;
}

// creating the form in controller
$form = $this->createForm(new ItemForm($mode));

Problem is even in edit mode, I still need to select an image. HTML5 validation triggers

Upvotes: 3

Views: 3033

Answers (2)

L0rD59
L0rD59

Reputation: 116

You can do :

public function setDefaultOptions(OptionsResolver\OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'LIG\Bundle\UserBundle\Entity\User',
        'validation_groups' => function(Form\FormInterface $form) {
            $data= $form->getData();
            if($data->getId())
            {
                return array('Default', 'Edit');
            }
            else
            {
                return array('Default', 'Add');
            }
        },
    ));
}

Upvotes: 0

leek
leek

Reputation: 12121

In your ItemForm constructor, you are setting $mode to $this->mode, but you are then trying to access $mode from getDefaultOptions(). $mode obviously doesn't exist within this scope - try changing to the following:

public function getDefaultOptions(array $opts) {
    if ($this->mode == 'add') {
        return array('validation_groups' => array('Default', 'add'));
    } else {
        return array('validation_groups' => array('Default'));
    }
}

Upvotes: 4

Related Questions