오류없이 Symfony2 잘못된 양식
Symfony2 생성 CRUD 양식에 문제가 있습니다. (MongoDB 문서와 관련이 있다고 생각하지 않습니다)
내 컨트롤러의 createAction () 메서드에서 양식 결과를 디버깅 할 때 :
$form->isValid() // returns false
$form->getErrors() // returns en empty array(0) {}
그래서 form_errors(form)
내 나뭇 가지 템플릿에서 아무것도 얻지 못합니다 ( $form->getErrors()
빈 반환으로 인해 정상으로 보입니다 )
그리고 쓰여진 값은 형식으로 대체되지 않습니다.
누구나 아이디어가 있습니까?
가장 먼저 이해해야 할 것은 유효성 검사가 양식이 아니라 모델에서 수행된다는 것입니다. 양식은 오류를 포함 할 수 있지만 유효성을 검사하지 않는 속성에 매핑 된 필드가있는 경우에만 가능합니다. 따라서 양식에 잘못된 필드 ( NotNull
양식에없는 속성에 대한 어설 션일 수 있음)가 포함되어 있지 않으면 오류가 표시되지 않습니다.
두 번째는 해당 $form->getErrors()
수준에 대한 오류 만 표시하며 각 양식 하위에는 자체 오류가 포함될 수 있습니다. 따라서 오류를 확인하려면 필드를 반복하고 각 필드에서 getErrors를 호출해야합니다. getErrors
Form 클래스 의 메서드는 그런 식으로 속일 수 있습니다.
양식을 디버깅하려면 사용하는 $form->getErrorsAsString()
대신 $form->getErrors()
.
$form->getErrorsAsString()
양식을 디버그하는 데만 사용해야합니다. ...의 경우가 아닌 각 하위 요소의 오류를 포함합니다 $form->getErrors()
.
Peter가 언급했듯이은 $form->getErrors()
자식 양식의 모든 오류 합계를 반환하지 않습니다.
폼이 어떻게 유효하지 않고 빈 배열을 반환하는 getErrors ()가 있는지 이해하려면 심포니 폼 클래스 의 isValid () 메서드를 살펴볼 수 있습니다 . 보시다시피 양식이 유효하지 않은 두 가지 경우가 있습니다. 첫 번째는 일반 양식에 대한 테스트이고 두 번째는 각 하위 요소에 대한 테스트입니다.
public function isValid()
{
//...
//CASE I : IF CHILD ELEMENTS HAVE ERRORS, $this->errors WILL CONTAIN
//THE ERROR ON THE CHILD ELEMENT AND NOT ON THE GENERAL 'errors' FIELD
//ITSELF
if (count($this->errors) > 0) {
return false;
}
//CASE II: AND THIS IS WHY WE ARE TESTING THE CHILD ELEMENTS AS WELL
//TO CHECK WHETHER THERE ARE VALID OR NOT
if (!$this->isDisabled()) {
foreach ($this->children as $child) {
if (!$child->isValid()) {
return false;
}
}
}
return true;
}
따라서 각 양식 하위에는 오류가 포함될 수 있지만 $form->getErrors()
자체적으로 모든 오류를 반환하지는 않습니다. 자식 요소가 많은 양식을 고려할 때 일반적으로 CSRF가 올바르지 않으면 CSRF 오류와 함께 $ form-> getErrors ()가 발생합니다.
Symfony 2.6 업데이트
따라서 Symfony2 버전에 따라 :
die($form->getErrorsAsString());
현재 symfony2.5 의 getErrorsAsString()
기능 (Symfony3에서 제거 될 예정입니다) 사용되지 않으며 다음과 같은 방법을 사용한다 :
die((string) $form->getErrors()); // Main errors
die((string) $form->getErrors(true)); // Main and child errors
현재 symfony2.6 , 당신은 또한 사용할 수 있습니다 dump
당신은 활성화 한 경우 기능 (dev에 환경) DebugBundle
:
dump((string) $form->getErrors()); // Main errors
dump((string) $form->getErrors(true)); // Main and child errors
같은 문제가 있습니다. 저에게는 양식이 유효하지 않지만 $form->getErrors()
또는 을 사용하여 오류가 발생하지 않았습니다 $form->getErrorsAsString()
. 나중에 CSRF 토큰을 양식에 전달하는 것을 잊었으므로 제출 $form->handleRequest($request)
되지 않고 아무것도 수행하지 않았습니다 (검증 없음). @pit의 대답을 보았을 때 사용하려고했습니다.
$form->submit($request);
$form->getErrorsAsString();
오류를 반환했습니다.
오류 : CSRF 토큰이 유효하지 않습니다. 양식을 다시 제출하십시오.
다음은 Symfony2 문서의 몇 가지 설명입니다. http://symfony.com/doc/current/book/forms.html#handling-form-submissions
Symfony (> = 3.2-4)의 경우 다음을 사용할 수 있습니다.
foreach($form->getErrors(true, false) as $er) {
print_r($er->__toString());
}
분명히 오류를 볼 수 있습니다.
문서에 따라 Symfony 3 이후부터는 새로운 구현을 사용해야합니다.
$errors = (string) $form->getErrors(true, false);
This will return all errors as one string.
For me the form was not submitted, even if I had a submit button. I added the code to solve the problem
$request = $this->get('request');
if($request->isMethod("POST")){
$form->submit($request);
if($form->isValid()){
// now true
}
}
If you are sending datas via AJAX, you may have missed to include the form's name on your datas keys and therefore are "victim" of …
# line 100 of Symfony/Component/Form/Extension/HttpFoundation/HttpFoundationRequestHandler.php
// Don't submit the form if it is not present in the request
Which means, while trying to handle the request, the request processing mechanism did not find your form's name inside GET/POST datas (meaning as an array).
When you render a form the usual way, each of its fields contain your form's name as a prefix into their name attribute my_form[child_field_name]
.
When using ajax, add your form's name as a prefix in datas !
data : {
"my_form" : {
"field_one" : "field_one_value"
...
}
}
Yes it is correct, what it say Peter Kruithof In SF 2.8 this is my function,to get the errors of the fields
private function getErrorsForm(\Symfony\Component\Form\Form $form)
{
$response = array();
foreach ($form as $child) {
foreach ($child->getErrors(true) as $error) {
$response[$child->getName()][] = $error->getMessage();
}
}
return $response;
}
I came across this error and found that I was forgetting to "handle" the request. Make sure you have that around...
public function editAction(Request $request)
{
$form = $this->createForm(new CustomType(),$dataObject);
/** This next line is the one I'm talking about... */
$form->handleRequest($request);
if ($request->getMethod() == "POST") {
if ($form->isValid()) {
...
It appears as you have a validation problem. The form is not validating on submitting. I am going to assume you are using Annotations for your validation. Make sure you have this at the top of the entity.
use Symfony\Component\Validator\Constraints as Assert;
and also this above each property
/**
* @Assert\NotBlank()
*/
The NotBlank()
can be changed to any constraint to fit your needs.
More information on validation can be found at: http://symfony.com/doc/current/book/validation.html
More information on Assert constraints can be found at: http://symfony.com/doc/current/book/validation.html#constraints
참고URL : https://stackoverflow.com/questions/11208992/symfony2-invalid-form-without-errors
'Program Tip' 카테고리의 다른 글
NSDateFormatter setDateFormat에 대한 서수 월-일 접미사 옵션 (0) | 2020.12.02 |
---|---|
tcpdump를 사용하여 HTTP 요청, 응답 헤더 및 응답 본문을 가져올 수 있습니까? (0) | 2020.12.02 |
ostream을 표준 문자열로 변환 (0) | 2020.12.02 |
SPAN_EXCLUSIVE_EXCLUSIVE와 같은 Span 플래그의 의미를 설명하십시오. (0) | 2020.12.02 |
UITableView 배경 이미지 (0) | 2020.12.02 |