我如何通过axios将数据从vue应用程序发送到Symfony?当我尝试发送数据Symfony请求时,看不到它们。
控制器代码:
$form = $this->createForm(TeacherType::class);
$form->submit($request->request->all());
$form->handleRequest($request);
if($form->isSubmitted() && !$form->isValid()) {
return new JsonResponse([
'code' => "400",
'data' => $this->getErrorMessages($form),
]);
}
return new JsonResponse(array(
'code' => 200,
));
axios:
sent() {
axios.post('http://localhost:8000/valid', {
firstname: this.firstname
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
表格:
<form @submit.prevent="sent" id="form" name="teacher" method="POST" action="#">
<input type="text" name="teacher[firstname]" v-model="firstname">
<button type="submit">OK</button>
</form>
总是我的回答是:{'code':400}并警告名字不要为空(形式设置为assert断言NotBlank为名字)
我该怎么办?
答案 0 :(得分:0)
尝试删除$form->handleRequest($request);
,handleRequest
不适用于api调用
更新。
这是验证实体的简单示例
实体:
use Symfony\Component\Validator\Constraints as Assert;
class SomeClass
{
/**
* @Assert\NotBlank
*/
private $content;
}
FormType:
class SomeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('content', TextType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => SomeClass::class,
]);
}
}
FormHandler:
class FormHandler
{
private $formFactory;
public function __construct(FormFactoryInterface $formFactory)
{
$this->formFactory = $formFactory;
}
public function handleWithSubmit(
array $data,
string $type,
$entity,
array $options = []
) {
$form = $this->formFactory->create($type, $entity, $options);
$form->submit($data);
return $this->processSubmitted($form, $entity);
}
private function processSubmitted(FormInterface $form, $entity)
{
if (!$form->isValid()) {
return $form->getErrors();
}
if (!is_object($entity)) {
$entity = $form->getData();
}
return $entity;
}
}
将FormHandler
插入控制器并调用
$handled = $this->formHandler->handleWithSubmit($request->request->all(), SomeType::class, new SomeClass());
if (!$handled instanceof SomeClass) {
// return errors
}
答案 1 :(得分:0)
发生这种情况是因为您在HTML文档中的字段命名不正确。
当前:
teacher[firstname]
但应该(或多或少):
teacher_teacher[firstname]
使用FormFactoryInterface
来创建命名表单:
public function yourAction(Request $request, FormFactoryInterface $forms)
{
$form = $this->forms->createNamed('', TeacherType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
return new JsonResponse([
'code' => '400',
'data' => $this->getErrorMessages($form),
]);
}
return new JsonResponse(['code' => 200]);
}
当您创建一个没有名称的表单(例如$this->createForm(TeacherType::class)
)时,系统会自动为您生成一个名称:该表单的名称末尾没有Form
和Type
词,因此字段名称前必须有teacher_
部分。
答案 2 :(得分:0)
安装FOS Rest捆绑包,并确保已安装序列化程序。我会使用Symfony序列化程序
https://symfony.com/doc/master/bundles/FOSRestBundle/1-setting_up_the_bundle.html
基本上,它将对HTTP请求正文和$form->handleRequest($request)
所需的Accept标头进行解码,然后显示提交的表单。