I\'ve been trying to set up a form with Symfony 2
.
So I followed the tutorial and I\'ve created a special class for creating the form and handling the
What you're trying to do here is creating a security hole: anyone would be able to inject any ID in the user_product_id
field and dupe you application. Not mentioning that it's useless to render a field and to not show it.
You can set a default value to user_product_id
in your entity:
/**
* @ORM\Annotations...
*/
private $user_product_id = 9000;
Another way is creating a Form Type Extension:
namespace App\Form\Extension;
// ...
class DefaultValueTypeExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (null !== $default = $options['default']) {
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
static function (FormEvent $event) use ($default) {
if (null === $event->getData()) {
$event->setData($default);
}
}
);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('default', null);
}
public static function getExtendedTypes(): iterable
{
yield FormType::class;
}
}
Now any possible value can be passed as default to any form field:
$form->add('user', null, ['default' => $this->getUser()]);
$form->add('user_product_id', null, ['default' => 1]);
This method is specially useful when you don't have a chance to hook into the initialization process of the bound object.