Thomas Landauer
Thomas Landauer

Reputation: 8355

Symfony2 Field Type Guessing: When is <textarea> chosen (over <input type="text">)?

Not declaring the field type brings the advantage that Symfony infers the required and maxlength attribute from validation rules, as explained here: http://symfony.com/doc/current/book/forms.html#field-type-options-guessing

However, I can't find a way to make Symfony 2.8.2 "guess" a <textarea> instead of an <input type="text"> :-(

My first idea was to increase the allowed length, but even with Length: max: 100000 in validation.yml, Symfony is unimpressed and just gives me <input type="text" maxlength="100000" />.

EDIT: @chalasr: I'm talking about an entity which is not mapped to the database. Sorry for not mentioning that earlier!

Upvotes: 3

Views: 1137

Answers (1)

chalasr
chalasr

Reputation: 13167

The FormBuilder guesses the field type by checking the type in the mapping of the corresponding property, in the entity.

Use text instead of string as type of your column mapping, and the FormBuilder will use a textarea instead of an input.

Example :

/**
 * @ORM\Column(type="text")
 */
protected $field;

Output with $builder->add('field'); :

<textarea id="entity_field" name="entity[field]" required="required"></textarea>

For more info look at the Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser.

Update

So, you don't use a mapped class.

Look at the FormBuilder, as you can see, if there is no corresponding Guesser found, the form type will be a TextType (input text).

Otherwise, there is 3 different Guesser:

Because your class is not mapped, Symfony will use the ValidatorTypeGuesser to guess the type of your field.

This Guesser looks for constraints in your class.
For example, if your field has a Type constraint with type integer, the NumberType will be used and an input type number will be rendered.

My first idea was to use a Length constraint with a big min-length.

But, after many tries and looks in classes, it seems the TextareaType is never guessed, unless your class is mapped and your field has text as type (DoctrineTypeGuesser is used) .

So, without a mapped class, Symfony cannot create a textarea from type guessing.

For more informations look at the ValidatorTypeGuesser::guessTypeForConstraint.

See also the Form Type Guessing chapter of documentation, it shows how create your own TypeGuesser with a good example.

Upvotes: 4

Related Questions