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

Valid Form Event Laravel Package

braunstetter/valid-form-event

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require braunstetter/valid-form-event
    

    Add the bundle to config/bundles.php (Symfony) or register it in config/app.php (Laravel via Symfony bridge):

    Braunstetter\ValidFormEventBundle\ValidFormEventBundle::class => ['all' => true],
    
  2. First Use Case:

    • Create a form type (e.g., App\Form\MyFlexibleFormType).
    • Extend Braunstetter\ValidFormEventBundle\Form\ValidFormTypeInterface or use the trait ValidFormTypeTrait:
      use Braunstetter\ValidFormEventBundle\Form\ValidFormTypeTrait;
      
      class MyFlexibleFormType extends AbstractType
      {
          use ValidFormTypeTrait;
      
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              $builder
                  ->add('field1')
                  ->add('field2')
                  ->addEventListener(ValidFormEvents::VALID, [$this, 'onValidForm']);
          }
      
          public function onValidForm(ValidFormEvent $event)
          {
              $data = $event->getData();
              // Your logic here (e.g., upload image, process data)
          }
      }
      
  3. Register the Form:

    // In your controller or service
    $form = $this->createForm(MyFlexibleFormType::class, $entity);
    

Implementation Patterns

Workflows

  1. Conditional Logic in Forms:

    • Use ValidFormEvents::VALID to trigger logic only when the entire form passes validation.
    • Example: Uploading files, sending emails, or processing complex data structures.
      public function onValidForm(ValidFormEvent $event)
      {
          $data = $event->getData();
          if ($data->getAction() === 'publish') {
              $this->publishService->publish($data);
          }
      }
      
  2. Nested Forms:

    • For nested forms (e.g., collections or embedded forms), ensure the parent form’s VALID event propagates correctly.
    • Use ValidFormTypeTrait in child forms to inherit validation checks:
      class ChildFormType extends AbstractType
      {
          use ValidFormTypeTrait;
          // ...
      }
      
  3. Event Propagation:

    • Disable propagation if the event should not bubble up:
      $event->stopPropagation();
      
  4. Data Access:

    • Access form data via $event->getData() or form fields via $event->getForm():
      $form = $event->getForm();
      $fieldValue = $form->get('field1')->getData();
      

Integration Tips

  • Laravel-Specific:

    • Use Symfony’s FormComponent via spatie/laravel-symfony-support or symfony/form directly in Laravel 9+.
    • Register the bundle in config/app.php:
      'providers' => [
          Braunstetter\ValidFormEventBundle\ValidFormEventBundle::class,
      ],
      
  • Dependency Injection:

    • Inject services into form types via constructor (Symfony-style):
      public function __construct(private UploadService $uploadService) {}
      
      public function onValidForm(ValidFormEvent $event)
      {
          $this->uploadService->upload($event->getData()->getImage());
      }
      
  • Validation Groups:

    • Combine with Symfony’s validation groups for granular control:
      $builder->addEventListener(ValidFormEvents::VALID, [$this, 'onValidForm'], 10);
      

Gotchas and Tips

Pitfalls

  1. Event Order:

    • The VALID event fires after all validation constraints are checked. Logic here runs only if the form is entirely valid.
    • Avoid mixing with PRE_SUBMIT or SUBMIT events unless intentional.
  2. Circular Dependencies:

    • If forms reference each other (e.g., parent-child), ensure the ValidFormTypeTrait is used consistently to avoid infinite loops.
  3. Laravel-Specific Quirks:

    • Laravel’s form handling (e.g., Illuminate\Http\Request) may not directly support Symfony’s FormEvent. Use a bridge or wrap logic in a service layer.
  4. Data Mutability:

    • The ValidFormEvent provides a clone of the form data. Modify data cautiously to avoid unintended side effects:
      $dataClone = $event->getData(); // Clone, not reference
      

Debugging

  • Check Event Firing:

    • Verify the VALID event is triggered by adding a dump() or logger:
      public function onValidForm(ValidFormEvent $event)
      {
          \Log::debug('Form valid!', ['data' => $event->getData()]);
      }
      
  • Validation Errors:

    • If the event doesn’t fire, check for validation errors in $event->getForm()->getErrors().
  • Priority Conflicts:

    • Use event listener priorities (e.g., 10, 20) to control execution order:
      $builder->addEventListener(ValidFormEvents::VALID, [$this, 'onValidForm'], 20);
      

Extension Points

  1. Custom Events:

    • Extend the bundle by creating custom events (e.g., PARTIALLY_VALID) by subclassing ValidFormEvent.
  2. Form Modifiers:

    • Dynamically add/remove fields based on validation:
    public function onValidForm(ValidFormEvent $event)
    {
        if ($event->getData()->isPremium()) {
            $event->getForm()->add('premiumField');
        }
    }
    
  3. Testing:

    • Mock ValidFormEvent in tests:
    $event = $this->createMock(ValidFormEvent::class);
    $event->method('getData')->willReturn($data);
    $this->formType->onValidForm($event);
    
  4. Performance:

    • For heavy operations, offload work to a queue or async process:
    public function onValidForm(ValidFormEvent $event)
    {
        dispatch(new ProcessDataJob($event->getData()));
    }
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle