我正在使用symfony2和bootstrap 3,当我将readonly属性设置为表单字段时,它变灰,并且我有禁止的光标,但该字段仍然是可编辑的(在我的情况下是选择下拉列表)。
readonly 属性适用于简单的文本字段,但不适用于选择。
如何确保用户无法单击选择并更改其值?
我不能使用"禁用",因为我需要将值传递给表单。使用 jquery 重写只读属性也不起作用。
我的表格:
->add('product', 'entity', array(
'label' => 'Produit',
'class' => 'AppBundle:MarketPlace'Product',
'read_only' => true,
))
按照文档中的说明为您的实体创建一个数据转换器ProductToTextTransformer
,然后在表单构建器中使用它,根据是否禁用选择的条件添加选择或只读文本:
//...
// this assumes that the entity manager was passed in as an option
$entityManager = $options['em'];
$transformer = new ProductToTextTransformer($entityManager);
if ($condition_to_disabled_the_select){
$builder->add('product', 'entity', array(
'label' => 'Produit',
'class' => 'AppBundle:MarketPlace'Product',
));
}
else{
$builder->add(
$builder->create('product', 'text', array('label' => 'Produit', 'read_only' => true))
->addModelTransformer($transformer)
);
}
以下内容正在工作,但我不太喜欢它,我觉得它不像它应该的那样干净:
<script>
$(function(){
$(':input[readonly]').each(function(){
$(this)
.hide()
.parent().append('<p>' + $(this).find(":selected").text() + '</p>')
})
;
})
</script>
我今天遇到了同样的问题。除了选定的选项之外,我禁用了所有其他选择的选项。
[
'choice_attr' => static fn(?string $choice): array => ['disabled' => !$choice || $selectedValue !== $choice];
]
希望它可以帮助某人。