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

sulu/form-bundle

SuluFormBundle adds dynamic form creation to Sulu Admin. Content managers build and arrange fields in a grid, configure email notifications, and power contact/sweepstake forms. Built on the Symfony Form Component with theming support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sulu/form-bundle
    

    Ensure your project meets the requirements (PHP 8.2+, Symfony 6.4+, Sulu 3.0+).

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Sulu\Form\SuluFormBundle::class => ['all' => true],
    ];
    
  3. Run Migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. Generate a Form:

    php bin/console sulu:form:generate
    

    This creates a basic form structure in the Sulu Admin UI under Forms.


First Use Case: Creating a Contact Form

  1. Admin UI Setup:

    • Navigate to Forms in Sulu Admin.
    • Click Create to add a new form.
    • Configure fields (e.g., Text, Email, Submit) in the drag-and-drop editor.
    • Set up email notifications under the Email tab.
  2. Frontend Integration: Embed the form in a Twig template:

    {{ render(controller('SuluFormBundle:Form:render', {
        'formId': 'your_form_id',
        'action': path('sulu_form_submit', {'formId': 'your_form_id'})
    })) }}
    
  3. Handle Submissions: Extend the form handler to process submissions:

    // config/services.yaml
    Sulu\Form\Handler\FormHandlerInterface: '@App\Service\CustomFormHandler'
    

Implementation Patterns

Dynamic Form Workflows

  1. Field Configuration:

    • Use the Dynamic Form Builder in Sulu Admin to define fields (e.g., Text, Checkbox, Media).
    • Configure validation rules (e.g., required, email) via the UI.
  2. Email Notifications:

    • Set up email templates in the Email tab of the form.
    • Use Twig variables like {{ formData.name }} to dynamically populate emails.
    • Example for Sendinblue integration:
      # config/packages/sulu_form.yaml
      sulu_form:
          sendinblue:
              enabled: true
              api_key: '%env(SENDINBLUE_API_KEY)%'
      
  3. Form Submission Handling:

    • Extend the default handler to customize logic:
      namespace App\Service;
      
      use Sulu\Form\Handler\FormHandlerInterface;
      use Sulu\Form\Handler\FormHandlerResult;
      use Sulu\Form\Handler\FormHandlerResultInterface;
      
      class CustomFormHandler implements FormHandlerInterface
      {
          public function handle(array $formData, string $formId): FormHandlerResultInterface
          {
              // Custom logic (e.g., save to database, trigger events)
              return new FormHandlerResult(true, ['message' => 'Form submitted!']);
          }
      }
      
  4. Frontend Rendering:

    • Use Twig extensions for dynamic rendering:
      {% form_theme form _self %}
      {{ form_row(form.field_name) }}
      
    • For AJAX submissions, use the sulu_form_submit route with a CSRF token:
      fetch('/form/submit', {
          method: 'POST',
          body: JSON.stringify({ formData, _csrf_token: '{{ csrf_token('sulu_form_submit') }}' }),
          headers: { 'Content-Type': 'application/json' }
      });
      

Integration with Sulu Ecosystem

  1. Media Fields:

    • Use the Media field type to attach files/images.
    • Configure allowed media types in the Sulu Admin under Settings > Media.
  2. Localization:

    • Forms support multi-language content. Use the Locale dropdown in the Admin UI to manage translations.
  3. Workflows:

    • Leverage Sulu’s workflow system to publish/unpublish forms:
      # config/packages/sulu_workflow.yaml
      sulu_workflow:
          resources:
              Sulu\Form\Rest\Resource\FormResource: ~
      
  4. Testing:

    • Use the generate-form command to create test forms:
      php bin/console sulu:form:generate --name="Test Form" --locale="en"
      
    • Test submissions with PHPUnit:
      $client = static::createClient();
      $crawler = $client->request('GET', '/form/render');
      $form = $crawler->selectButton('Submit')->form([
          'formData[email]' => 'test@example.com',
      ]);
      $client->submit($form);
      

Gotchas and Tips

Common Pitfalls

  1. CSRF Token Issues:

    • If using AJAX, ensure the CSRF token is included in the request.
    • Disable CSRF for specific forms (not recommended for production):
      # config/packages/sulu_form.yaml
      sulu_form:
          csrf_protection:
              disabled: true
      
  2. Field Validation:

    • Hidden fields (Hidden) and spacers (Spacer) ignore the required constraint by default.
    • Custom validation requires extending the form type or using Symfony’s Constraints.
  3. Media Uploads:

    • Ensure the MediaManagerInterface is properly configured in your services.yaml:
      Sulu\Form\Handler\FormHandlerInterface:
          arguments:
              $mediaManager: '@sulu_media.media_manager'
      
  4. Locale Fallbacks:

    • Forms rely on Sulu’s locale system. If translations are missing, the system falls back to the default locale.
    • Debug missing translations with:
      php bin/console debug:translation sulu_form
      

Debugging Tips

  1. Form Submission Errors:

    • Check the FormHandlerResult for errors:
      $result = $formHandler->handle($formData, $formId);
      if (!$result->isSuccess()) {
          throw new \RuntimeException($result->getMessage());
      }
      
    • Enable debug mode in config/packages/dev/sulu_form.yaml:
      sulu_form:
          debug: true
      
  2. Database Issues:

    • Verify migrations are applied:
      php bin/console doctrine:migrations:status
      
    • Clear the cache after changes:
      php bin/console cache:clear
      
  3. Sendinblue Integration:

    • Validate API keys and pagination settings:
      sulu_form:
          sendinblue:
              pagination:
                  limit: 100
      
    • Test with the sulu_form.sendinblue.contact_created event:
      $eventDispatcher->addListener(
          'sulu_form.sendinblue.contact_created',
          function ($event) {
              // Log or debug the event data
          }
      );
      

Extension Points

  1. Custom Form Types:

    • Create a new form type by extending Sulu\Form\Type\AbstractType:
      namespace App\Form\Type;
      
      use Sulu\Form\Type\AbstractType;
      use Symfony\Component\Form\FormBuilderInterface;
      
      class CustomFieldType extends AbstractType
      {
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              $builder->add('custom_field', TextType::class);
          }
      
          public function getBlockPrefix(): string
          {
              return 'app_custom_field';
          }
      }
      
    • Register the type in resources/config/sulu_form.yaml:
      sulu_form:
          types:
              app_custom_field: App\Form\Type\CustomFieldType
      
  2. Event Listeners:

    • Listen to form submission events:
      namespace App\EventListener;
      
      use Sulu\Form\Event\FormSubmittedEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class FormSubmittedListener implements EventSubscriberInterface
      {
          public static function getSubscribedEvents(): array
          {
              return [
                  FormSubmittedEvent::NAME => 'onFormSubmitted',
              ];
          }
      
          public function onFormSubmitted(FormSubmittedEvent $event)
          {
              // Handle submission (e.g., log, notify)
          }
      }
      
  3. Twig Extensions:

    • Extend Twig rendering with custom filters:
      namespace App\Twig;
      
      use Twig\Extension\AbstractExtension;
      use Twig\TwigFilter;
      
      class FormExtension extends AbstractExtension
      {
          public function getFilters(): array
          {
              return [
                  new TwigFilter('format_form_data', [$this, 'formatData']),
              ];
          }
      
          public function formatData(array $data): string
          {
              return json_encode($data, JSON_PRETTY_PRINT);
          }
      }
      
    • Register in config/packages/twig.yaml:
      twig:
          extensions:
              - App\Twig\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.
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