Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Form Bundle Laravel Package

austral/form-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require austral/form-bundle
    

    Ensure Austral\EntityBundle and Austral\ToolsBundle are also installed (required dependencies).

  2. Bundle Registration: Add to config/bundles.php:

    Austral\FormBundle\FormBundle::class => ['all' => true],
    
  3. First Use Case: Create a form type extending Austral\FormBundle\Form\AbstractType:

    use Austral\FormBundle\Form\AbstractType;
    use Austral\FormBundle\Form\Field\FieldInterface;
    
    class MyFormType extends AbstractType
    {
        public function buildForm(): void
        {
            $this->addField('text', 'username', [
                'label' => 'Username',
                'required' => true,
            ]);
        }
    }
    
  4. Rendering: Use in a controller:

    use Austral\FormBundle\Form\FormFactory;
    
    public function index(FormFactory $formFactory)
    {
        $form = $formFactory->create(MyFormType::class);
        return $this->render('my_template.html.twig', ['form' => $form->createView()]);
    }
    
  5. Key Files:

    • src/Form/AbstractType.php: Base class for form types.
    • src/Form/Field/: Field implementations (e.g., TextField, SelectField).
    • templates/: Twig templates for fields (override in your project).

Implementation Patterns

Core Workflows

  1. Field Definition: Use addField() in buildForm() with:

    • Type (text, select, fieldset, etc.).
    • Name (maps to entity property or DTO).
    • Options (e.g., label, required, autocomplete, collapse).

    Example with nested fieldset:

    $this->addField('fieldset', 'address', [
        'fields' => [
            'text' => 'street',
            'text' => 'city',
            'select' => 'country' => ['choices' => ['US', 'CA']],
        ],
        'collapse' => true, // Added in v3.0.1
    ]);
    
  2. Dynamic Fields: Use addDynamicField() for conditional fields:

    $this->addDynamicField('checkbox', 'subscribe', [
        'options' => ['label' => 'Subscribe to newsletter'],
        'condition' => ['field' => 'newsletter_consent', 'value' => true],
    ]);
    
  3. Mapping to Entities: Extend Austral\FormBundle\Form\Mapper\AbstractMapper to handle entity hydration:

    class UserMapper extends AbstractMapper
    {
        protected function mapDataToEntity($data, User $entity): void
        {
            $entity->setUsername($data['username']);
        }
    }
    

    Bind mapper in buildForm():

    $this->setMapper(new UserMapper());
    
  4. Validation Integration: Leverage Symfony’s validator via options:

    $this->addField('email', 'email', [
        'constraints' => [new NotBlank(), new Email()],
    ]);
    
  5. Twig Integration: Override templates in templates/AustralFormBundle/ (e.g., field_text.html.twig). Access form data via form.vars:

    {{ form_label(form) }}
    {{ form_widget(form, { 'attr': { 'autocomplete': form.vars.autocomplete ? 'on' : 'off' } }) }}
    
  6. Autocomplete Handling: Set autocomplete option (default: on for text/email, off for checkbox/select/radio unless specified):

    $this->addField('text', 'password', ['autocomplete' => 'new-password']);
    

Integration Tips

  • Austral EntityBundle: Use Austral\EntityBundle\Annotation\Mapper to auto-register mappers.
  • Event Dispatching: Listen to form.pre_submit or form.post_map via Symfony’s event system.
  • Sortable Fields: Use the sortable option (v3.0.1+) for drag-and-drop reordering in fieldsets:
    $this->addField('fieldset', 'items', ['sortable' => true]);
    
  • Custom Fields: Extend Austral\FormBundle\Form\Field\AbstractField for reusable components.

Gotchas and Tips

Pitfalls

  1. Template Path Changes (v3.1.0):

    • templatePath option was renamed to template in v3.1.0. Update overrides if using custom templates.
    • Example:
      // Old (v3.0.x)
      $this->addField('text', 'name', ['templatePath' => '@MyBundle/field.html.twig']);
      
      // New (v3.1.0+)
      $this->addField('text', 'name', ['template' => '@MyBundle/field.html.twig']);
      
  2. Autocomplete Defaults:

    • Checkbox/select/radio fields default to autocomplete: off (v3.1.0+). Explicitly set autocomplete: on if needed:
      $this->addField('checkbox', 'agree', ['autocomplete' => 'on']);
      
  3. Fieldset Collapse:

    • The collapse option (v3.0.1+) requires JavaScript for toggling. Ensure your frontend supports it:
      // Example using jQuery (if not using Austral’s JS)
      $('.austral-fieldset-collapsible').on('click', function() {
          $(this).next().toggle();
      });
      
  4. Sortable Fields:

    • Requires a frontend library (e.g., SortableJS). Add to your assets:
      new Sortable(document.querySelector('.austral-sortable'), {
          animation: 150,
      });
      
  5. Mapper Binding:

    • Forgetting to call setMapper() will result in unmapped data. Always bind mappers in buildForm():
      $this->setMapper(new MyMapper());
      
  6. Dynamic Fields Conditions:

    • Conditions use dot notation for nested fields. Test with:
      'condition' => ['field' => 'user.profile.active', 'value' => true],
      

Debugging

  1. Form Data Dumping: Use dump($form->getData()) in controllers to inspect submitted data.

  2. Template Debugging: Enable Twig debug mode and check for missing templates in var/cache/dev/.

  3. Mapper Issues:

    • Verify entity properties match field names.
    • Use dd($this->getMapper()->mapDataToEntity($data, $entity)) to debug mapping.
  4. Validation Errors: Access errors via:

    $errors = $form->getErrors(true, false);
    

Extension Points

  1. Custom Field Types: Extend AbstractField and register via service:

    # config/services.yaml
    services:
        App\Form\Field\CustomField:
            tags: [austral.form.field_type]
    
  2. Field Options: Add custom options to AbstractField and handle in buildView()/finishView().

  3. Event Listeners: Subscribe to form.events:

    $dispatcher->addListener('form.pre_submit', function (FormEvent $event) {
        $form = $event->getForm();
        // Modify form data before submission
    });
    
  4. Override Default Templates: Copy templates from vendor/austral/form-bundle/templates/ to templates/AustralFormBundle/ and customize.

  5. Configuration: Override bundle config in config/packages/austral_form.yaml:

    austral_form:
        default_options:
            autocomplete: 'on' # Global default
    

Pro Tips

  • Reusable Fieldsets: Create base fieldset types for common groups (e.g., AddressFieldsetType).
  • Conditional Logic: Combine addDynamicField with condition for multi-step forms.
  • Performance: For large forms, lazy-load fieldsets or use enabled options to hide sections.
  • Testing: Use Austral\FormBundle\Test\FormTestCase for form unit tests.
  • Documentation: Check the Austral Framework docs for advanced patterns.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui