如果对象的名称是“默认”,如何禁用表单的名称字段?因此,用户不能更改“默认”对象的名称,但可以更改任何其他对象的名称?
这就是我已经拥有的:
ObjectType
trim($_POST['do_add'])
编辑操作
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name','text', array('required' => true))
->add('description', 'textarea', array('required' => false))
->add('type', 'choice', array('choices' => array(
Object::TYPE_PUBLIC => 'Public',
Object::TYPE_PRIVATE => 'Private',
),
));
}
答案 0 :(得分:2)
一种真正简单的方法是在编辑时将值传递给表单的构造函数并打开标记。所以你的表单类型是:
class ObjectType extends AbstractType
{
private $isEdit;
public function __construct($isEdit = false)
{
$this->isEdit = $isEdit;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', 'textarea', array('required' => false))
->add('type', 'choice', array('choices' => array(
Object::TYPE_PUBLIC => 'Public',
Object::TYPE_PRIVATE => 'Private',
),
));
if (!$editMode) {
$builder->add('name','text', array('required' => true));
}
}
}
然后在你的控制器中:
public function editAction(Object $object, Request $request)
{
$form = $this->createForm(new ObjectType($isEdit = true), $object, array(
'action' => $this->generateUrl('edit_object',['id' => $object->getId()]),
'method' => 'POST'
));
//...
}
对于创建新内容的createForm
,您可以传递new ObjectType()
并暂停参数,因为在这种情况下默认为false
。
另一种方法是根据您传递给它的实体(即FormEvents)构建表单。如果它已包含id的值,则您可以不将名称字段添加到表单中:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', 'textarea', array('required' => false))
->add('type', 'choice', array('choices' => array(
Object::TYPE_PUBLIC => 'Public',
Object::TYPE_PRIVATE => 'Private',
),
));
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$object= $event->getData();
$form = $event->getForm();
if (!$object || null === $object->getId()) {
$form->add('name','text', array('required' => true));
}
});