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

Bdf Form Laravel Package

b2pweb/bdf-form

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require b2pweb/bdf-form
    

    Register the service provider in config/app.php under providers:

    B2PWeb\BDFForm\BDFFormServiceProvider::class,
    
  2. Basic Usage: Create a form class extending B2PWeb\BDFForm\BDFForm:

    use B2PWeb\BDFForm\BDFForm;
    
    class MyForm extends BDFForm
    {
        protected $fields = [
            'name' => ['type' => 'text', 'label' => 'Your Name'],
            'email' => ['type' => 'email', 'label' => 'Email Address'],
        ];
    }
    
  3. Rendering: Use the render() method in a Blade view:

    $form = new MyForm();
    echo $form->render();
    
  4. Handling Submissions:

    $form = new MyForm();
    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        // Process data (e.g., save to DB)
    }
    

First Use Case

Build a contact form with validation:

class ContactForm extends B2PWeb\BDFForm\BDFForm
{
    protected $fields = [
        'name' => ['type' => 'text', 'rules' => 'required|min:3'],
        'email' => ['type' => 'email', 'rules' => 'required|email'],
        'message' => ['type' => 'textarea', 'rules' => 'required|min:10'],
    ];

    protected $submitButton = 'Send Message';
}

Implementation Patterns

Workflows

  1. Form Creation:

    • Extend BDFForm and define $fields as an associative array.
    • Use built-in types (text, email, textarea, select, checkbox, etc.) or custom types via type key.
  2. Validation:

    • Leverage Laravel’s validation rules (e.g., required, min, email) via the rules key.
    • Override validate() for custom logic:
      protected function validate(array $data): array
      {
          $rules = parent::validate($data);
          $rules['email'][] = 'unique:users'; // Example custom rule
          return $rules;
      }
      
  3. Dynamic Fields:

    • Use addField() or removeField() dynamically:
      $form->addField('age', ['type' => 'number', 'label' => 'Age']);
      
  4. Integration with Laravel:

    • Request Handling: Bind the form to a route parameter or use middleware to auto-instantiate:
      public function showForm(MyForm $form) { ... }
      
    • Flash Messages:
      if (!$form->isValid()) {
          return back()->withErrors($form->errors())->withInput();
      }
      
  5. CSRF Protection: Enable via config (config/bdf-form.php):

    'csrf' => env('APP_DEBUG') ? false : true,
    

Integration Tips

  • Blade Macros: Create reusable form components:

    Blade::component('form', function ($form) {
        return $form->render();
    });
    

    Usage:

    @form($form)
    
  • Localization: Use Laravel’s localization features for labels/errors:

    'name' => ['type' => 'text', 'label' => __('form.name')],
    
  • Assets: Override default assets (CSS/JS) via config:

    'assets' => [
        'css' => 'path/to/custom.css',
        'js' => 'path/to/custom.js',
    ],
    

Gotchas and Tips

Pitfalls

  1. CSRF Mismatch:

    • If csrf is enabled in config but the form lacks a CSRF token, submissions will fail.
    • Fix: Ensure {{ csrf_field() }} is included in Blade or manually add the token:
      $form->addHidden('_token', csrf_token());
      
  2. Validation Rules:

    • Rules like unique require database access. If the connection fails, validation silently passes.
    • Fix: Wrap in a try-catch or test rules in isolation.
  3. Field Naming Collisions:

    • Dynamic fields with duplicate names (e.g., addField('email', [...]) twice) may overwrite data.
    • Fix: Use unique keys or sanitize input names.
  4. Asset Loading:

    • Custom assets may not load if paths are incorrect or permissions are denied.
    • Fix: Verify paths in config/bdf-form.php and check storage/framework/views for cached issues.

Debugging

  • Enable Debug Mode: Set 'debug' => true in config/bdf-form.php to log errors and validation failures to Laravel’s log.

  • Inspect Form Data: Use dd($form->getData()) or dd($form->errors()) to debug submissions.

  • Check Field Types: Typos in field types (e.g., 'type' => 'textbox') will render as plain text. Use valid types from the documentation.

Extension Points

  1. Custom Field Types: Create a new class extending B2PWeb\BDFForm\Field\AbstractField:

    class CustomField extends AbstractField
    {
        public function render(): string
        {
            return '<input type="custom" name="' . $this->name . '">';
        }
    }
    

    Register it in config/bdf-form.php:

    'field_types' => [
        'custom' => \App\CustomField::class,
    ],
    
  2. Override Rendering: Extend the render() method in your form class:

    public function render(): string
    {
        return '<div class="custom-form">' . parent::render() . '</div>';
    }
    
  3. Event Hooks: Listen for form events (e.g., form.submitted) via Laravel’s event system:

    event(new \B2PWeb\BDFForm\Events\FormSubmitted($form));
    
  4. Middleware: Use middleware to pre-process forms:

    public function handle($request, Closure $next)
    {
        $form = new MyForm();
        $form->setData($request->all());
        if ($form->isValid()) {
            // Pre-process data
        }
        return $next($request);
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky