mcfedr/json-form
Symfony bundle/trait that lets controllers handle forms submitted as JSON. Use JsonControllerTrait to create and process JSON-backed forms, accepting payloads shaped like normal form fields, then validate and persist as usual.
Simply use the JsonControllerTrait and then use forms as you would normally,
but they now expect to receive JSON.
php composer.phar require mcfedr/json-form
Include the bundle in your AppKernel
public function registerBundles()
{
$bundles = array(
...
new Mcfedr\JsonFormBundle\McfedrJsonFormBundle()
The expected JSON will be just like that form values that would be sent.
Suppose you have the following form type
class AccountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name');
}
public function getBlockPrefix()
{
return 'account';
}
}
Then the JSON should be
{
"account": {
"name": "Fred"
}
}
class AccountController extends AbstractController
use JsonControllerTrait;
/**
* @Route("/accounts", methods={"POST"})
*/
public function accountCreateAction(Request $request, $uuid) {
$account = new Account();
$form = $this->createJsonForm(AccountType::class, $account);
$this->handleJsonForm($form, $request);
$em = $this->getDoctrine()->getManager();
$em->persist($account);
$em->flush();
return $this->json([
'account' => $account
]);
}
}
For Symfony 3.x you will need to extend Controller because the trait needs
access to getParameter method.
To run the tests
./vendor/bin/php-cs-fixer fix
./vendor/bin/phpunit
./vendor/bin/phpstan analyse
How can I help you explore Laravel packages today?