Change form before submitting it
There are 2 entities: Client and Apps.
The association between client and app is done in entity Client
as follows:
class Clients {
/**
* App id
*
* @ManyToOne(targetEntity="Apps", inversedBy="clients", fetch="EXTRA_LAZY")
* @JoinColumn(name="app_id", referencedColumnName="id")
* @Assert\NotBlank(message="Código da aplicação inválido.")
*/
private $appId;
//...
}
The problem is that I do not want to expose any id
in the form, so each app besides id
, has the field reference
and it is this value that is sent by the form, see below the build of the form:
class ClientType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('reference', TextType::class, [
'mapped' => false
])
->add('title', TextType::class)
->add('firstname', TextType::class)
->add('lastname', TextType::class)
->add('phone', TextType::class)
->add('email', EmailType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Clients',
'csrf_protection' => false,
));
}
}
Notice that the field reference
is false, that is, it does not exist in my entity but the field appId
.
Ao save my form, the field appId
goes with the value null
and the following validation error occurs (the message was set via annotation in the code above):
Invalid application code.
In the controller, I have the following code:
//...
$data = json_decode($request->getContent(), true);
$client = new Clients();
$form = $this->createForm(ClientType::class, $client);
$form->submit($data);
if ($form->isValid()) {
//...
}
//...
Before submitting the form, I need to fill in the field appId
with a valid id
according to the reference sent through the field reference
.
1 answers
When I run into issues where I can't expose values in my application forms, what I do is simply fill in those values after the submitted form has been validated.
Then the code would look like this.
Form:
class ClientType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class)
->add('firstname', TextType::class)
->add('lastname', TextType::class)
->add('phone', TextType::class)
->add('email', EmailType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Clients',
'csrf_protection' => false,
));
}
}
Controller:
$form = $this->createForm(ClientType::class, new Clients());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$clients = $form->getData();
$clients->setAppId($appId);
$this-getDoctrine()->getManager()->persist($clients);
$this-getDoctrine()->getManager()->flush();
}