Reputation: 2375
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?
Upvotes: 2
Views: 967
Reputation: 59
Using this:
$isNew = $this->getSubject()->isNew();
throws an error:
Attempted to call an undefined method named "isNew" of class "SomeEntity".
So I used this instead:
if ($this->getSubject()->getId() === null) {
$isNew = true;
} else {
$isNew = false;
}
I hope it helps anyone facing the same issue in the future.
Upvotes: 2
Reputation: 16502
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.)
Upvotes: 0
Reputation: 211
On our side, we are doing the same way than the original post, but we would be happy to know that there is a cleaner solution :)
Event Subscriber looks too complex for a such small need.
Best regards, Christophe
Upvotes: 2
Reputation: 4092
I think the better way is to add an Event Subscriber To A Form Class you can view an example here:
http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html
thanks ;)
Upvotes: 0