Joomla的JForms在编辑时设置为只读


Joomla's JForms make readonly on edit

我正在创建一个Joomla 3.0组件,我有一个问题。

我想在编辑模式下将某些字段设为只读。它们应该在创建时设置,然后不可编辑。

我知道三种(在我看来)可能的方法可以做到这一点。

  1. 在后台将字段设置为只读
  2. 如果我们处于编辑模式,其中字段是只读的,则加载其他表单
  3. 使用 JavaScript 使字段只读

我更喜欢方法 2(或者更简单,则使用一种方法),但我不知道如何做到这一点。我怎么知道 getForm() 函数中我们是否进入编辑模式?有什么建议:)吗?

编辑:目前,我正在使用我不喜欢的方法3:

<?PHP if ($this->item->id > 0) { ?>
<script type="text/javascript">
var text_box = document.getElementById('jform_name');
text_box.setAttribute('readonly', 'readonly'); 
</script>
<?PHP } ?>

我不建议创建一个"只读"表单,因为您必须在更新时保持不同版本之间的同步,基本上您会破坏 DRY。

您可以在运行时使用 setFieldAttribtue() 设置 JForm 的各种属性。

例如,在许多核心组件中,您可以找到正在修改的表单:

com_admin/models/profile.php

public function getForm($data = array(), $loadData = true)
{
    // Get the form.
    $form = $this->loadForm('com_admin.profile', 'profile', array('control' => 'jform', 'load_data' => $loadData));
    if (empty($form))
    {
        return false;
    }
    if (!JComponentHelper::getParams('com_users')->get('change_login_name'))
    {
        $form->setFieldAttribute('username', 'required', 'false');
        $form->setFieldAttribute('username', 'readonly', 'true');
        $form->setFieldAttribute('username', 'description', 'COM_ADMIN_USER_FIELD_NOCHANGE_USERNAME_DESC');
    }
    return $form;
}

在我们的某些组件中,我们不仅设置了readonly属性,而且还设置了class以便我们可以适当地设置字段样式。

$form->setFieldAttribute('name', 'class', 'readonly');
$form->setFieldAttribute('name', 'readonly', 'true');