Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Components
  4. Form
  5. Creating a custom Type Guesser
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Create a PHPDoc Type Guesser
    • Guessing the Type
    • Guessing Field Options
  • Registering a Type Guesser

Creating a custom Type Guesser

Edit this page

Warning: You are browsing the documentation for Symfony 2.5, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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:

  • PropelTypeGuesser provided by the Propel1 bridge;
  • 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 FormTypeGuesserInterface. This interface requires 4 methods:

  • guessType() - tries to guess the type of a field;
  • guessRequired() - tries to guess the value of the required option;
  • guessMaxLength() - tries to guess the value of the max_length option;
  • guessPattern() - tries to guess the value of the pattern option.

Start by creating the class and these methods. Next, you'll learn how to fill each on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace Acme\Form;

use Symfony\Component\Form\FormTypeGuesserInterface;

class PHPDocTypeGuesser implements FormTypeGuesserInterface
{
    public function guessType($class, $property)
    {
    }

    public function guessRequired($class, $property)
    {
    }

    public function guessMaxLength($class, $property)
    {
    }

    public function guessPattern($class, $property)
    {
    }
}

Guessing the Type

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

The TypeGuess constructor requires 3 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 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 easily implement the guessType method of the PHPDocTypeGuesser:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
namespace Acme\Form;

use Symfony\Component\Form\Guess\Guess;
use Symfony\Component\Form\Guess\TypeGuess;

class PHPDocTypeGuesser implements FormTypeGuesserInterface
{
    public function guessType($class, $property)
    {
        $annotations = $this->readPhpDocAnnotations($class, $property);

        if (!isset($annotations['var'])) {
            return; // guess nothing if the @var annotation is not available
        }

        // otherwise, base the type on the @var annotation
        switch ($annotations['var']) {
            case 'string':
                // there is a high confidence that the type is text when
                // @var string is used
                return new TypeGuess('text', array(), Guess::HIGH_CONFIDENCE);

            case 'int':
            case 'integer':
                // integers can also be the id of an entity or a checkbox (0 or 1)
                return new TypeGuess('integer', array(), Guess::MEDIUM_CONFIDENCE);

            case 'float':
            case 'double':
            case 'real':
                return new TypeGuess('number', array(), Guess::MEDIUM_CONFIDENCE);

            case 'boolean':
            case 'bool':
                return new TypeGuess('checkbox', array(), Guess::HIGH_CONFIDENCE);

            default:
                // there is a very low confidence that this one is correct
                return new TypeGuess('text', array(), Guess::LOW_CONFIDENCE);
        }
    }

    protected function readPhpDocAnnotations($class, $property)
    {
        $reflectionProperty = new \ReflectionProperty($class, $property);
        $phpdoc = $reflectionProperty->getDocComment();

        // parse the $phpdoc into an array like:
        // array('type' => 'string', 'since' => '1.0')
        $phpdocTags = ...;

        return $phpdocTags;
    }
}

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

Guessing Field Options

The other 3 methods (guessMaxLength, guessRequired and guessPattern) return a 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

The last thing you need to do is registering your custom type guesser by using addTypeGuesser() or addTypeGuessers():

1
2
3
4
5
6
7
8
9
use Symfony\Component\Form\Forms;
use Acme\Form\PHPDocTypeGuesser;

$formFactory = Forms::createFormFactoryBuilder()
    // ...
    ->addTypeGuesser(new PHPDocTypeGuesser())
    ->getFormFactory();

// ...

Note

When you use the Symfony framework, you need to register your type guesser and tag it with form.type_guesser. For more information see the tag reference.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Symfony Code Performance Profiling

Symfony Code Performance Profiling

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Krasimir Bosilkov, a Symfony contributor

Thanks Krasimir Bosilkov (@kbosilkov) for being a Symfony contributor

6 commits • 360 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia