Joomla字段:动态更改只读属性

use*_*093 2 joomla joomla2.5

在Joomla组件形式:

有没有办法动态更改表单字段属性:"readonly"?

例如:

if( _condition_ )
   $this->form->getInput('Name')->readonly = true;
Run Code Online (Sandbox Code Playgroud)

Val*_*spa 6

从我在API中看到的,你基本上可以改变它.

我这样看:

当你调用的时候$this->form->getInput('Name')你在JFormField对象里面(实际上是一个插入JFormField的类,它是抽象的 - 例如由JFormFieldText继承),调用该方法getInput().

这个方法,从我们可以直接从你定义的XML中看到getInput()它的参数$element(描述表单字段的XML元素的SimpleXMLElement对象),它只返回一个字符串(实际的HTML),所以显然设置和不存在的属性不行.

但是JForm有一个很好的方法叫做setFieldAttribute(),见下面的签名:

 /**
 * Method to set an attribute value for a field XML element.
 *
 * @param   string  $name       The name of the form field for which to set the attribute value.
 * @param   string  $attribute  The name of the attribute for which to set a value.
 * @param   mixed   $value      The value to set for the attribute.
 * @param   string  $group      The optional dot-separated form group path on which to find the field.
 *
 * @return  boolean  True on success.
 *
 * @since   11.1
 */
public function setFieldAttribute($name, $attribute, $value, $group = null)
Run Code Online (Sandbox Code Playgroud)

所以你的代码看起来像:

if( _condition_ ) 
{
    $this->form->setFieldAttribute('Name', 'readonly', 'true', $group = null);
    echo $this->form->getInput('name');
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.