php - Symfony/Sonata ModelType not working correctly
问题描述
I'm using Sonata Admin Bundle to make crud operations on an entity.
The entity has a OneToMany relation with itself.
The form show correctly but the items i try to add to the entity aren't getting added.
When i manually link an entity to another in the database, it shows correctly on the edit form, but still can't change it.
here is my code :
NavBarAdmin.php :
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('text', TextType::class)
->add('link', TextType::class)
->add('children', ModelType::class, [
'class' => NavItem::class,
'property' => 'text',
'multiple' => true
]);
}
services.yaml :
admin.navbar:
class: App\Admin\NavBarAdmin
arguments: [ ~, App\Entity\NavItem, App\Controller\NavBarAdminController, ~ ]
tags:
- { name: sonata.admin, manager_type: orm, label: Nav bar }
NavItem.php :
namespace App\Entity;
use App\Repository\NavItemRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
class NavItem
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $text;
/**
* @ORM\Column(type="string", length=255)
*/
private $link;
/**
* @ORM\ManyToOne(targetEntity=NavItem::class, inversedBy="children")
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity=NavItem::class, mappedBy="parent")
*/
private $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getText(): ?string
{
return $this->text;
}
public function setText(string $text): self
{
$this->text = $text;
return $this;
}
public function getLink(): ?string
{
return $this->link;
}
public function setLink(string $link): self
{
$this->link = $link;
return $this;
}
public function getParent(): ?self
{
return $this->parent;
}
public function setParent(?self $parent): self
{
$this->parent = $parent;
return $this;
}
/**
* @return Collection|self[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(self $child): self
{
if (!$this->children->contains($child)) {
$this->children[] = $child;
$child->setParent($this);
}
return $this;
}
public function removeChild(self $child): self
{
if ($this->children->removeElement($child)) {
// set the owning side to null (unless already changed)
if ($child->getParent() === $this) {
$child->setParent(null);
}
}
return $this;
}
}
解决方案
推荐阅读
- java - 放心总是返回 400 Bad Request for POST
- python - 如何将数据框附加到另一个数据框?
- css - 使用 CSS 将数据显示为列表?
- kotlin - Kotlin 如何选择泛型重载函数来调用?
- java - Java Spring WebFlux 多部分文件上传
- javascript - 文件池从 s3 加载初始图像
- kubernetes - Kubectl 等待服务获取外部 ip
- firebase - 向现有用户发送验证电子邮件
- javascript - Keycloak 返回 CORS Access-Control-Allow-Origin 错误
- c# - 将字符串转换为日期时间,以处理 c# 中所有不同格式的 excel 和 csv