How specify parameter's format in Nelmio ApiDocBundle

ghanbari picture ghanbari · Oct 19, 2015 · Viewed 8.1k times · Source

I use input property of @ApiDoc annotation for specifieng of parameters of my api that are form's fields.

 * @ApiDoc(
 *      section="User",
 *      resource=true,
 *      input={
 *          "class"="Nik\UserBundle\Form\UserType",
 *      },
 *     ....

data_class of form is a entity that have constraint validation for properties.

I expect that nelmio api doc specify parameter format as validation constraints of entity, but format are empty.

enter image description here

How can i specify parameter formats in nelmio ApiDocBundle?


EDIT: maybe i write a bad question.

we can specify parsers for input & output, if we no specify parser for these, it call all parser for input & output, then all parser are called for UserType.

nelmio have a parser named ValidationParser that have a method named parseConstraint that set format for input & output, but this method is not called for my document, why?

Answer

chapay picture chapay · Oct 27, 2015

Format column is designed only for datetime, date and choice types.

For datetime and date it represents the date format like Y-m-d H:i:s and the array of choices for choice.

I haven't found any documentation about it, so I had to look through the source code. This is FormTypeParser class, the place where FormType is actually parsed and and you can see how format field is set.

In FormTypeParserTest class you can see how to use it. Just pass the string parameter with format name for one of the available types and the parser will handle it.

UPDATE: You are to define your constrains inside your FormType class.

For example:

class TestType extends AbstractType
{
    /**
     * @Assert\Type("string")
     * @Assert\Length(min="10", max="255")
     * @Assert\Regex("/^[^<>]+$/i")
     */
    private $title;

    /**
     * @Assert\Type("string")
     * @Assert\Length(min="10", max="255")
     * @Assert\Regex("/^[^<>]+$/i")
     */
    private $content;

    /**
     * @Assert\Date()
     */
    private $created;

    public function getName()
    {
        return 'test';
    }
}

will be parsed into:

enter image description here

ValidationParser in doParse() method finds all constrains defined in your FormType class and then executes parseConstraint() method for each of them.

You can also use FormTypeParser as I described above. For example:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('created', 'date', array('label' => 'Created', 'format' => 'yyyy-MM-dd'))
        ->add('color', 'choice', array('label' => 'Color', 'choices' => array('grey' => '#CCCCCC', 'red' => '#FF0000')))
        ->add('save', 'submit');
}

will be parsed as:

enter image description here

Hope it helps now!