How to add an array (customisable) to a symfony2 form (with sonata Admin)?

浪子不回头ぞ 提交于 2019-12-06 07:35:09

问题


I have a simple form with Sonata admin.

I would like the user could add a list of integers (as many as he wants). And after it would be store as an array in my object:

[1, 2, 3, 6, 9]

There any way of doing it without creating another class to instantiate the integers?

UPDATE:

The only way I know how to something close is using choice like:

 ->add('type', 'choice', [
                "required"           => true,
                "expanded"           => true,
                "multiple"           => false,
                "choices"            => Campanha::getTypes(),
            ])

But with that I have a limited number of choices, I would like that it would be free to the user to add the quantity of numbers and the values he wants


回答1:


Try looking into sonata_type_native_collection:

From the Sonata Admin Docs:

This bundle handle the native Symfony collection form type by adding:

  • an add button if you set the allow_add option to true.
  • a delete button if you set the allow_delete option to true.

And the Symfony collection form type:

This field type is used to render a "collection" of some field or form. In the easiest sense, it could be an array of TextType fields that populate an array emails values.

So, for your case, maybe something like:

->add('type', 'sonata_type_native_collection', [
    'required' => true,
    'entry_type' => 'number',
    'options' => [
        // Any options you'd like the integer fields to have.
    ]
])

(This doesn't speak at all to the change's you'll need to make to the underlying model, of course.)

Edit: Changed the 'entry_options' array key to 'options', as per @Matheus Oliveira's comment.




回答2:


All you need to accomplish this is a Data Transformer. Look at an example:

namespace AppBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class ArrayToStringTransformer implements DataTransformerInterface
{
    public function transform($array)
    {
        if (null === $array) {
            $array = array();
        }

        if (!is_array($array)) {
            throw new TransformationFailedException('Expected an array.');
        }

        return implode(',', $array);
    }

    public function reverseTransform($string)
    {
        if (null === $string || '' === $string) {
            return array();
        }

        if (!is_string($string)) {
            throw new TransformationFailedException('Expected a string.');
        }

        return explode(',', $string);
    }
}

Later, use it where there is an array field. For greater reusability let's create a custom field type which extends of TextType:

namespace AppBundle\Form\Type;

use AppBundle\Form\DataTransformer\ArrayToStringTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class ArrayTextType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new ArrayToStringTransformer());
    }

    public function getParent()
    {
        return TextType::class;
    }
}

That's it! Now you can manage your array fields safely by using your ArrayTextType:

// in any controller context

public function fooAction() 
{
    $data = array(
        'tags' => array(1, 2, 3, 4, 5),
    );

    $form = $this->createFormBuilder($data)
        ->add('tags', ArrayTextType::class)
        ->getForm();

    return $this->render('default/index.html.twig', array('form' => $form->createView()));
}

Also we can use any Doctrine array mapped field (i.e. @ORM\Column(name="tags", type="array")).

Output result:


For better data entry I recommend using with this the Bootstrap Tags Input jQuery plugin. See examples here.



来源:https://stackoverflow.com/questions/40046848/how-to-add-an-array-customisable-to-a-symfony2-form-with-sonata-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!