Creating a custom Type Guesser

Creating a custom Type Guesser

The Form component can guess the type and some options of a form field by using type guessers. The component already includes a type guesser using the assertions of the Validation component, but you can also add your own custom type guessers.

Form Type Guessers in the Bridges

Symfony also provides some form type guessers in the bridges:

  • Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser provided by the Doctrine bridge.

Create a PHPDoc Type Guesser

In this section, you are going to build a guesser that reads information about fields from the PHPDoc of the properties. At first, you need to create a class which implements Symfony\Component\Form\FormTypeGuesserInterface. This interface requires four methods:

[guessType()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormTypeGuesserInterface.php "Symfony\Component\Form\FormTypeGuesserInterface::guessType()")

Tries to guess the type of a field;

[guessRequired()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormTypeGuesserInterface.php "Symfony\Component\Form\FormTypeGuesserInterface::guessRequired()")

Tries to guess the value of the required option;

[guessMaxLength()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormTypeGuesserInterface.php "Symfony\Component\Form\FormTypeGuesserInterface::guessMaxLength()")

Tries to guess the value of the maxlength input attribute;

[guessPattern()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormTypeGuesserInterface.php "Symfony\Component\Form\FormTypeGuesserInterface::guessPattern()")

Tries to guess the value of the pattern input attribute.

Start by creating the class and these methods. Next, you’ll learn how to fill each in:

  1. // src/Form/TypeGuesser/PHPDocTypeGuesser.php
  2. namespace App\Form\TypeGuesser;
  3. use Symfony\Component\Form\FormTypeGuesserInterface;
  4. use Symfony\Component\Form\Guess\TypeGuess;
  5. use Symfony\Component\Form\Guess\ValueGuess;
  6. class PHPDocTypeGuesser implements FormTypeGuesserInterface
  7. {
  8. public function guessType($class, $property): ?TypeGuess
  9. {
  10. }
  11. public function guessRequired($class, $property): ?ValueGuess
  12. {
  13. }
  14. public function guessMaxLength($class, $property): ?ValueGuess
  15. {
  16. }
  17. public function guessPattern($class, $property): ?ValueGuess
  18. {
  19. }
  20. }

Guessing the Type

When guessing a type, the method returns either an instance of Symfony\Component\Form\Guess\TypeGuess or nothing, to determine that the type guesser cannot guess the type.

The TypeGuess constructor requires three options:

  • The type name (one of the form types);
  • Additional options (for instance, when the type is entity, you also want to set the class option). If no types are guessed, this should be set to an empty array;
  • The confidence that the guessed type is correct. This can be one of the constants of the Symfony\Component\Form\Guess\Guess class: LOW_CONFIDENCE, MEDIUM_CONFIDENCE, HIGH_CONFIDENCE, VERY_HIGH_CONFIDENCE. After all type guessers have been executed, the type with the highest confidence is used.

With this knowledge, you can implement the guessType() method of the PHPDocTypeGuesser:

  1. // src/Form/TypeGuesser/PHPDocTypeGuesser.php
  2. namespace App\Form\TypeGuesser;
  3. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  4. use Symfony\Component\Form\Extension\Core\Type\IntegerType;
  5. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  6. use Symfony\Component\Form\Extension\Core\Type\TextType;
  7. use Symfony\Component\Form\Guess\Guess;
  8. use Symfony\Component\Form\Guess\TypeGuess;
  9. class PHPDocTypeGuesser implements FormTypeGuesserInterface
  10. {
  11. public function guessType($class, $property): ?TypeGuess
  12. {
  13. $annotations = $this->readPhpDocAnnotations($class, $property);
  14. if (!isset($annotations['var'])) {
  15. return null; // guess nothing if the @var annotation is not available
  16. }
  17. // otherwise, base the type on the @var annotation
  18. switch ($annotations['var']) {
  19. case 'string':
  20. // there is a high confidence that the type is text when
  21. // @var string is used
  22. return new TypeGuess(TextType::class, [], Guess::HIGH_CONFIDENCE);
  23. case 'int':
  24. case 'integer':
  25. // integers can also be the id of an entity or a checkbox (0 or 1)
  26. return new TypeGuess(IntegerType::class, [], Guess::MEDIUM_CONFIDENCE);
  27. case 'float':
  28. case 'double':
  29. case 'real':
  30. return new TypeGuess(NumberType::class, [], Guess::MEDIUM_CONFIDENCE);
  31. case 'boolean':
  32. case 'bool':
  33. return new TypeGuess(CheckboxType::class, [], Guess::HIGH_CONFIDENCE);
  34. default:
  35. // there is a very low confidence that this one is correct
  36. return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE);
  37. }
  38. }
  39. protected function readPhpDocAnnotations(string $class, string $property): array
  40. {
  41. $reflectionProperty = new \ReflectionProperty($class, $property);
  42. $phpdoc = $reflectionProperty->getDocComment();
  43. // parse the $phpdoc into an array like:
  44. // ['var' => 'string', 'since' => '1.0']
  45. $phpdocTags = ...;
  46. return $phpdocTags;
  47. }
  48. // ...
  49. }

This type guesser can now guess the field type for a property if it has PHPDoc!

Guessing Field Options

The other three methods (guessMaxLength(), guessRequired() and guessPattern()) return a Symfony\Component\Form\Guess\ValueGuess instance with the value of the option. This constructor has 2 arguments:

  • The value of the option;
  • The confidence that the guessed value is correct (using the constants of the Guess class).

null is guessed when you believe the value of the option should not be set.

Caution

You should be very careful using the guessPattern() method. When the type is a float, you cannot use it to determine a min or max value of the float (e.g. you want a float to be greater than 5, 4.512313 is not valid but length(4.512314) > length(5) is, so the pattern will succeed). In this case, the value should be set to null with a MEDIUM_CONFIDENCE.

Registering a Type Guesser

If you’re using autowire and autoconfigure, you’re done! Symfony already knows and is using your form type guesser.

If you’re not using autowire and autoconfigure, register your service manually and tag it with form.type_guesser:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Form\TypeGuesser\PHPDocTypeGuesser:
    5. tags: [form.type_guesser]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Form\TypeGuesser\PHPDocTypeGuesser">
    9. <tag name="form.type_guesser"/>
    10. </service>
    11. </services>
    12. </container>
  • PHP

    1. // config/services.php
    2. use App\Form\TypeGuesser\PHPDocTypeGuesser;
    3. $container->register(PHPDocTypeGuesser::class)
    4. ->addTag('form.type_guesser')
    5. ;

Registering a Type Guesser in the Component

If you’re using the Form component standalone in your PHP project, use [addTypeGuesser()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormFactoryBuilder.php "Symfony\Component\Form\FormFactoryBuilder::addTypeGuesser()") or [addTypeGuessers()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormFactoryBuilder.php "Symfony\Component\Form\FormFactoryBuilder::addTypeGuessers()") of the FormFactoryBuilder to register new type guessers:

  1. use App\Form\TypeGuesser\PHPDocTypeGuesser;
  2. use Symfony\Component\Form\Forms;
  3. $formFactory = Forms::createFormFactoryBuilder()
  4. // ...
  5. ->addTypeGuesser(new PHPDocTypeGuesser())
  6. ->getFormFactory();
  7. // ...

Tip

Run the following command to verify that the form type guesser was successfully registered in the application:

  1. $ php bin/console debug:form

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.