【发布时间】:2014-05-17 13:00:05
【问题描述】:
我目前正在尝试为表单类型实现密钥对值,它与 FOSRestBundle 一起使用以允许发送如下请求:
{
"user": {
"username": "some_user",
"custom_fields": {
"telephone": "07777",
"other_custom_field": "other custom value"
}
}
}
为此的后端表示如下:
用户
id、用户名、自定义字段
自定义用户字段
id,字段
CustomUserFieldValue
user_id、field_id、值
我目前已经制作了如下的自定义表单:
<?php
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add(
'custom_fields',
'user_custom_fields_type'
)
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'Acme\DemoBundle\Entity\User',
'csrf_protection' => false,
)
);
}
public function getName()
{
return 'user';
}
}
还有我的user_custom_fields_type:
<?php
class CustomUserFieldType extends AbstractType
{
private $em;
/**
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$fields = $this->em->getRepository('AcmeDemoBundle:CustomUserField')->findAll();
foreach($fields as $field) {
$builder->add($field->getField(), 'textarea');
}
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'invalid_message' => 'The selected custom field does not exist'
)
);
}
public function getParent()
{
return 'collection';
}
public function getName()
{
return 'user_custom_fields_type';
}
}
这一直给我一个错误,即有额外的字段。哪些是我在CustomUserFieldType 中添加的。我怎样才能让它工作?
注意:这是实际代码的简化版本,我已经尝试删除所有不相关的代码。
【问题讨论】:
标签: php symfony symfony-forms symfony-2.3 fosrestbundle