Accessing the bound's entity to a Symfony form type inside the buildForm function
Published on 2021-03-16 • Modified on 2021-03-16
In this snippet, we will see how to access the bound's entity to a Symfony form type inside the buildForm
function. We just have to call the getData()
function on the form builder object. This is useful when wanting to create dynamic forms depending on the entity current state. Note that if your form type is instantiated multiple times in a given request, you should use events to modify it (check the documentation link below).
<?php
declare(strict_types=1);
// src/Form/ArticleType.php
namespace App\Form;
use App\Entity\Article;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* Fake article form for snippet30.
*/
final class ArticleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$article = $builder->getData();
if (!$article instanceof Article) {
throw new \RuntimeException('Invalid entity.');
}
if ($article->isArticle() || $article->isSnippet()) {
$builder->add('slug', TextType::class, ['constraints' => [new NotBlank()]]);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'csrf_protection' => false,
'data_class' => Article::class,
'constraints' => [
new UniqueEntity(['fields' => ['slug']]),
],
]);
}
}
More on Stackoverflow Read the doc Random snippet