Я пытаюсь построить форму с вложенными сущностями.
ЦСИ / Entity / Компания
/**
* @ORM\ManyToOne(targetEntity="App\Entity\CompanyAddress", inversedBy="company")
* @Serializer\Groups({"company"})
*/
private $addresses;
/**
* @ORM\OneToOne(targetEntity="App\Entity\CompanyAddress")
* @ORM\JoinColumn(name="main_address")
*
* @Assert\NotBlank()
* @Serializer\Groups({"company"})
*/
private $mainAddress;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User")
* @ORM\JoinColumn(name="owner", onDelete="SET NULL", nullable=true)
* @Serializer\Groups({"company"})
*
*/
private $owner;
public function __construct()
{
$this->addresses = new ArrayCollection();
$this->accountants = new ArrayCollection();
}
/**
* @return array
*/
public function getAddresses()
{
return $this->addresses->toArray();
}
/**
* @param $addresses
* @return Company
*/
public function setAddresses($addresses): self
{
$this->addresses = $addresses;
}
/**
* @param CompanyAddress $address
* @return Company
*/
public function addAddress(CompanyAddress $address): self
{
if ($this->addresses->contains($address)) return $this;
$this->addresses->add($address);
return $this;
}
/**
* @param CompanyAddress $address
* @return Company
*/
public function removeAddress(CompanyAddress $address): self
{
if ($this->addresses->contains($address)) {
$this->addresses->removeElement($address);
// $address->setCompany(null);
}
return $this;
}
/**
* @return mixed
*/
public function getMainAddress()
{
return $this->mainAddress;
}
/**
* @param CompanyAddress $address
* @return Company
*/
public function setMainAddress(?CompanyAddress $address): self
{
$this->mainAddress = $address;
return $this;
}
/**
* @return User
*/
public function getOwner(): ?User
{
return $this->owner;
}
/**
* @param User|null $owner
* @return Company
*/
public function setOwner(?User $owner): self
{
$this->owner = $owner;
return $this;
}
// and other entity code
ЦСИ / Entity / CompanyAddress.php
/**
* @ORM\OneToMany(targetEntity="App\Entity\Company", mappedBy="addresses", orphanRemoval=true)
*/
private $company;
/**
* @return Company
*/
public function getCompany(): Company
{
return $this->company;
}
/**
* @param Company $company
* @return CompanyAddress
*/
public function setCompany(?Company $company): self
{
$this->company = $company;
return $this;
}
// some other code
Теперь я строю форму
ЦСИ / Форма / CompanyType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('shortName')
->add('nip')
->add('regon')
->add('description')
->add('addresses', CollectionType::class, ['entry_type' => CompanyAddressType::class, 'allow_add' => true])
->add('mainAddress', CompanyAddressType::class)
->add('accountants', CollectionType::class, ['entry_type' => CompanyAccountantType::class, 'allow_add' => true])
->add('owner', UserCompanyType::class, ['empty_data' => null])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Company::class,
]);
}
ЦСИ / Форма / CompanyAddressType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('country')
->add('city')
->add('street')
->add('house')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => CompanyAddress::class,
]);
}
SRC / контроллер / CompanyController.php
public function new(Request $request, CompanyService $cs)
{
// $this->denyAccessUnlessGranted('new');ump($request->getContent());
$company = new Company();
$form = $this->createForm(CompanyType::class, $company);
$form->submit(json_decode($request->getContent(), true));
if (!$form->isValid()) {
return $this->json([
'message' => 'Data validation error',
'errors' => $this->normalizeFormErrors($form)
], Response::HTTP_UNPROCESSABLE_ENTITY);
}
try {
$company = $cs->addCompany($company);
} catch (\Exception $e) {
return JsonResponse::create(['error' => $e->getMessage()], 406);
}
return JsonResponse::fromJsonString($cs->getSerializer()->serialize($company, ['id', 'company']));
}
и Сервис src / Services / CompanyService.php
public function addCompany(Company $company)
{
if ($this->companyRepository->findOneByNipOrRegon(['nip' => $company->getNip(), 'regon' => $company->getRegon()]))
throw new \Exception($this->translator->trans('Company with given NIP or REGON exists'));
try {
$this->em->persist($company);
$this->em->flush();
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
return $company;
}
Теперь я отправляю данные json
{
"name":"Long Company Name",
"shortName":"Short Name",
"nip":"8888888",
"regon":"1111111",
"description":"Description",
"addresses": [ {
"city":"First City",
"street":"No street Name",
"house":"44",
"country":"Country"
}, {
"country":"Country",
"city":"Another City",
"street":"",
"house":"11"
}],
"mainAddress": {
"country":"Main Country",
"city":"Main City",
"street":"Main Street",
"house":"1"
},
"accountants": [],
"owner": {
"id":1
}
}
И я получил ошибку "Expected value of type \"App\\Entity\\CompanyAddress\" for association field \"App\\Entity\\Company#$addresses\", got \"Doctrine\\Common\\Collections\\ArrayCollection\" instead."
Когда я отправляю пустой массив адресов и отправляю id
как владелец, мой владелец в компании имеет значение null: / не получает из базы данных: / Когда я удаляю опцию "empty_data", я получаю ошибку "Could not determine access type for property "id" in class "App\Entity\User"
Я хотел бы добавить адреса из компании Comapany при добавлении компании, а также я хотел бы удалить адрес из компании.
Как создать сущности из этой формы? Или какие функции я должен добавить к юридическому лицу компании?