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

burgov/key-value-form-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require burgov/key-value-form-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    return [
        // ...
        Burgov\Bundle\KeyValueFormBundle\BurgovKeyValueFormBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Add KeyValueType to a form builder in a controller or service:

    use Burgov\Bundle\KeyValueFormBundle\Form\Type\KeyValueType;
    use Symfony\Component\Form\Extension\Core\Type\TextType;
    
    $builder->add('config', KeyValueType::class, [
        'value_type' => TextType::class,
        'label' => 'Configuration Settings',
    ]);
    
  3. Template Rendering: Use Symfony’s collection rendering (e.g., prototype for dynamic fields):

    {{ form_row(form.config) }}
    

    For dynamic fields, include the prototype template (see Symfony Collection Docs).


Implementation Patterns

Common Workflows

  1. Basic Key-Value Storage: Use KeyValueType for editable key-value pairs (e.g., user preferences, API configs):

    $builder->add('metadata', KeyValueType::class, [
        'value_type' => TextType::class,
        'value_options' => ['attr' => ['class' => 'metadata-value']],
    ]);
    
  2. Custom Key/Value Types: Override default types (e.g., EmailType for keys, NumberType for values):

    $builder->add('settings', KeyValueType::class, [
        'key_type' => EmailType::class,
        'value_type' => NumberType::class,
    ]);
    
  3. Data Transformation: Bind to an array or object with getData()/setData():

    $form->getData(); // Returns ['key1' => 'value1', 'key2' => 'value2']
    
  4. Validation: Add constraints to the root form or via value_options:

    $builder->add('tags', KeyValueType::class, [
        'value_type' => TextType::class,
        'value_options' => [
            'constraints' => [new Length(['max' => 50])],
        ],
    ]);
    
  5. Dynamic Fields: Use allow_add/allow_delete for interactive forms:

    $builder->add('dynamic_data', KeyValueType::class, [
        'value_type' => TextType::class,
        'allow_add' => true,
        'allow_delete' => true,
        'prototype' => true, // Enable prototype template
    ]);
    

Integration Tips

  • Twig Templates: Extend Symfony’s collection templates (e.g., key_value_row.html.twig) for custom styling.
  • APIs: Serialize/deserialize key-value data in JSON APIs using JsonResponse/JsonRequest.
  • Database: Store key-value pairs as JSON in a single column (e.g., config table with settings column).

Gotchas and Tips

Pitfalls

  1. Missing value_type: Required option—omit it, and the form will fail silently or throw an exception.

    // ❌ Fails
    $builder->add('bad_form', KeyValueType::class);
    
  2. Prototype Template: Forgetting to include the prototype template breaks dynamic field addition. Ensure:

    {% include 'BurgovKeyValueFormBundle:Form:key_value_row.html.twig' %}
    
  3. Data Binding: Keys/values must be strings or castable to strings. Non-string keys (e.g., objects) will break rendering.

  4. CSRF in Dynamic Forms: Dynamic fields require CSRF tokens. Use Symfony’s form_row with prototype:

    {{ form_row(form.dynamic_data, {'prototype': true}) }}
    
  5. Validation Scope: Constraints in value_options apply to individual values, not the entire collection. Use root form constraints for global rules.

Debugging

  • Form Errors: Check {{ form_errors(form) }} in Twig or dump($form->getErrors()) in PHP.
  • Data Flow: Debug with var_dump($form->getData()) to verify key-value binding.
  • Template Issues: Clear cache (php bin/console cache:clear) if templates render incorrectly.

Extension Points

  1. Custom Templates: Override key_value_row.html.twig in templates/Bundles/BurgovKeyValueFormBundle/Form/.
  2. Event Subscribers: Hook into PRE_SET_DATA/POST_SUBMIT for preprocessing/postprocessing:
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $data = $event->getData() ?: [];
        $data['default_key'] = 'default_value';
        $event->setData($data);
    });
    
  3. Form Events: Use FormEvents::SUBMIT to transform data before submission:
    $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        $data = array_map('strtoupper', $data); // Example: uppercase keys
        $event->setData($data);
    });
    

Configuration Quirks

  • Default Options: key_type defaults to TextType, but value_type must be specified.
  • Allowed Keys: The README mentions allowed_key... options (likely a typo for allowed_keys). Use:
    $builder->add('restricted', KeyValueType::class, [
        'value_type' => TextType::class,
        'allowed_keys' => ['admin', 'user'], // Only allow these keys
    ]);
    
  • Empty Values: Handle null/empty values in PRE_SET_DATA to avoid validation errors.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware