【问题标题】:A choice list based on database values in sonata奏鸣曲中基于数据库值的选择列表
【发布时间】:2016-09-16 03:26:02
【问题描述】:
是否可以在 configureformfields 中添加一个选项列表,其中包含从数据库映射的选项值,而不是像这样手动配置它:
->add('testfield', 'choice', array('choices' => array(
'1' => 'choice 1',
'2' => 'choice 2',)))
【问题讨论】:
标签:
entity
admin
choice
sonata
【解决方案1】:
如果实体映射正确,那么您可以使用:
->add('testfield')
Sonata 管理员将完成这项工作。
假设您有一个 Product 类链接到 Category 类:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* @ORM\Table(name="product")
*
*/
class Product
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
*/
protected $category;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* @param Category $category
*
* @return Product
*/
public function setCategory(Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* @return Category
*/
public function getCategory()
{
return $this->category;
}
}
只需使用:
->add('category')
将提供一个包含所有类别的选择表单字段。
如果您想要更高级的东西,也可以使用 SONATA_TYPE_MODEL:
<?php
// src/AppBundle/Admin/ProductAdmin.php
class ProductAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$imageFieldOptions = array(); // see available options below
$formMapper
->add('category', 'sonata_type_model', $imageFieldOptions)
;
}
}
文档在此页面上:Form Types
希望这会有所帮助!