S
S
square2015-10-23 18:56:22
symfony
square, 2015-10-23 18:56:22

How to work with an entity field of type array?

Hello everyone, there is such an entity:

class Ent
{
    /**
     * @var array
     *
     * @ORM\Column(name="data", type="array", nullable=false)
     *
     * @Assert\NotBlank
     * @Assert\Collection(fields = {
     *    "country" = @Assert\Required({
     *         @Assert\NotBlank,
     *         @Assert\Country
     *    }),
     *    "cnt" = @Assert\Required({
     *         @Assert\NotBlank,
     *         @Assert\Range(min = 1, max = 9)
     *    }),
     *    "startDate" = @Assert\Required({
     *         @Assert\NotBlank,
     *         @Assert\Date
     *    })
     * })
     */
    protected $data;
}

can someone tell me how to correctly create a FormType to work with the data field? Broke my whole brain.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2015-10-23
@prototype_denis

class Ent 
{
    public function __construct()
    {
        $data = new \Doctrine\Common\Collections\ArrayCollection();
    }
}

A
Alexey Skobkin, 2015-10-23
@skobkin

Well, the fact is that the type arraywas not originally intended to work with forms, as far as I know.
It can be quite logically used to store some data that contains several entities (not in the sense that is meant in Symfony), but it makes no sense to normalize them by spreading them across different fields or tables.
For example, the type arrayis used in IPhpFileStoreBundle to store information about a file.
So first of all, you can just not use array if that's not the case. Or, if it is exactly like that, you can try to make your own field type and a transformer for it.
Or, in the simplest version (but not the most correct) - add fields with'mapped' => falseand manually process the contents of the array and fill it with data. It is better, of course, to choose one of the previous methods.
Alternatively (I'm not sure if this will work here), you can try adding margins using the child-referencing syntax:

$formBuilder
    ->add('arrayField.key1')
    ->add('arrayField.key2')

But this is just an assumption that I have not tested myself.
UPD: Also have a look here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question