我終於找到了我的問題的解決方案。我不得不使用Data transformer和自定義form field type。我也使用FPNTagBundle和它的tagManager。這是我做的方式:
class TagsTransformer implements DataTransformerInterface
{
private $tagManager;
public function __construct(TagManager $tagManager)
{
$this->tagManager = $tagManager;
}
/**
* Transforms a value from the original representation to a transformed representation.
*
* By convention, transform() should return an empty string if NULL is
* passed.
*
* @param mixed $value The value in the original representation
*
* @return mixed The value in the transformed representation
*
* @throws TransformationFailedException When the transformation fails.
*/
public function transform($tags)
{
if(!is_null($tags))
return join(', ', $tags->toArray());
return '';
}
/**
* Transforms a value from the transformed representation to its original
* representation.
*
* By convention, reverseTransform() should return NULL if an empty string
* is passed.
*
* @param mixed $value The value in the transformed representation
*
* @return mixed The value in the original representation
*
* @throws TransformationFailedException When the transformation fails.
*/
public function reverseTransform($tags)
{
if(is_null($tags) || !$tags)
return;
return $this->tagManager->loadOrCreateTags(
$this->tagManager->splitTagNames($tags)
);
}
}
class TagType extends AbstractType
{
protected $tagManager;
public function __construct(TagManager $tagManager)
{
$this->tagManager = $tagManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new TagsTransformer($this->tagManager);
$builder->addModelTransformer($transformer);
}
public function getName()
{
return 'tags';
}
public function getParent()
{
return 'text';
}
}
最後我的形式是這樣的:
class CorporatePostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('keywords', 'tags');
}
//.....
}
你將不得不爲你的自定義表單字段類型的集成創建一個自定義模板Bootstrap tagsinput。
實體(模型)和設計(視圖)之間沒有鏈接... – pbenard