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 Helper Error Bundle Laravel Package

avtonom/form-helper-error-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require avtonom/form-helper-error-bundle
    

    Replace ~1.1 with the latest stable version (e.g., ^1.1.0).

  2. Enable Bundle: Add to config/bundles.php (Laravel 5.4+) or app/AppKernel.php (Symfony):

    Avtonom\FormHelper\ErrorBundle\FormHelperErrorBundle::class,
    
  3. Configure Translator (if not using Symfony’s default):

    # config/packages/framework.yaml (Symfony) or .env (Laravel)
    FRAMEWORK_TRANSLATOR_FALLBACKS=['%locale%']
    
  4. First Use Case: Inject the helper into a controller/service:

    use Avtonom\FormHelper\ErrorBundle\Service\FormErrorHelper;
    
    public function __construct(private FormErrorHelper $formErrorHelper) {}
    
    public function showFormErrors(Request $request) {
        $form = $this->createForm(...);
        $form->handleRequest($request);
    
        // Get errors as an array (nested by field)
        $errors = $this->formErrorHelper->getErrorsAsArray($form);
        return response()->json($errors);
    }
    

Implementation Patterns

Common Workflows

  1. Form Validation Feedback:

    • Use getErrorsAsArray() to flatten Symfony form errors into a structured array for:
      • JSON API responses.
      • Frontend validation (e.g., Vue/React error display).
      • Logging invalid submissions.
    $errors = $this->formErrorHelper->getErrorsAsArray($form);
    // Output: ['field.name' => ['Error 1', 'Error 2'], ...]
    
  2. Conditional Error Handling:

    • Check for errors before processing:
    if ($this->formErrorHelper->hasErrors($form)) {
        return redirect()->back()->withErrors($errors);
    }
    
  3. Custom Error Messages:

    • Override default messages via translation files (e.g., messages.en.yaml):
    validation:
        unique: "This value is already taken."
    
  4. Integration with Laravel Validation:

    • Combine with Laravel’s Validator for hybrid validation:
    $validator = Validator::make($data, $rules);
    $form = $this->createForm(...)->submit($data);
    $errors = array_merge(
        $validator->errors()->toArray(),
        $this->formErrorHelper->getErrorsAsArray($form)
    );
    
  5. Dynamic Forms:

    • Use with dynamic forms (e.g., collectives/laravel-bread) to validate nested structures:
    $errors = $this->formErrorHelper->getErrorsAsArray($form, true); // Deep flatten
    

Integration Tips

  • Laravel-Specific:

    • Register the service in config/services.php:
      'form_error_helper' => Avtonom\FormHelper\ErrorBundle\Service\FormErrorHelper::class,
      
    • Bind in AppServiceProvider:
      $this->app->bind('form.helper.error', function ($app) {
          return new FormErrorHelper($app['form.factory']);
      });
      
  • Symfony Forms:

    • Works seamlessly with Symfony’s FormBuilder and FormInterface.
    • Supports FormType extensions for custom validation.
  • Testing:

    • Mock the helper in PHPUnit:
      $helper = $this->createMock(FormErrorHelper::class);
      $helper->method('getErrorsAsArray')->willReturn(['test' => ['Error']]);
      

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Compatibility:

    • The bundle is Symfony-first. In Laravel, ensure:
      • You’re using a Symfony-compatible form component (e.g., symfony/form via laravel/symfony-form).
      • The FormFactory is properly bound (Laravel 5.5+ may need manual binding).
  2. Error Structure:

    • getErrorsAsArray() returns nested arrays by default. Use the second parameter to flatten:
      $flatErrors = $this->formErrorHelper->getErrorsAsArray($form, true);
      
  3. Translation Fallbacks:

    • If translations are missing, errors will default to raw Symfony messages. Ensure your messages.{locale}.yaml includes:
      validation:
          required: "This field is required."
      
  4. Circular References:

    • Deeply nested forms (e.g., collections with sub-collections) may cause infinite loops. Limit recursion depth:
      $errors = $this->formErrorHelper->getErrorsAsArray($form, true, 3); // Max depth 3
      
  5. Bundle Autoloading:

    • If errors occur, verify the bundle is autoloaded in composer.json:
      "autoload": {
          "psr-4": {
              "Avtonom\\FormHelper\\": "vendor/avtonom/form-helper-error-bundle/src"
          }
      }
      

Debugging Tips

  • Check Form Errors Directly:
    dump($form->getErrors(true)); // Symfony's raw error structure
    
  • Enable Debug Mode:
    # config/packages/dev/framework.yaml
    framework:
        translator:
            debug: true
    
  • Log Errors:
    \Log::debug('Form errors:', [
        'raw' => $form->getErrors(true),
        'processed' => $this->formErrorHelper->getErrorsAsArray($form)
    ]);
    

Extension Points

  1. Custom Error Formatters:

    • Extend the helper by creating a decorator:
      class CustomFormErrorHelper extends FormErrorHelper {
          public function getErrorsAsJson($form) {
              return json_encode($this->getErrorsAsArray($form));
          }
      }
      
    • Bind it in services.php:
      'form_error_helper' => CustomFormErrorHelper::class,
      
  2. Add Custom Validation Rules:

    • Use Symfony’s Constraint system and integrate with the bundle’s error handling.
  3. Laravel Notifications:

    • Attach errors to notifications:
      $notification = new FormValidationFailed($errors);
      $this->notify($user, $notification);
      
  4. Frontend Integration:

    • Expose errors via API:
      return response()->json([
          'success' => false,
          'errors' => $this->formErrorHelper->getErrorsAsArray($form)
      ]);
      
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