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

Forms Laravel Package

nette/forms

Nette Forms is a PHP form-building library for creating secure, reusable web forms with built-in validation, CSRF protection, rendering helpers, and easy component composition. Integrates smoothly with Nette Framework but works standalone in any PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nette/forms
    

    For Laravel integration, use nette/forms alongside nette/di (dependency injection) and latte/latte (if using Latte templates).

  2. Basic Form Creation:

    use Nette\Forms\Container;
    use Nette\Forms\Controls\TextInput;
    
    $form = new Container();
    $form->addText('username', 'Username')
         ->addRule($form::MIN_LENGTH, 'Too short', 3)
         ->addRule($form::MAX_LENGTH, 'Too long', 50);
    
  3. First Use Case:

    • Rendering in Laravel Blade:
      {!! $form->render() !!}
      
    • Handling Submission (in a controller):
      public function handleForm(Container $form)
      {
          if ($form->isSubmitted() && $form->isValid()) {
              $values = $form->getValues();
              // Process $values['username']
          }
      }
      

Key Starting Points


Implementation Patterns

1. Form Composition

  • Grouping Controls:
    $form->addGroup('Personal Info')
         ->addText('firstName')
         ->addText('lastName');
    
  • Dynamic Controls:
    $form->addDynamic('tags', function (Container $form, $name) {
        return $form->addTextInput($name);
    });
    

2. Validation Workflows

  • Rule Chaining:
    $email = $form->addEmail('email')
                 ->addRule($form::EMAIL, 'Invalid email')
                 ->addRule($form::FILLED, 'Email is required');
    
  • Custom Validators:
    $form->addRule(function ($value) {
        return strlen($value) > 10 || 'Must be >10 chars';
    });
    

3. Integration with Laravel

  • Service Provider Binding:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind('nette.form.factory', function () {
            return new \Nette\Forms\FormFactory();
        });
    }
    
  • Dependency Injection:
    use Nette\Forms\FormFactory;
    
    public function __construct(FormFactory $formFactory) {
        $this->formFactory = $formFactory;
    }
    

4. Client-Side Validation

  • Auto-Generated JavaScript:
    $form->setRenderer(new \Nette\Forms\Renderers\DefaultFormRenderer());
    echo $form->render();
    
    • Includes netteForms.js for real-time validation (e.g., data-nette-rules attributes).

5. Object Hydration

  • Mapping to Classes:
    $user = new User();
    $form->setValues($user); // Hydrates object properties
    $form->getValues($user); // Validates and updates object
    

6. File Uploads

  • Handling Uploads:
    $upload = $form->addUpload('avatar')
                   ->addRule($form::MAX_FILE_SIZE, 'Too large', 5 * 1024 * 1024);
    if ($form->isSubmitted() && $upload->isValid()) {
        $upload->getFile()->move(__DIR__ . '/uploads');
    }
    

7. Latte Template Integration

  • Macros for Forms:
    {form $form}
        {input username}
        {input email}
        {submit 'Save'}
    {/form}
    

Gotchas and Tips

Pitfalls

  1. CSRF Protection:

    • Forms auto-enable CSRF protection (via isSameSite() checks). Disable with:
      $form->setCsrfProtection(false);
      
    • Gotcha: Forgetting this in AJAX submissions may fail silently.
  2. Validation Scope:

    • getValues() only returns controls in the validation scope (BC break in v3.1+). Use:
      $form->getValues(true); // Force all values (deprecated in v3.2+)
      
    • Tip: Use getUntrustedValues() for raw POST data.
  3. Enum Hydration:

    • getValues(MyEnum::class) requires PHP 8.1+ and BackedEnums. For older PHP:
      $form->addSelect('status', ['active', 'inactive'])
           ->setDefaultValue('active');
      
  4. Client-Side Validation Quirks:

    • netteForms.js only validates elements with data-nette-rules. Ensure:
      $form->setRenderer(new \Nette\Forms\Renderers\DefaultFormRenderer());
      
    • Gotcha: Disabled controls ($control->setDisabled(true)) are skipped in client validation.
  5. Upload Limits:

    • UploadControl auto-sets MAX_FILE_SIZE, but check upload_max_filesize in php.ini for consistency.
  6. Latte Template Caching:

    • Latte macros ({form}, {input}) cache aggressively. Clear cache after form changes:
      $latte->addFilter('form', function () { return true; }); // Force refresh
      

Debugging Tips

  1. Validation Errors:

    • Check $form->getErrors() for server-side errors.
    • Client-side errors appear in the browser console (e.g., netteForms.js logs).
  2. Hidden Fields:

    • Use addHidden() for non-editable values:
      $form->addHidden('user_id')->setValue(auth()->id());
      
  3. Type Safety:

    • PHPStan reports false positives for Container::getValue(). Use:
      $value = $form->getValue('field', 'default');
      
  4. Event Handling:

    • Attach listeners after adding controls:
      $form->onSubmit[] = function ($form) {
          if ($form->isValid()) { /* ... */ }
      };
      

Extension Points

  1. Custom Renderers:

    • Extend DefaultFormRenderer for Bootstrap/Tailwind:
      class BootstrapRenderer extends DefaultFormRenderer {
          protected function renderControl(Control $control) {
              return '<div class="form-group">' . parent::renderControl($control) . '</div>';
          }
      }
      
  2. Dynamic Rules:

    • Use addRule() with closures for runtime validation:
      $form->addText('password')
           ->addRule(function ($value) use ($user) {
               return $value === $user->getPassword() || 'Incorrect';
           });
      
  3. Blueprints:

    • Generate form classes from PHP classes:
      $blueprint = new \Nette\Forms\Blueprint($user);
      $form = $blueprint->create();
      
  4. Modal Forms:

    • Use netteForms.js modals:
      Nette.showModal('#my-form', {title: 'Confirm'});
      

Config Quirks

  1. PHP 8.1+ Features:

    • Enums: Require BackedEnum for getValues() mapping.
    • Typed Properties: Use addInteger(), addFloat() for strict typing.
  2. Deprecated Methods:

    • Avoid getValues(true) (use getUntrustedValues()).
    • Replace addImage() with addImageButton().
  3. Latte-Specific:

    • {inputError} requires a control argument:
      {inputError email 'Invalid email'}
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope