Installation Add the bundle via Composer:
composer require alpixel/formbundle
Enable it in AppKernel.php (Symfony 2.x):
new Alpixel\FormBundle\AlpixelFormBundle(),
First Use Case
Create a form type extending Alpixel\FormBundle\Form\Type\BaseFormType:
use Alpixel\FormBundle\Form\Type\BaseFormType;
class MyFormType extends BaseFormType
{
public function getName()
{
return 'my_form';
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text');
$builder->add('submit', 'submit');
}
}
Register the Form Add the form type to your services (Symfony 2.x):
# app/config/services.yml
services:
my_form.type:
class: AppBundle\Form\Type\MyFormType
tags:
- { name: form.type, alias: my_form }
Use in Controller
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MyController extends Controller
{
public function indexAction(Request $request)
{
$form = $this->createForm('my_form');
// ...
}
}
Dynamic Form Fields
Leverage BaseFormType to dynamically add fields based on runtime logic:
public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($options['dynamic_field']) {
$builder->add('dynamic_field', 'text');
}
}
Form Events
Use Symfony’s form events (e.g., PRE_SET_DATA, POST_SUBMIT) for validation or transformations:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
// Modify data before form population
});
Reusable Form Components
Create modular form types for reuse (e.g., AddressFormType, UserProfileFormType).
Integration with Doctrine
Bind forms to entities via add() with entity class:
$builder->add('user', 'entity', [
'class' => 'AppBundle\Entity\User',
'property' => 'name',
]);
FormComponent (Symfony 4+).Form packages (e.g., laravelcollective/html).FOSUserBundle for user management or StofDoctrineExtensions for advanced form fields.Outdated Dependencies
Limited Documentation
Form Type Registration
form.type tags are correctly configured in services.yml or as annotations.CSRF Protection Enable Symfony’s CSRF protection in forms:
{{ form_start(form, { attr: { 'data-csrf-token': app.session.token } }) }}
{{ dump(form.errors) }} in Twig to inspect validation issues.PRE_SET_DATA events for entity hydration problems.app/console debug:config) to trace form lifecycle.Custom Validation Add constraints via annotations or callbacks:
use Symfony\Component\Validator\Constraints as Assert;
$builder->add('email', 'email', [
'constraints' => new Assert\NotBlank(),
]);
Override Templates
Customize form themes in config.yml:
twig:
form_themes:
- 'AlpixelFormBundle:Form:fields.html.twig'
Event Subscribers
Attach global form logic via FormEvents:
$formFactory->addFormTypeExtension(new MyExtension(), 'my_form');
How can I help you explore Laravel packages today?