Search code examples
formssymfonydoctrine-ormsymfony-sonata

Make field required only for new object


There is form with some fields:

protected function configureFormFields(FormMapper $formMapper)
{
    $isNew = !$this->getRequest()->get($this->getIdParameter());

    $formMapper
        ->add('title')
        ->add('file', 'file', array('required' => $isNew))
    ;
}

Is there better way to make field required only for new objects?


Solution

  • You can use the Sonata isNew() function found here from the docs:

    protected function configureFormFields(FormMapper $formMapper)
    {
        $isNew = $this->getSubject()->isNew();
    
        $formMapper
            ->add('title')
            ->add('file', 'file', array('required' => $isNew))
        ;
    }
    

    However there's some issues with $this->getSubject() not returning the right things. There is a pull request open to fix these problems (I've linked to my comment with instructions on how to use the branch in its current state.)