简体   繁体   中英

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

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

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 (ie @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 .

引导标签输入

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM