如何解决Symfony 未使用 Fos Rest Bundle 和 Nelmio Api doc 与 symfony 4.4 使用表单从后调用中设置实体
我正在尝试使用 fos rest bundle 和 nelmio api doc 在 post http 调用中使用 symfony 表单设置实体。
我配置了没有名称的表单并使用“application/x-www-form-urlencoded”配置了nelmio api doc
问题在于:
提交表单后,对象没有被水合/设置,数量属性为空!
这是我的代码:
fos 休息配置:
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener:
rules:
- { path: ^/api/,priorities: [ html,json,xml ],fallback_format: ~,prefer_extension: true }
- { path: '^/',priorities: [ 'html','*/*' ],fallback_format: html,prefer_extension: true }
view:
view_response_listener: 'force'
表格:
class CartItemFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder,array $options): void
{
$builder
->add(
'quantity',IntegerType::class,[
'required' => true
]
);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(
[
'data_class' => CartItem::class,'csrf_protection' => false,'allow_extra_fields' => true,]
);
}
/**
* @return string
*/
public function getName()
{
return '';
}
}
购物车经理:
class CartManager
{
protected ObjectManager $em;
protected ValidatorInterface $validator;
protected FormFactoryInterface $formFactory;
public function __construct(ObjectManager $em,ValidatorInterface $validator,FormFactoryInterface $formFactory)
{
$this->em = $em;
$this->validator = $validator;
$this->formFactory = $formFactory;
}
public function post(Request $request,Product $product)
{
$form = $this->createForm(CartItemFormType::class,new CartItem());
$form->submit($request->request->all());
if ($form->isValid()) {
/** @var CartItem $cartItem */
$cartItem = $form->getData();
$cartItem->setProduct($product);
$this->em->persist($cartItem);
$this->em->flush();
return $cartItem;
}
return $form;
}
private function createForm($type,$data = null,array $options = [])
{
return $this->formFactory->createNamed('',$type,$data,$options);
}
}
带有 nelmio api 和 fos rest 注释配置的控制器。
/**
* @Rest\Route("/cart-item")
*/
class CartItemController extends AbstractFOSRestController
{
/**
* @Rest\Post("/product/{id}/")
*
* @Rest\View()
* @SWG\Post(consumes={"application/x-www-form-urlencoded"})
*
* @SWG\Response(
* response=201,* description="Post Cart Item by product"
* )
* @SWG\Parameter(
* name="formData",* in="body",* description="description",* @Model(type=CartItemFormType::class)
* )
*
* @SWG\Tag(name="Cart item")
*/
public function postCartItemAction(Request $request,Product $product,CartManager $cartManager)
{
$result = $cartManager->post($request,$product);
return ['result' => $result];
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。