Giter Site home page Giter Site logo

keyvalueformbundle's Introduction

KeyValueFormBundle

A form type for managing key-value pairs.

Installation

$ composer require burgov/key-value-form-bundle:@stable

Then add the bundle to your application:

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Burgov\Bundle\KeyValueFormBundle\BurgovKeyValueFormBundle(),
        // ...
    );
}

Usage

To add to your form, use the KeyValueType type:

use Burgov\Bundle\KeyValueFormBundle\Form\Type\KeyValueType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

$builder->add('parameters', KeyValueType::class, array('value_type' => TextType::class));

// or

$formFactory->create(KeyValueType::class, $data, array('value_type' => TextType::class));

The type extends the collection type, so for rendering it in the browser, the same logic is used. See the Symfony docs on collection types for an example on how to render it client side.

The type adds four options to the collection type options, of which one is required:

  • value_type (required) defines which form type to use to render the value field
  • value_options optional options to the child defined in value_type
  • key_type defines which form type to use to render the key field (default is a text field)
  • key_options optional options to the child defined in key_type
  • allowed_keys if this option is provided, the key field (which is usually a simple text field) will change to a choice field, and allow only those values you supplied in the this option.
  • use_container_object see explanation below at 'The KeyValueCollection'

Besides that, this type overrides some defaults of the collection type and it's recommended you don't change them: type is set to BurgovKeyValueRow::class and allow_add and allow_delete are always true.

Working with SonataAdminBundle

In order to render your form with add/remove buttons, you need to extend the template SonataAdminBundle:Form:form_admin_fields.html.twig and add this little piece of code

{% block burgov_key_value_widget %}
    {{- block('sonata_type_native_collection_widget') -}}
{% endblock %}

The KeyValueCollection

To work with collections and the Symfony2 form layer, you can provide an adder and a remover method. This however only works if the adder method expects one argument only. This bundle provides composed key-value pairs.

Your model class typically will provide a method like:

class Model
{
    public function addOption($key, $value)
    {
        $this->options[$key] = $value;
    }
}

This will lead to the add method not being found by the form layer. To work around this problem, the bundle provides the KeyValueCollection object. To use it, you need to set the use_container_object option on the form type to true. A form definition could look like this:

/** @var $builder Symfony\Component\Form\FormBuilderInterface */
$builder->add('options', 'burgov_key_value', array(
    'required' => false,
    'value_type' => TextType::class,
    'use_container_object' => true,
));

Your model class then needs to provide a setOptions method that accepts a Burgov\Bundle\KeyValueFormBundle\KeyValueContainer argument. A flexible implementation might look like this:

class Model
{
    /**
     * Set the options.
     *
     * @param array|KeyValueContainer|\Traversable $data Something that can be converted to an array.
     */
    public function setOptions($options)
    {
        $this->options = $this->convertToArray($options);
    }

    /**
     * Extract an array out of $data or throw an exception if not possible.
     *
     * @param array|KeyValueContainer|\Traversable $data Something that can be converted to an array.
     *
     * @return array Native array representation of $data
     *
     * @throws InvalidArgumentException If $data can not be converted to an array.
     */
    private function convertToArray($data)
    {
        if (is_array($data)) {
            return $data;
        }

        if ($data instanceof KeyValueContainer) {
            return $data->toArray();
        }

        if ($data instanceof \Traversable) {
            return iterator_to_array($data);
        }

        throw new InvalidArgumentException(sprintf('Expected array, Traversable or KeyValueContainer, got "%s"', is_object($data) ? getclass($data) : get_type($data)));
    }
}

keyvalueformbundle's People

Contributors

burgov avatar cordoval avatar dbu avatar electricmaxxx avatar hacfi avatar hason avatar julienfalque avatar lemoinem avatar mathroc avatar plopix avatar robhunt3r avatar sgoettschkes avatar wouterj avatar yellow1912 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

keyvalueformbundle's Issues

bug with using the form

we started to use this in a sonata admin form. but we get an error from the form layer:

Found the public method "removeExtraProperty()", but did not find a public "addExtraProperty()" on class PHPCRProxies__CG__\Symfony\Cmf\Bundle\SeoBundle\Doctrine\Phpcr\SeoMetadata

the form type is at
https://github.com/symfony-cmf/SeoBundle/blob/master/Form/Type/SeoMetadataType.php#L42
and the method at
https://github.com/symfony-cmf/SeoBundle/blob/master/Model/SeoMetadata.php#L211

i found that PropertyAccessor::402 is looking for $addMethodFound = $this->isAccessible($reflClass, $addMethod, 1);, that is a method with only one parameter. if i change the signature of our addExtraProperty it indeed is found, but i only get the key and not the value.

if you want to see all in action, you could set up the cmf sandbox branch https://github.com/symfony-cmf/cmf-sandbox/tree/prepare-rc and go to http://cmf.lo/app_dev.php/de/admin/sandbox/main/demoseocontent/cms/content/home/edit and there on the SeoConfiguration tab and play with the collections.

do we just have the wrong signature on the method? or what should we do to make things work?

[Question] How to render line instead of block

This is not a issue with the bundle itself but I was wondering if you know how to easily render the form as a row instead of a block.

This is how I would want to it to look like (this is a override of a row rendering I did in sonata)
Screenshot from 2019-12-06 23-42-02

And this is the default rendering of your component:

Screenshot from 2019-12-06 23-42-34

Maybe there is a generic solution (class, css, configurion) I don't want to end up overriding with
{% block {form_input_name}_row %} for all the input I need to do so...

Implementing with Symfony, which ORM type ?

Which ORM Column type should I be using to save this to the database ? I tried text and simple_array, but I can't get it to work. When using text, it saves as 'Array', when using simple_array, it only saves the value of the last item in the collection.

Entity :

/**
     * Store key-value options
     * @ORM\Column(type="simple_array", name="options", nullable=true)
     */
    protected $options;

public function getOptions()
    {
        return $this->options;
    }

    public function setOptions($options)
    {
        $this->options = $this->convertToArray($options);
    }

    private function convertToArray($data)
    {
        if (is_array($data)) {
            return $data;
        }

        if ($data instanceof KeyValueContainer) {
            return $data->toArray();
        }

        if ($data instanceof \Traversable) {
            return iterator_to_array($data);
        }

        throw new \InvalidArgumentException(sprintf('Expected array, Traversable or KeyValueContainer, got "%s"', is_object($data) ? getclass($data) : get_type($data)));
    }

Form :

$builder->add('options', KeyValueType::class, [
            'required' => false,
            'value_type' => TextType::class,
            'use_container_object' => true,
        ]);

Merge PR #15 Failed

Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in /Form/Type/KeyValueType.php on line 74:
$resolver->setAllowedTypes('allowed_keys' => array('null', 'array'));

should be :
$resolver->setAllowedTypes(array('allowed_keys' => array('null', 'array')));

Model vs Entity vs FormTypes

I do not know what the documentation refers to when it talk about "your model"

To work with collections and the Symfony2 form layer, you can provide an adder
and a remover method. This however only works if the adder method expects one
argument only. This bundle provides composed key-value pairs.

Your model class typically will provide a method like:

I have doctrine based entities and form types in my project, but not models.

is not working with symfony 3

The bundle is not working in symfony3.
The bundle is trying to load form types with alias instead of ::class.
Could you fix this?.
Thx and regards.

Can't get it working

I cloned the extraProperties field for my own content, and using it like this

            ->add('extraProperties', 'burgov_key_value', array(
                'label' => 'form.label_extraProperties',
                'value_type' => 'text',
                'use_container_object' => true,
            ))

But it doesn't show anything, just the label.

Here are my classes

interface GameModelInterface {

    /**
     * @param array|\Traversable|KeyValueContainer
     */
    public function setExtraProperties($extraProperties);
    /**
     * @return array
     */
    public function getExtraProperties();
    /**
     * Add a key-value pair for meta attribute property.
     *
     * @param string $key
     * @param string $value
     */
    public function addExtraProperty($key, $value);
}
class GameModel implements GameModelInterface {

    /**
     * To store meta tags for type property.
     *
     * @var array
     */
    private $extraProperties = array();

    /**
     * {@inheritDoc}
     */
    public function setExtraProperties($extraProperties)
    {
        $this->extraProperties = $this->toArray($extraProperties);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getExtraProperties()
    {
        return $this->extraProperties;
    }

    /**
     * {@inheritDoc}
     */
    public function addExtraProperty($key, $value)
    {
        $this->extraProperties[$key] = (string) $value;
    }

    /**
     * {@inheritDoc}
     */
    public function removeExtraProperty($key)
    {
        if (array_key_exists($key, $this->extraProperties)) {
            unset($this->extraProperties[$key]);
        }
    }
    /**
     * Extract an array out of $data or throw an exception if not possible.
     *
     * @param array|KeyValueContainer|\Traversable $data Something that can be converted to an array.
     *
     * @return array Native array representation of $data
     *
     * @throws InvalidArgumentException If $data can not be converted to an array.
     */
    private function toArray($data)
    {
        if (is_array($data)) {
            return $data;
        }

        if ($data instanceof KeyValueContainer) {
            return $data->toArray();
        }

        if ($data instanceof \Traversable) {
            return iterator_to_array($data);
        }

        throw new InvalidArgumentException(sprintf('Expected array, Traversable or KeyValueContainer, got "%s"', is_object($data) ? getclass($data) : get_type($data)));
    }
} 
class GameContent extends stc implements GameModelInterface {
    /**
     * @var string
     */
    protected $app;

    /**
     * To store meta tags for type property.
     *
     * @var array
     */
    private $extraProperties = array();

    /**
     * {@inheritDoc}
     */
    public function setExtraProperties($extraProperties)
    {
        $this->extraProperties = $this->toArray($extraProperties);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getExtraProperties()
    {
        return $this->extraProperties;
    }

    /**
     * {@inheritDoc}
     */
    public function addExtraProperty($key, $value)
    {
        $this->extraProperties[$key] = (string) $value;
    }

    /**
     * {@inheritDoc}
     */
    public function removeExtraProperty($key)
    {
        if (array_key_exists($key, $this->extraProperties)) {
            unset($this->extraProperties[$key]);
        }
    }
(... more content)

It works if I use collectionType and using allowadd and allowremove, but it shows only one field (and I want a key=> value field)

Query over multivalue assoc field

Is it possible to make query with QueryBuilder which will mach multivalue assoc field by exact combination of index and value

$qb->andWhere()->like()->field("a.testFieldAssoc1")->literal("key1=>value1")->end();

thx,
Milos

nesting KeyValues

Hi,

Does KeyValue support nesting? I mean, can it deal with nested key-value array like the following?

["someKey" => ["someOtherKey" => "someOtherValue"],
"someKey2" => "someValue2"]

Extend layout error?

Hi, i'm using Symfony 4.3
When i exends the @SonataAdmin/Form/form_admin_fields.html.twig template, i add

{% block burgov_key_value_widget %}
{{- block('sonata_type_native_collection_widget') -}}
{% endblock %}

but then there is an error

Variable "compound" does not exist.

some help?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.