问题描述
我正在尝试使用 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 (将#修改为@)