我使用以下库/技术:
JMSSerializer,FOSRestBundle + Symfony 3.2 + PHP 7.1
当我尝试向POST端点发出POST请求时,我无法使表单生效。
文件:
Country.php - > POPO实体
CountryType.php
<?php
declare(strict_types = 1);
namespace AppBundle\Form;
use AppBundle\Model\Entity\Country;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CountryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name' , TextType::class)
->add('iso_alpha_2_code', TextType::class)
->add('iso_alpha_3_code', TextType::class)
->add('is_numeric_code', IntegerType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Country::class,
'csrf_protection' => false,
]);
}
/**
* @inheritdoc
*/
public function getName() : string
{
return '';
}
}
CountryController.php postAction
public function postAction(Request $request)
{
$country = new Country();
$form = $this->createForm(CountryType::class, $country);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
die('ok');
// TODO INSERT DATA then redirect
return $this->routeRedirectView('get_country', ['id' => $country->getId()]);
}
return $this->get('fos_rest.view_handler')->handle(View::create($form));
}
问题是它不会输入if块,因为isSubmited()和isValid()方法都返回false。当我致电$form->getData()
时,它会返回
CountryController.php on line 40:
Country {#306
-id: null
-name: null
-isoAlpha2Code: null
-isoAlpha3Code: null
-isNumericCode: null
}
我提出的要求:
你能给我一个提示我做错了吗?
答案 0 :(得分:4)
这是我在使用FOSRest包时提交表单的方式,我希望这会让你朝着正确的方向前进。这是一个示例注册操作。您会注意到您必须手动提交表单
$form->submit($request->request->all());
,然后检查它是否有效
public function postRegistrationAction(Request $request){
$form = $this->createForm(UserType::class, null, [
'csrf_protection' => false,
]);
$form->submit($request->request->all());
if (!$form->isValid()) {
return $form;
}
/**
* @var $user User
*/
$user = $form->getData();
$em = $this->getDoctrine()->getManager();
//Set the user role
$user->setRoles(array('ROLE_USER'));
//Encode the password
$password = $request->request->get('password');
$encodedPassword = $this->get('security.password_encoder')->encodePassword($user, $password['first']);
$user->setPassword($encodedPassword);
$token = $this->get('lexik_jwt_authentication.encoder')->encode(['username' => $user->getUsername(), 'role' => $user->getRoles(), 'name' => $user->getName()]);
$em->persist($user);
$em->flush();
$view = FOSView::create();
$view
->setData(['token' => $token])
->setStatusCode(200);
return $view;
}
答案 1 :(得分:0)
我能够使用以下几行来获取数据
$user = new User;
$form = $this->createForm(UserType::class, $user);
$form->submit($request->request->all());
if($form->isValid()){
//persist or do anything
return $user;
}
return 'There were an error in your form';