Reputation: 31548
I am not able to understand why Symfony does this.
Suppose i have the UserFormType class
->add(username);
->add(datecreated);
Now i don't show dateCreated in my template then symfony sets the DateCreated
to null
which overwrites the database value.
I want to know what the problem in not setting that value to null and just have original value if its not in the template
Upvotes: 1
Views: 1973
Reputation: 53
This is an old topic but I ran into the same situation and the easiest and cleanest way for me to handle this was to remove the field from the form when you don't want to do anything with it.
For example I want to show the list of groups a user is attached to but some other user can't see them. The result was any changes for those users would remove the group they already had.
The solution:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
$this->onPreSubmit($event);
}
);
.....
}
public function onPreSubmit(FormEvent $event)
{
$params = $event->getData();
if (!isset($params['groups'])) {
$event->getForm()->remove('groups');
}
}
Now your form will reject the groups if it is set, to avoid that you can add to your form the options 'allow_extra_fields' => true
. It will pass validation and do nothing with it.
Although it is neat I am not a big fan but I can't see any other solution, or you will have to build the html yourself and the action/service to handle validation without symfony built in form system.
Upvotes: 1
Reputation: 136
From the documentation: Additionally, if there are any fields on the form that aren't included in the submitted data, those fields will be explicitly set to null.
so you must render all your fields otherwise they will be set to null.
You can either not add it in the form and Symfony will leave that value alone on update, I'm guessing you set dateCreated in your code anyway so you don't need the Forms library trying to update that field.
The other option is to add the field as a hidden field ->add('dateCreated', 'hidden')
you will need to render the field in your template and Symfony will keep around the dateCreated data. If you are rendering each row you can use form_rest(form)
in your twig to render all the missing fields.
Upvotes: 1