Symfony form handler abstraction, (*1)
Demo
You can try this library on Demo Form-handler, (*2)
Installation
The recommended way to install FormHandler is through
Composer., (*3)
# Install Composer
curl -sS https://getcomposer.org/installer | php
php composer require symftony/form-handler
After installing, you need to require Composer's autoloader:, (*4)
require 'vendor/autoload.php';
Documentation
This bundle provide a build in FormHandler and TypeExtension., (*5)
The TypeExtension add options to the Symfony FormType, (*6)
- handler_invalid = true to throw InvalidFormException
- handler_not_submitted = true to throw NotSubmittedFormException
- handler_transformation_failed = true to throw TransformationFailedFormException
If you set a data instead of true in this option the FormHandler::handle return it if the case append, (*7)
Use in Symfony
Add the bundle to your kernel app/AppKernel.php
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
...
new Symftony\FormHandler\FormBundle\FormHandlerBundle(),
...
];
}
...
public function yourAction(Request $request)
{
$formHandler = $this->get('form_handler.form_handler.default');
// Throw exception if the form is NotSubmit/NotValid/TransformFailed
$form = $formHandler->createForm(TextType::class, 'my-value', 'My default data', [
'method' => 'GET',
'handler_invalid' => true,
'handler_not_submitted' => true,
'handler_transformation_failed' => true,
]);
// You get the $form->getData() if all succeed
$result = $formHandler->handleRequest($form, $request);
return $this->render('default/index.html.twig', [
'form' => $form->createView(),
'result' => $result,
]);
}
You can add a try/catch to handle Exception by yourself
OR implement a KernelException, (*8)
Create YourFormHandler
and extends FormHandler
, (*9)
<?php
namespace AppBundle\Form\Handler;
use Symfony\Component\HttpFoundation\Request;
use Symftony\FormHandler\FormHandler;
class YourFormHandler extends FormHandler
{
public function createFromRequest(Request $request, $notSubmitted = true, $invalid = true)
{
$form = $this->createForm(TextType::class, 'my-value', 'My default data', [
'handler_not_submitted' => $notSubmitted,
'handler_invalid' => $invalid,
]);
$result = $this->handleRequest($form, $request);
// DO whatever you want with your $result
return $result
}
}
Declare as a service, (*10)
services:
app.form_handler.your:
class: AppBundle\Form\Handler\YourFormHandler
tags:
- { name: 'form.handler' }
/!\ Dont forget to tag with 'form.handler'
Or to Inject the FormFactory by yourself, (*11)
Use it!!!, (*12)
public function yourAction(Request $request)
{
return $this->render('default/index.html.twig', [
'result' => $this->get('app.form_handler.your')->createFromRequest(
$request,
'my data if form wasn\'t post' // result if the form isn't submitted
true // Gonna throw Exception when the form isn't valid
),
]);
}