I'm creating a form with Symfony, its works perfectly but I have an issue with my validation, I made a field required and not blank but the error message isn't displayed when I submit the form with the input empty I don't know why
there is some part of code:
FormType:
use Symfony\Component\Validator\Constraints\NotBlank;
class AnnonceurType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
<some fields>
->add('phone', TextType::class, [
'required' => true,
'constraints' =>[
new NotBlank()
]
])
}
}
template of form:
{{ form_start(form) }}
<some fields>
<div class="form-group">
{{ form_label(form.phone, 'Phone number') }} *
{{ form_widget(form.phone, { 'attr': {'class': 'form-control'}}) }}
</div>
<div class="float-right">
<button type="submit" class="btn btn-primary">
{{ 'submit'|trans() }}
</button>
</div>
<div class="form-error">
{{ form_errors(form) }}
</div>
{{ form_end(form) }}
Someone know what's wrong with my code? thanks you
update: solved, it was because of the required, I added a novalidate and now its ok
The function form_errors
will output the errors associated with an specific field . In this case, as the root form doesn't have any error, it shows nothing.
You can either:
form_errors(form.phone)
.error_bubbling
in your form fields, so the error does bubble up to the parent and works as you expect. Additionally, as you seem to be using bootstrap, you can configure the form_theme
to use the bootstrap layout; it'll automatically output the field errors as part of the form_label
call, although you'll lose the ability to fine control their rendering.
if($form->issubmitted()){
$form['phone']->addError(new FormError('display message here'))
if($form->isValid()){
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.