Symfony2 validation form without class

2019-07-27 08:45发布

I'm trying to make a search form without an entity.

Controller:

public function SearchFormAction() {
    $collectionConstraint = new Collection(array(
        'size' => new MinLength(3),
    ));

    $searchform = $this->createFormBuilder(null, array(
        'validation_constraint' => $collectionConstraint,
    ))
            ->add('min_range')
            ->add('max_range')
            ->add('bedrooms')
            ->add('bathrooms')
            ->add('size')
            ->add('user')
        ->getForm()
    ;

    return $this->render("RealBundle:User:search.html.twig", array(
                'searchform'  => $searchform->createView(),
            ));
}

View:

<div id="dialog" title="Advanced Search">
<form action="{{ path('searchresults') }}" method="post" {{ form_enctype(searchform) }} id="frmSearch">
<fieldset>
        <h3>Properties</h3>
        <div class="form-search-item">
    {{ form_label(searchform.min_range, 'Price Range') }} {{ form_widget(searchform.min_range) }} to {{ form_widget(searchform.max_range) }}
    {{ form_widget(searchform.min_range) }}
         </div>
         <div class="form-search-item">
            {{ form_label(searchform.bedrooms, 'Bedrooms') }}: {{ form_widget(searchform.bedrooms) }}
         </div>
         <div class="form-search-item">
            {{ form_label(searchform.bedrooms, 'Bathrooms') }}: {{ form_widget(searchform.bathrooms) }}
         </div>
         <div class="form-search-item">
            {{ form_label(searchform.bedrooms, 'Size') }}: {{ form_widget(searchform.size) }}
         </div>
        <h3>User</h3>
        <div class="form-search-item">
            {{ form_label(searchform.user, 'User') }}: {{ form_widget(searchform.user) }}
         </div>
        {{ form_rest(searchform) }}
        <input type="submit" value="Search">
</fieldset>
</form>

I've try with another validations like MinLength, MaxLenght, Type and nothing works for me, what am I doing wrong? I want to validate, range, bedrooms, bathrooms, size as integers, and a minLenght for user.

Tnx and sorry for my english.

1条回答
【Aperson】
2楼-- · 2019-07-27 09:29

Your validation seems to be working in my test. But you're missing the error messages in the template.

You need

{{ form_errors(form) }}

to render global errors, and then for each field you can display its errors, eg

{{ form_errors(form.size) }}

Then as if by magic you should see your error messages. Although not having seen your controller I can't be sure you're binding and calling isValid.

If you're still having problems then please post your controller too.

查看更多
登录 后发表回答