Я пытаюсь отправить JSON через сложную форму.Я не могу понять, чего мне не хватает.«Нормальная» форма функционирует.Я могу получать сериализованные данные с группами.
Класс TaskBoard
class TaskBoard
{
/**
* @var integer $id id
*
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var \DateTime $createdTime createdTime
*
* @ORM\Column(type="datetime")
* @Assert\DateTime()
*/
private $createdTime;
/**
* @var \DateTime $lastUpdatedTime lastUpdatedTime
*
* @ORM\Column(type="datetime", nullable=true)
* @Assert\DateTime()
*/
private $lastUpdatedTime;
/**
* @var string $name name
*
* @ORM\Column(type="string", length=20)
* @Assert\Type("string")
* @Assert\NotBlank()
* @Assert\Length(
* min = 2,
* max = 20,
* minMessage = "The name must be at least {{ limit }} characters long",
* maxMessage = "The name cannot be longer than {{ limit }} characters"
* )
*/
private $name;
/**
* @var App\Entity\User $user user
*
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="taskboards", cascade={"persist"})
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* @var string $description description
*
* @ORM\Column(type="text", nullable=true)
* @Assert\Type("string")
*/
private $description;
/**
* @var App\Entity\Status $status status
*
* @ORM\ManyToOne(targetEntity="App\Entity\Status", inversedBy="taskboards", cascade={"persist"})
* @ORM\JoinColumn(name="status_id", referencedColumnName="id", nullable=false)
*/
private $status;
/**
* @var boolean $completed completed
*
* @ORM\Column(type="boolean")
*/
private $completed;
/**
* @var \DateTime $deadLine deadLine
*
* @ORM\Column(type="date", nullable=true)
* @Assert\DateTime()
* @Assert\GreaterThanOrEqual("today")
*/
private $deadLine;
Состояние класса
class Status
{
/**
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=20)
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="App\Entity\TaskBoard", mappedBy="status", cascade={"persist"})
*/
public $taskboards;
Класс пользователя
class User extends BaseUser
{
/**
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="App\Entity\TaskBoard", mappedBy="user", cascade={"persist"})
*/
public $taskboards;
Форма
class TaskBoardType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name', TextType::class)
->add('user', EntityType::class, array(
'class' => User::class,
'choice_label' => 'username',
)
)
->add('description', TextareaType::class, array(
'required' => false
))
->add('status', EntityType::class, array(
'class' => Status::class,
'choice_label' => 'name',
)
)
->add('deadLine', DateTimeType::class)
;
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => TaskBoard::class,
'csrf_protection' => false,
]);
}
Контроллер
class TaskBoardAPIController extends AbstractController {
public function postTaskBoard(Request $request) {
$form = $this->createForm(TaskBoardType::class, new TaskBoard());
$data = json_decode(
$request->getContent(), true
);
var_dump($data);
$form->submit($data);
if (!$form->isValid()) {
return new JsonResponse(
[
'status' => 'error',
'errors' => $form->getErrors(),
'form' => $form,
], JsonResponse::HTTP_BAD_REQUEST
);
}
$this->entityManager->persist($form->getData());
$this->entityManager->flush();
return new JsonResponse(
[
'status' => 'ok',
], JsonResponse::HTTP_CREATED
);
}
JSON отправлено
{
"name": "XXX",
"user": {
"id": 1,
"username": "BFA"
},
"description": "XXXXXXXXXXXXXXX",
"status": {
"id": 1,
"name": "To Do"
},
"completed": false
}
Форма недействительна и пуста в JsonResponse.
Я основываюсь на: https://codereviewvideos.com/course/beginners-guide-back-end-json-api-front-end-2018/video/symfony-4-json-api-form-submission и Десериализацияюридическое лицо, связанное с Symfony Serializer Component
Спасибо за вашу помощь.