Answer the question
In order to leave comments, you need to log in
SYmfony 3.4: how to do form validation correctly?
Greetings!
There is an essence
class Meeting
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
//......и т. д.
}
class MeetingType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class)
->add('desctiption', TextareaType::class)
->add('avatar', FileType::class)
->add('beginAt', IntegerType::class)
->add('createdAt', IntegerType::class)
->add('updatedAt', IntegerType::class)
->add('uid', IntegerType::class)
;
}
}
public function createAction(Request $request)
{
$data = $request->request->all();
$formData = [
//... здесь заполнение в соответствии с моделью и преобразование некоторых полей
//... так же подцепляется CSRF токен
];
$form = $this->createForm(MeetingType::class, new Meeting);
$form->submit($formData);
if (!$form->isValid()) {
$errors = [];
foreach ($form->getErrors(true, false) as $key => $error) {
if (method_exists($error, 'getMessage')) {
$errors[] = $error->getMessage();
} else {
foreach ($error as $k => $e) {
$errors[] = $e->getMessage();
}
}
}
return new JsonResponse([
'success' => false,
'errors' => $errors,
'type' => 'form-validation',
]);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question