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

Key Value Form Bundle Laravel Package

alexandre-fernandez/key-value-form-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alexandre-fernandez/key-value-form-bundle
    

    Add to config/bundles.php (Symfony) or config/app.php (Laravel via bridge):

    AlexandreFernandez\KeyValueFormBundle\AlexandreFernandezKeyValueFormBundle::class => ['all' => true],
    
  2. Basic Usage Register the form type in a Symfony controller (or Laravel via bridge):

    use AlexandreFernandez\KeyValueFormBundle\Form\Type\KeyValueType;
    
    $builder->add('settings', KeyValueType::class, [
        'label' => 'Configuration Settings',
        'required' => false,
        'entry_type' => TextType::class, // Default entry type (Symfony Form)
        'entry_options' => ['attr' => ['class' => 'form-control']],
    ]);
    
  3. First Use Case Store dynamic key-value pairs (e.g., user preferences, API configs):

    // In a Laravel controller
    public function updateSettings(Request $request) {
        $form = $this->createForm(KeyValueType::class, $request->user()->settings);
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            $request->user()->update(['settings' => $form->getData()]);
            return redirect()->back()->with('success', 'Settings saved!');
        }
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Key-Value Management

    // Laravel Form Request example
    public function rules() {
        return [
            'dynamic_data' => ['required', KeyValueType::class, [
                'entry_type' => TextareaType::class, // Customize entry fields
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => true, // Enable AJAX row addition
            ]],
        ];
    }
    
  2. Integration with Laravel Collections Convert form data to a Laravel Collection:

    $data = $form->getData();
    $collection = collect($data)->mapWithKeys(fn($value, $key) => [$key => $value]);
    
  3. Validation Patterns

    $builder->add('metadata', KeyValueType::class, [
        'entry_options' => [
            'constraints' => [
                new NotBlank(),
                new Length(['max' => 255]),
            ],
        ],
    ]);
    
  4. Twig Template Customization Override the default template in resources/views/form/key_value_widget.html.twig:

    {% extends '@KeyValueForm/key_value_widget.html.twig' %}
    {% block key_value_row %}
        <div class="row">
            <div class="col-md-3">{{ form_row(entry.key) }}</div>
            <div class="col-md-6">{{ form_row(entry.value) }}</div>
        </div>
    {% endblock %}
    

Gotchas and Tips

Pitfalls

  1. CSRF Token Issues

    • If using AJAX prototype additions, ensure the CSRF token is included in requests:
      $.ajaxSetup({
          headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
      });
      
  2. Data Serialization

    • Laravel’s json:encode() may break nested structures. Use json_encode($data, JSON_UNESCAPED_UNICODE) for complex values.
  3. Prototype Cloning

    • If prototype is enabled but rows don’t clone, verify:
      • The prototype_name option is set (default: key_value_prototype).
      • jQuery is loaded (required for prototype functionality).
  4. Symfony/Laravel Bridge Quirks

    • Laravel’s FormRequest may not auto-bind KeyValueType data. Explicitly cast:
      $form->getData() === (array) $request->input('dynamic_data');
      

Debugging Tips

  1. Dump Raw Data

    dd($form->getData()); // Check structure before saving
    
  2. Template Overrides

    • Clear cache after modifying Twig templates:
      php artisan view:clear
      
  3. Validation Errors

    • Use dump($form->getErrors()) to inspect nested errors.

Extension Points

  1. Custom Entry Types

    $builder->add('tags', KeyValueType::class, [
        'entry_type' => EntityType::class,
        'entry_options' => [
            'class' => Tag::class,
            'choice_label' => 'name',
        ],
    ]);
    
  2. Dynamic Entry Options

    $builder->add('pricing', KeyValueType::class, [
        'entry_options' => function ($key, $value, FormInterface $form) {
            return ['attr' => ['data-key' => $key, 'data-value' => $value]];
        },
    ]);
    
  3. Laravel Service Provider Hooks Extend the bundle via a service provider:

    public function boot() {
        KeyValueType::defaultOptions(function (OptionsResolver $resolver) {
            $resolver->setDefaults([
                'attr' => ['class' => 'key-value-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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager