Reputation: 35
I have the following form:
class TestFormType extends AbstractType
{
protected $testArgument;
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (isset($options['testArgument'])) {
$this->testArgument = $options['testArgument'];
}
$builder->add('textField', 'Symfony\Component\Form\Extension\Core\Type\TextType');
}
public function configureOptions(OptionsResolver $optionsResolver)
{
$optionsResolver->setRequired('testArgument');
$optionsResolver->setDefaults(
array(
'data_class' => get_class($this->testArgument)
)
);
}
}
I am passing the value for the testArgument
attribute via form options (Symfony 3 modifications), but when is comes to get the class name of the attribute to set the 'data_class'
inside configureOptions
method, it is always null
. Basically I need to depend on the form type class attribute inside the configureOptions
method.Can someone please help me out here to the right direction ?
Upvotes: 1
Views: 2950
Reputation: 3686
You should pass the *Type __constructor for use to
use App\Entity\Blog;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class BlogType extends AbstractType {
private $someDependency;
public function __construct($someDependency)
{
$this->someDependency = $someDependency;
}
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'empty_data' => new Blog($this->someDependency),
]);
} }
Upvotes: 1
Reputation: 35
I had to pass the dependency in configureOptions
method from the form factory create
method itself:
$form = $this->factory->create(
'app\TestBundle\Form\Type\TestFormType',
$this->testArgument,
array(
'data_class' => get_class($this->testArgument)
)
);
as it would not be set by the default settings in the form type and had to refactor the form type class as follows:
class TestFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('textField', 'Symfony\Component\Form\Extension\Core\Type\TextType');
}
}
Upvotes: 1