How can I display required fields error (validation) message with symfony formbuilder?
PagesController.php
$id = $request->request->get('id');
$target = $request->request->get('target');
$EntityName = 'App\Entity\' . ucwords($slug);
$em = $this->getDoctrine()->getManager();
$cmf = $em->getMetadataFactory();
$classes = $cmf->getMetadataFor($EntityName);
if($request->request->get('target')){
$item = new $EntityName();
$item= $this->getDoctrine()->getRepository($EntityName)->find($id);
$formBuilder = $this->createFormBuilder($item);
foreach ($classes->fieldMappings as $fieldMapping) {
$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control'), 'required' => true,));
}
$formBuilder->add('cancel', ButtonType::class, array('label' => 'Cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'target' => $target,
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
} else {
$em = $this->getDoctrine()->getManager();
foreach ($classes->fieldMappings as $fieldMapping) {
$func = 'set'.$fieldMapping['fieldName'];
$args = $data['form['.$fieldMapping['fieldName'].']'];
$entity->$func($args);
}
$em->persist($entity);
$em->flush();
$response = new JsonResponse(array('id' => $data['form[id]']), 200);
return $response;
}
form.html.twig
<section class="content-header" style="margin-bottom:20px">
<h1 style="float:left;margin-bottom:30px">Create Entry </h1>
</section>
<section class="content" style="clear:left">
<div class="form-group">
{{ form_start(form) }}
{{ form_end(form) }}
</section>
My form is working well, when I fill it out and press the "Save" Button it is stored in the database.
When I leave all fields empty and press "Save" nothing is happening and I get a 500 Error
An exception occurred while executing 'INSERT INTO members (username,
password, email, is_active) VALUES (?, ?, ?, ?)' with params ["",
null, "", "1"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'password' cannot be null
This is actually fine, because the fields are required, but the errors are not displayed in my form, even if I added "required" = "true".
json symfony twig formbuilder requiredfieldvalidator
|
show 2 more comments
PagesController.php
$id = $request->request->get('id');
$target = $request->request->get('target');
$EntityName = 'App\Entity\' . ucwords($slug);
$em = $this->getDoctrine()->getManager();
$cmf = $em->getMetadataFactory();
$classes = $cmf->getMetadataFor($EntityName);
if($request->request->get('target')){
$item = new $EntityName();
$item= $this->getDoctrine()->getRepository($EntityName)->find($id);
$formBuilder = $this->createFormBuilder($item);
foreach ($classes->fieldMappings as $fieldMapping) {
$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control'), 'required' => true,));
}
$formBuilder->add('cancel', ButtonType::class, array('label' => 'Cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'target' => $target,
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
} else {
$em = $this->getDoctrine()->getManager();
foreach ($classes->fieldMappings as $fieldMapping) {
$func = 'set'.$fieldMapping['fieldName'];
$args = $data['form['.$fieldMapping['fieldName'].']'];
$entity->$func($args);
}
$em->persist($entity);
$em->flush();
$response = new JsonResponse(array('id' => $data['form[id]']), 200);
return $response;
}
form.html.twig
<section class="content-header" style="margin-bottom:20px">
<h1 style="float:left;margin-bottom:30px">Create Entry </h1>
</section>
<section class="content" style="clear:left">
<div class="form-group">
{{ form_start(form) }}
{{ form_end(form) }}
</section>
My form is working well, when I fill it out and press the "Save" Button it is stored in the database.
When I leave all fields empty and press "Save" nothing is happening and I get a 500 Error
An exception occurred while executing 'INSERT INTO members (username,
password, email, is_active) VALUES (?, ?, ?, ?)' with params ["",
null, "", "1"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'password' cannot be null
This is actually fine, because the fields are required, but the errors are not displayed in my form, even if I added "required" = "true".
json symfony twig formbuilder requiredfieldvalidator
1
This looks very much like a magic "create the database table and form on-the-fly", which is an anti-pattern. I strongly suggest you define an Entity and a form Type class. If you have an assertion on the entity it will be checked by the form component automatically. Otherwise you will have to call the validator service yourself: symfony.com/doc/current/… The attribute you set is just the HTML attribute, no validation is assigned just by setting'required' => true
. See symfony.com/doc/current/reference/forms/types/…
– YetiCGN
Nov 21 '18 at 11:29
@YetiCGN Thank you for your message. This is not on the fly, I worked very long to realize this.
– Jarla
Nov 21 '18 at 11:32
1
What I mean is, your model and form are created programatically on-the-fly at runtime. They can be anything and you cannot utilize language or framework features to give semantic meaning and check for things like data type. I know it's tempting to have just one magic method do everything no matter what you feed it, but it's an anti-pattern.
– YetiCGN
Nov 21 '18 at 11:35
@YetiCGN I have an entity defined, I just updated my question with some more information. What is a form type Class? Do you mean "TextType::class, PasswordType::class" etc...?
– Jarla
Nov 21 '18 at 11:38
I mean "a form can be created and used directly in a controller. However, a better practice is to build the form in a separate, standalone PHP class" -> symfony.com/doc/current/forms.html#creating-form-classes
– YetiCGN
Nov 21 '18 at 12:17
|
show 2 more comments
PagesController.php
$id = $request->request->get('id');
$target = $request->request->get('target');
$EntityName = 'App\Entity\' . ucwords($slug);
$em = $this->getDoctrine()->getManager();
$cmf = $em->getMetadataFactory();
$classes = $cmf->getMetadataFor($EntityName);
if($request->request->get('target')){
$item = new $EntityName();
$item= $this->getDoctrine()->getRepository($EntityName)->find($id);
$formBuilder = $this->createFormBuilder($item);
foreach ($classes->fieldMappings as $fieldMapping) {
$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control'), 'required' => true,));
}
$formBuilder->add('cancel', ButtonType::class, array('label' => 'Cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'target' => $target,
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
} else {
$em = $this->getDoctrine()->getManager();
foreach ($classes->fieldMappings as $fieldMapping) {
$func = 'set'.$fieldMapping['fieldName'];
$args = $data['form['.$fieldMapping['fieldName'].']'];
$entity->$func($args);
}
$em->persist($entity);
$em->flush();
$response = new JsonResponse(array('id' => $data['form[id]']), 200);
return $response;
}
form.html.twig
<section class="content-header" style="margin-bottom:20px">
<h1 style="float:left;margin-bottom:30px">Create Entry </h1>
</section>
<section class="content" style="clear:left">
<div class="form-group">
{{ form_start(form) }}
{{ form_end(form) }}
</section>
My form is working well, when I fill it out and press the "Save" Button it is stored in the database.
When I leave all fields empty and press "Save" nothing is happening and I get a 500 Error
An exception occurred while executing 'INSERT INTO members (username,
password, email, is_active) VALUES (?, ?, ?, ?)' with params ["",
null, "", "1"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'password' cannot be null
This is actually fine, because the fields are required, but the errors are not displayed in my form, even if I added "required" = "true".
json symfony twig formbuilder requiredfieldvalidator
PagesController.php
$id = $request->request->get('id');
$target = $request->request->get('target');
$EntityName = 'App\Entity\' . ucwords($slug);
$em = $this->getDoctrine()->getManager();
$cmf = $em->getMetadataFactory();
$classes = $cmf->getMetadataFor($EntityName);
if($request->request->get('target')){
$item = new $EntityName();
$item= $this->getDoctrine()->getRepository($EntityName)->find($id);
$formBuilder = $this->createFormBuilder($item);
foreach ($classes->fieldMappings as $fieldMapping) {
$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control'), 'required' => true,));
}
$formBuilder->add('cancel', ButtonType::class, array('label' => 'Cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'target' => $target,
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
} else {
$em = $this->getDoctrine()->getManager();
foreach ($classes->fieldMappings as $fieldMapping) {
$func = 'set'.$fieldMapping['fieldName'];
$args = $data['form['.$fieldMapping['fieldName'].']'];
$entity->$func($args);
}
$em->persist($entity);
$em->flush();
$response = new JsonResponse(array('id' => $data['form[id]']), 200);
return $response;
}
form.html.twig
<section class="content-header" style="margin-bottom:20px">
<h1 style="float:left;margin-bottom:30px">Create Entry </h1>
</section>
<section class="content" style="clear:left">
<div class="form-group">
{{ form_start(form) }}
{{ form_end(form) }}
</section>
My form is working well, when I fill it out and press the "Save" Button it is stored in the database.
When I leave all fields empty and press "Save" nothing is happening and I get a 500 Error
An exception occurred while executing 'INSERT INTO members (username,
password, email, is_active) VALUES (?, ?, ?, ?)' with params ["",
null, "", "1"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'password' cannot be null
This is actually fine, because the fields are required, but the errors are not displayed in my form, even if I added "required" = "true".
json symfony twig formbuilder requiredfieldvalidator
json symfony twig formbuilder requiredfieldvalidator
edited Nov 21 '18 at 11:36
Jarla
asked Nov 21 '18 at 11:10
JarlaJarla
2,35711639
2,35711639
1
This looks very much like a magic "create the database table and form on-the-fly", which is an anti-pattern. I strongly suggest you define an Entity and a form Type class. If you have an assertion on the entity it will be checked by the form component automatically. Otherwise you will have to call the validator service yourself: symfony.com/doc/current/… The attribute you set is just the HTML attribute, no validation is assigned just by setting'required' => true
. See symfony.com/doc/current/reference/forms/types/…
– YetiCGN
Nov 21 '18 at 11:29
@YetiCGN Thank you for your message. This is not on the fly, I worked very long to realize this.
– Jarla
Nov 21 '18 at 11:32
1
What I mean is, your model and form are created programatically on-the-fly at runtime. They can be anything and you cannot utilize language or framework features to give semantic meaning and check for things like data type. I know it's tempting to have just one magic method do everything no matter what you feed it, but it's an anti-pattern.
– YetiCGN
Nov 21 '18 at 11:35
@YetiCGN I have an entity defined, I just updated my question with some more information. What is a form type Class? Do you mean "TextType::class, PasswordType::class" etc...?
– Jarla
Nov 21 '18 at 11:38
I mean "a form can be created and used directly in a controller. However, a better practice is to build the form in a separate, standalone PHP class" -> symfony.com/doc/current/forms.html#creating-form-classes
– YetiCGN
Nov 21 '18 at 12:17
|
show 2 more comments
1
This looks very much like a magic "create the database table and form on-the-fly", which is an anti-pattern. I strongly suggest you define an Entity and a form Type class. If you have an assertion on the entity it will be checked by the form component automatically. Otherwise you will have to call the validator service yourself: symfony.com/doc/current/… The attribute you set is just the HTML attribute, no validation is assigned just by setting'required' => true
. See symfony.com/doc/current/reference/forms/types/…
– YetiCGN
Nov 21 '18 at 11:29
@YetiCGN Thank you for your message. This is not on the fly, I worked very long to realize this.
– Jarla
Nov 21 '18 at 11:32
1
What I mean is, your model and form are created programatically on-the-fly at runtime. They can be anything and you cannot utilize language or framework features to give semantic meaning and check for things like data type. I know it's tempting to have just one magic method do everything no matter what you feed it, but it's an anti-pattern.
– YetiCGN
Nov 21 '18 at 11:35
@YetiCGN I have an entity defined, I just updated my question with some more information. What is a form type Class? Do you mean "TextType::class, PasswordType::class" etc...?
– Jarla
Nov 21 '18 at 11:38
I mean "a form can be created and used directly in a controller. However, a better practice is to build the form in a separate, standalone PHP class" -> symfony.com/doc/current/forms.html#creating-form-classes
– YetiCGN
Nov 21 '18 at 12:17
1
1
This looks very much like a magic "create the database table and form on-the-fly", which is an anti-pattern. I strongly suggest you define an Entity and a form Type class. If you have an assertion on the entity it will be checked by the form component automatically. Otherwise you will have to call the validator service yourself: symfony.com/doc/current/… The attribute you set is just the HTML attribute, no validation is assigned just by setting
'required' => true
. See symfony.com/doc/current/reference/forms/types/…– YetiCGN
Nov 21 '18 at 11:29
This looks very much like a magic "create the database table and form on-the-fly", which is an anti-pattern. I strongly suggest you define an Entity and a form Type class. If you have an assertion on the entity it will be checked by the form component automatically. Otherwise you will have to call the validator service yourself: symfony.com/doc/current/… The attribute you set is just the HTML attribute, no validation is assigned just by setting
'required' => true
. See symfony.com/doc/current/reference/forms/types/…– YetiCGN
Nov 21 '18 at 11:29
@YetiCGN Thank you for your message. This is not on the fly, I worked very long to realize this.
– Jarla
Nov 21 '18 at 11:32
@YetiCGN Thank you for your message. This is not on the fly, I worked very long to realize this.
– Jarla
Nov 21 '18 at 11:32
1
1
What I mean is, your model and form are created programatically on-the-fly at runtime. They can be anything and you cannot utilize language or framework features to give semantic meaning and check for things like data type. I know it's tempting to have just one magic method do everything no matter what you feed it, but it's an anti-pattern.
– YetiCGN
Nov 21 '18 at 11:35
What I mean is, your model and form are created programatically on-the-fly at runtime. They can be anything and you cannot utilize language or framework features to give semantic meaning and check for things like data type. I know it's tempting to have just one magic method do everything no matter what you feed it, but it's an anti-pattern.
– YetiCGN
Nov 21 '18 at 11:35
@YetiCGN I have an entity defined, I just updated my question with some more information. What is a form type Class? Do you mean "TextType::class, PasswordType::class" etc...?
– Jarla
Nov 21 '18 at 11:38
@YetiCGN I have an entity defined, I just updated my question with some more information. What is a form type Class? Do you mean "TextType::class, PasswordType::class" etc...?
– Jarla
Nov 21 '18 at 11:38
I mean "a form can be created and used directly in a controller. However, a better practice is to build the form in a separate, standalone PHP class" -> symfony.com/doc/current/forms.html#creating-form-classes
– YetiCGN
Nov 21 '18 at 12:17
I mean "a form can be created and used directly in a controller. However, a better practice is to build the form in a separate, standalone PHP class" -> symfony.com/doc/current/forms.html#creating-form-classes
– YetiCGN
Nov 21 '18 at 12:17
|
show 2 more comments
1 Answer
1
active
oldest
votes
So when using the form builder, you have access to:
$form->isSubmitted()
and
$form->isValid()
As a result you can do something like:
if ($form->isSubmitted() && $form->isValid()) {
// save to database
}
We want to check the form is submitted before we check it's valid as if the form isn't submitted, it's unnecessary to check it's valid as it will be false.
This is going to prevent your MySQL error because your form technically isn't valid and you're trying to flush invalid data. We obviously only want to save our data when it's valid.
Of course, if the form fails you can return the view and in the template, you have access to
{{ form_errors() }}
This will probably cover what you need but you could also pass to your template something like
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
and then in your template
{% if formHasErrors %}
Something else you may want to do, this allows you to have more control over your fields, is separate out the field out like below:
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
{{ form_widget(form.name) }}
{{ form_end(form) }}
It is very important you catch errors and handle them correctly. Your implementation didn't verify the form is valid which is why you were getting 500 errors.
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
1
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
It is problably because I submit it via json: codeshare.io/G8eJ0d I think afterdone(function(data){
is probably the part where I need to catch the errors, could this be correct?
– Jarla
Nov 21 '18 at 12:52
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410863%2fhow-can-i-display-required-fields-error-validation-message-with-symfony-formbu%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
So when using the form builder, you have access to:
$form->isSubmitted()
and
$form->isValid()
As a result you can do something like:
if ($form->isSubmitted() && $form->isValid()) {
// save to database
}
We want to check the form is submitted before we check it's valid as if the form isn't submitted, it's unnecessary to check it's valid as it will be false.
This is going to prevent your MySQL error because your form technically isn't valid and you're trying to flush invalid data. We obviously only want to save our data when it's valid.
Of course, if the form fails you can return the view and in the template, you have access to
{{ form_errors() }}
This will probably cover what you need but you could also pass to your template something like
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
and then in your template
{% if formHasErrors %}
Something else you may want to do, this allows you to have more control over your fields, is separate out the field out like below:
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
{{ form_widget(form.name) }}
{{ form_end(form) }}
It is very important you catch errors and handle them correctly. Your implementation didn't verify the form is valid which is why you were getting 500 errors.
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
1
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
It is problably because I submit it via json: codeshare.io/G8eJ0d I think afterdone(function(data){
is probably the part where I need to catch the errors, could this be correct?
– Jarla
Nov 21 '18 at 12:52
add a comment |
So when using the form builder, you have access to:
$form->isSubmitted()
and
$form->isValid()
As a result you can do something like:
if ($form->isSubmitted() && $form->isValid()) {
// save to database
}
We want to check the form is submitted before we check it's valid as if the form isn't submitted, it's unnecessary to check it's valid as it will be false.
This is going to prevent your MySQL error because your form technically isn't valid and you're trying to flush invalid data. We obviously only want to save our data when it's valid.
Of course, if the form fails you can return the view and in the template, you have access to
{{ form_errors() }}
This will probably cover what you need but you could also pass to your template something like
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
and then in your template
{% if formHasErrors %}
Something else you may want to do, this allows you to have more control over your fields, is separate out the field out like below:
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
{{ form_widget(form.name) }}
{{ form_end(form) }}
It is very important you catch errors and handle them correctly. Your implementation didn't verify the form is valid which is why you were getting 500 errors.
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
1
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
It is problably because I submit it via json: codeshare.io/G8eJ0d I think afterdone(function(data){
is probably the part where I need to catch the errors, could this be correct?
– Jarla
Nov 21 '18 at 12:52
add a comment |
So when using the form builder, you have access to:
$form->isSubmitted()
and
$form->isValid()
As a result you can do something like:
if ($form->isSubmitted() && $form->isValid()) {
// save to database
}
We want to check the form is submitted before we check it's valid as if the form isn't submitted, it's unnecessary to check it's valid as it will be false.
This is going to prevent your MySQL error because your form technically isn't valid and you're trying to flush invalid data. We obviously only want to save our data when it's valid.
Of course, if the form fails you can return the view and in the template, you have access to
{{ form_errors() }}
This will probably cover what you need but you could also pass to your template something like
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
and then in your template
{% if formHasErrors %}
Something else you may want to do, this allows you to have more control over your fields, is separate out the field out like below:
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
{{ form_widget(form.name) }}
{{ form_end(form) }}
It is very important you catch errors and handle them correctly. Your implementation didn't verify the form is valid which is why you were getting 500 errors.
So when using the form builder, you have access to:
$form->isSubmitted()
and
$form->isValid()
As a result you can do something like:
if ($form->isSubmitted() && $form->isValid()) {
// save to database
}
We want to check the form is submitted before we check it's valid as if the form isn't submitted, it's unnecessary to check it's valid as it will be false.
This is going to prevent your MySQL error because your form technically isn't valid and you're trying to flush invalid data. We obviously only want to save our data when it's valid.
Of course, if the form fails you can return the view and in the template, you have access to
{{ form_errors() }}
This will probably cover what you need but you could also pass to your template something like
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
and then in your template
{% if formHasErrors %}
Something else you may want to do, this allows you to have more control over your fields, is separate out the field out like below:
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
{{ form_widget(form.name) }}
{{ form_end(form) }}
It is very important you catch errors and handle them correctly. Your implementation didn't verify the form is valid which is why you were getting 500 errors.
edited Nov 21 '18 at 12:30
answered Nov 21 '18 at 12:23


MylesKMylesK
1267
1267
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
1
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
It is problably because I submit it via json: codeshare.io/G8eJ0d I think afterdone(function(data){
is probably the part where I need to catch the errors, could this be correct?
– Jarla
Nov 21 '18 at 12:52
add a comment |
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
1
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
It is problably because I submit it via json: codeshare.io/G8eJ0d I think afterdone(function(data){
is probably the part where I need to catch the errors, could this be correct?
– Jarla
Nov 21 '18 at 12:52
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
Thank you! Will this display the error at the place of the field? I mean if someone filled out all fields and just forgot password, is it possible that the error "Password is required" is right beyond that field?
– Jarla
Nov 21 '18 at 12:26
1
1
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Yes, it should display the error related to the field that is causing the error.
– MylesK
Nov 21 '18 at 12:27
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
Ok I will test it exactly like you suggest, I hope I put everything on the right place. Will let you know if it worked.
– Jarla
Nov 21 '18 at 12:29
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
I don't understanding why your application is written in the way it is, so it's hard to advise properly. You seem to be returning a response, maybe in the response have something like 'errors' => $form->getErrors(). Usually from my controller I'd return a view. Dump $form->getErrors() in your controller, is isValid() and work with that and your logic.
– MylesK
Nov 21 '18 at 12:45
It is problably because I submit it via json: codeshare.io/G8eJ0d I think after
done(function(data){
is probably the part where I need to catch the errors, could this be correct?– Jarla
Nov 21 '18 at 12:52
It is problably because I submit it via json: codeshare.io/G8eJ0d I think after
done(function(data){
is probably the part where I need to catch the errors, could this be correct?– Jarla
Nov 21 '18 at 12:52
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410863%2fhow-can-i-display-required-fields-error-validation-message-with-symfony-formbu%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
This looks very much like a magic "create the database table and form on-the-fly", which is an anti-pattern. I strongly suggest you define an Entity and a form Type class. If you have an assertion on the entity it will be checked by the form component automatically. Otherwise you will have to call the validator service yourself: symfony.com/doc/current/… The attribute you set is just the HTML attribute, no validation is assigned just by setting
'required' => true
. See symfony.com/doc/current/reference/forms/types/…– YetiCGN
Nov 21 '18 at 11:29
@YetiCGN Thank you for your message. This is not on the fly, I worked very long to realize this.
– Jarla
Nov 21 '18 at 11:32
1
What I mean is, your model and form are created programatically on-the-fly at runtime. They can be anything and you cannot utilize language or framework features to give semantic meaning and check for things like data type. I know it's tempting to have just one magic method do everything no matter what you feed it, but it's an anti-pattern.
– YetiCGN
Nov 21 '18 at 11:35
@YetiCGN I have an entity defined, I just updated my question with some more information. What is a form type Class? Do you mean "TextType::class, PasswordType::class" etc...?
– Jarla
Nov 21 '18 at 11:38
I mean "a form can be created and used directly in a controller. However, a better practice is to build the form in a separate, standalone PHP class" -> symfony.com/doc/current/forms.html#creating-form-classes
– YetiCGN
Nov 21 '18 at 12:17