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

Generate Form Bundle Laravel Package

bghanem/generate-form-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps to First Use
1. **Installation**
   ```bash
   composer require bghanem/generate-form-bundle

Ensure your project is Symfony 4.2+ (compatible with Symfony 5/6 via backward compatibility).

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

    return [
        // ...
        Bg\GenerateFormBundle\BgGenerateFormBundle::class => ['all' => true],
    ];
    
  2. Register Routes Add to config/routes.yaml:

    app_genform:
        resource: '@BgGenerateFormBundle/Controller/'
        type: annotation
        prefix: /genform
    
  3. Database Setup

    • Install Doctrine ORM and MakerBundle (if not already present):
      composer require symfony/orm-pack symfony/maker-bundle
      
    • Configure .env with your database (e.g., DATABASE_URL=mysql://user:pass@localhost/db_genform).
    • Run migrations:
      php bin/console doctrine:database:create
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
  4. First Use Case: Generate a Form

    • Visit /genform in your browser to access the admin interface.
    • Use the UI to define form fields (e.g., text, email, dropdown) and save as a "form template."
    • Test the generated form endpoint (e.g., /genform/submit/{formId}) via debug:router:
      php bin/console debug:router | grep genform
      

Implementation Patterns

Core Workflows

  1. Form Definition

    • Use the admin panel (/genform/admin) to:
      • Create form templates (e.g., "Contact Us," "User Profile").
      • Define fields (type, validation rules, labels, placeholders).
      • Set submission handlers (e.g., store in DB, send email).
    • Example field configuration (via UI):
      • Text Input: name="email", validation="email|required".
      • Dropdown: options=["Admin","User"], default="User".
  2. Rendering Forms

    • Embed forms in templates using Twig:
      {{ render(controller('BgGenerateFormBundle:Form:render', {'formId': 1})) }}
      
    • Pass dynamic data (e.g., pre-filled values):
      {{ render(controller('BgGenerateFormBundle:Form:render', {
          'formId': 1,
          'data': {'email': 'user@example.com'}
      })) }}
      
  3. Handling Submissions

    • Submit data to /genform/submit/{formId}.
    • Override default handlers by extending the bundle’s FormSubmitListener:
      // src/EventListener/CustomFormSubmitListener.php
      namespace App\EventListener;
      
      use Bg\GenerateFormBundle\Event\FormSubmitEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class CustomFormSubmitListener implements EventSubscriberInterface
      {
          public static function getSubscribedEvents()
          {
              return [
                  'bg_genform.form_submit' => 'onFormSubmit',
              ];
          }
      
          public function onFormSubmit(FormSubmitEvent $event)
          {
              $data = $event->getData();
              // Custom logic (e.g., save to DB, trigger email)
          }
      }
      
    • Register the listener in services.yaml:
      services:
          App\EventListener\CustomFormSubmitListener:
              tags: ['kernel.event_subscriber']
      
  4. Dynamic Forms

    • Fetch form templates programmatically:
      $formTemplate = $this->getDoctrine()
          ->getRepository(Bg\GenerateFormBundle\Entity\FormTemplate::class)
          ->find($formId);
      
    • Use in APIs (e.g., Symfony UX Live Component):
      use Bg\GenerateFormBundle\Form\Type\DynamicFormType;
      
      $builder->add('dynamicForm', DynamicFormType::class, [
          'form_id' => $formId,
          'data' => $initialData,
      ]);
      

Gotchas and Tips

Pitfalls

  1. Database Schema Conflicts

    • If you modify the bundle’s FormTemplate or FormField entities, drop and recreate the database to avoid schema conflicts:
      php bin/console doctrine:database:drop --force
      php bin/console doctrine:database:create
      php bin/console doctrine:migrations:migrate
      
    • Tip: Use --dry-run to preview migrations:
      php bin/console doctrine:migrations:diff --dry-run
      
  2. Route Conflicts

    • The bundle registers routes under /genform. If you have existing routes (e.g., /genform for an API), rename the prefix in routes.yaml:
      app_genform:
          prefix: /dynamic_forms  # Custom prefix
      
  3. Validation Rules

    • The bundle uses Symfony’s validator. Custom rules (e.g., @Assert\Callback) won’t work in the UI. Extend the FormField entity or use a custom field type:
      // src/Form/Extension/CustomFieldTypeExtension.php
      namespace App\Form\Extension;
      
      use Bg\GenerateFormBundle\Form\Type\FormFieldType;
      use Symfony\Component\Form\AbstractTypeExtension;
      use Symfony\Component\Form\FormBuilderInterface;
      
      class CustomFieldTypeExtension extends AbstractTypeExtension
      {
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              $builder->addEventListener(\Symfony\Component\Form\FormEvents::PRE_SET_DATA, function ($event) {
                  $data = $event->getData();
                  if ($data->getType() === 'custom') {
                      $event->getForm()->add('custom_rule', TextType::class);
                  }
              });
          }
      
          public function getExtendedType(): string
          {
              return FormFieldType::class;
          }
      }
      
  4. Performance with Large Forms

    • The bundle loads all form fields into memory. For forms with >50 fields, optimize by:
      • Lazy-loading fields via DQL:
        $qb = $this->createQueryBuilder('f')
            ->where('f.form = :form')
            ->setParameter('form', $formTemplate);
        $fields = $qb->getQuery()->getResult();
        
      • Caching form templates:
        $cache = $this->get('cache.app');
        $formTemplate = $cache->get('form_'.$formId, function() use ($formId) {
            return $this->getDoctrine()->getRepository(FormTemplate::class)->find($formId);
        });
        
  5. Translation Issues

    • Field labels/placeholders use Symfony’s translation system. Ensure your translations/ directory is configured:
      # config/packages/translation.yaml
      framework:
          translation:
              paths: ['%kernel.project_dir%/translations']
      
    • Add translations for dynamic keys (e.g., form.field.{field_name}.label).

Debugging Tips

  1. Check Form Submission Data

    • Temporarily dump submitted data in a listener:
      public function onFormSubmit(FormSubmitEvent $event)
      {
          file_put_contents(
              'var/log/genform_submission.log',
              print_r($event->getData(), true)
          );
      }
      
  2. Validate Form Field Types

    • The bundle supports basic types (text, email, select, etc.). For custom types (e.g., date), ensure the FormField entity’s type field matches Symfony’s form types:
      // Extend the bundle's FormFieldType class
      class ExtendedFormFieldType extends FormFieldType
      {
          public function configureOptions(OptionsResolver $resolver)
          {
              $resolver->setDefaults([
                  'types' => array_merge(parent::getDefaultTypes(), ['date' => DateType::class]),
              ]);
          }
      }
      
  3. Clear Cache After Changes

    • After modifying templates or entities, clear the cache:
      php bin/console cache:clear
      

Extension Points

  1. Custom Field Types
    • Extend the bundle’s FormFieldType to support new field types (e.g., rich text, file uploads):
      // src/Form/Type/CustomFieldType.php
      namespace App\Form\Type;
      
      use Bg\GenerateFormBundle\Form\Type\FormFieldType;
      use Symfony\Component\Form\Extension\Core\Type\TextareaType;
      
      class CustomFieldType extends FormFieldType
      {
          protected function getTypeMap()
          {
              return array_merge(parent::getTypeMap(), [
                  'rich_text' => TextareaType::class,
              ]);
          }
      }
      
    • Override
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