1
votes

I can't set the default value of a form field that has a DataTransformer attached to it.

Let's take the example from the official documentation on DataTransformers:

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('description', TextareaType::class)
        ->add('issue', TextType::class)
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Task::class,
    ));
}

In the example, a ModelTransformer is added to the 'issue' field, transforming the Issue object into a string (the issue number) when rendering the form, and transforming it back to an Issue upon form submission.

Now I'm setting a default value for the issue field through the builder options:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $issue = $options['issue']; //$issue contains an Issue Object from the controller
    $builder
        ->add('description', TextareaType::class)
        ->add('issue', TextType::class, array(
            'data' => $issue
        ))
    ;
}

When rendering the form I get the following error:

The form's view data is expected to be an instance of class AppBundle/Entity/Issue, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of AppBundle/Entity/Issue.

  • Dumping $issue returns an Issue object
  • Setting the data_class option to null as suggested returns the same error
  • Passing $issue->getId() instead of $issue gets me the following error: "Call to a member function getId() on integer"

I really don't understand this error, I hope you'll be able to help !

1
I think you're wrong. You seem to want to pass an object to a text field which by definition can only take a string as a parameter. Maybe it works if your object has a method __toString() but I do not think it's logical. - Alphonse D.
@AlphonseD. I thought so, but passing $issue->getId() instead of $issue as 'data' value throws another Exception saying that getId() can't be called on string values whereas it IS NOT a string when dumped in the buildForm() function so I was really confused. - alpadev

1 Answers

0
votes

IssueSelectorType (child of TextType) expects a string as initial value and the data transformer inside, converts this to issue instance, so you need to pass the issue id instead.

However, data option does not works as default value always:

The default values for form fields are taken directly from the underlying data structure. The data option overrides this default value (Doc.)

See this answer for more details: How to set a default value in a Symfony 2 form field?