FloatFlower.Huang
FloatFlower.Huang

Reputation: 120

Handle form data by myself

I built a form with createFormBuilder

$form = $this->createFormBuilder($post)
        ->add("name", TextType::class, array("label"=>"Article Title"))
        ->add("content", TextareaType::class, array("label"=>"Article Content"))
        ->add("categories",
            EntityType::class,
            array(
                "class" => Category::class,
                "choice_label" => "name",
                "multiple" => true,
                "label" => "Article Category",
                "required" => false
            )
        )
        ->add("attachments", TextType::class, array("required"=>false))
        ->add("submit", SubmitType::class, array("label"=>"Add new article"))
        ->getForm();

the "attachments" variable is an entity variable, I want to get a json string from the form and search the database by myself, like this:

$em = $this->getDoctrine()->getManager();
$attachmentsRepository = $em->getRepository(Attachment::class);
$attachments = $post->getAttachments();
$json = json_decode($attachments);
$dataSize = sizeof($json);
for ($i = 0; $i < $dataSize; $i ++) {
    $attachment = $attachmentsRepository->find($json[$i]->getId());
    $post->addAttachments($attachment);
}
$em->persist($post);
$em->flush();

However, there is the error hint said that:

Could not determine access type for property "attachments" in class "App\Entity\Post".

I don't know how to solve this problem, if I add a @ORM\Column(type="string") in my Entity the json string will also be stored, I think this is not a good solution.

How do I modify my code?

Upvotes: 0

Views: 90

Answers (1)

Nicolai Fr&#246;hlich
Nicolai Fr&#246;hlich

Reputation: 52483

First of all to get rid of the error you need to add mapped => false to the field options of your attachments field.

If the attachments fields is configured as a mapped field the form component will look for a setAttachments() method or a public property attachments in your Post Entity to set the value - which do not exist in your Post entity. That's why you get the error message:

Could not determine access type for property "attachments" in class "App\Entity\Post".

In order to transform the submitted JSON string to Attachment entities yourself you need a custom data transformer!

A good example how create and use a data transformer can be found in the documentation chapter How to Use Data Transformers.

A clean solution would involve the attachments field being a CollectionType of EntityType, sending the whole form as a JSON POST request and using i.e FOSRestBundle's fos_rest.decoder.jsontoform body listener to decode the JSON request to a form.

The documentation for FOSRestBundle's body listener support can be found here.

Upvotes: 1

Related Questions