I'm trying to set an entity using a symfony form in a post http call using fos rest bundle and nelmio api doc.
I configured the form without name and configured nelmio api doc with "application/x-www-form-urlencoded"
The problem is:
After make submit form the object is not hydrateted/setted, quantity property is null!
This is my code:
fos rest configuration:
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'
Form:
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 '';
}
}
Cart Manager:
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);
}
}
Controller with nelmio api and fos rest annotation configuration.
/**
* @RestRoute("/cart-item")
*/
class CartItemController extends AbstractFOSRestController
{
/**
* @RestPost("/product/{id}/")
*
* @RestView()
* @SWGPost(consumes={"application/x-www-form-urlencoded"})
*
* @SWGResponse(
* response=201,
* description="Post Cart Item by product"
* )
* @SWGParameter(
* name="formData",
* in="body",
* description="description",
* @Model(type=CartItemFormType::class)
* )
*
* @SWGTag(name="Cart item")
*/
public function postCartItemAction(Request $request, Product $product, CartManager $cartManager)
{
$result = $cartManager->post($request, $product);
return ['result' => $result];
}
}
question from:
https://stackoverflow.com/questions/66050865/symfony-is-not-setting-entity-from-post-call-with-form-using-fos-rest-bundle-and