如何在字段级别动态添加 readonly 属性,而不修改核心 XML?

解读

国内企业在 Joomla 二开面试里常把“不改核心、不改 XML”当成硬指标,目的是考察候选人对 Joomla 事件体系与表单渲染链路的熟悉度。
readonly 属于字段的 HTML 属性,XML 一旦解析成 JFormField 实例,属性就被固化;要“动态”加,只能插足解析之后、渲染之前这一小段生命周期。
国内主流做法有三条路线:

  1. 插件层——借 onContentPrepareForm 事件给特定字段追加属性;
  2. 模型层——在表单对象已加载、尚未渲染时,用 JForm 的 setFieldAttribute 方法;
  3. 视图层——直接覆盖字段模板,用 Layout Override 写死 readonly。
    路线 1 最干净,路线 2 最灵活,路线 3 最直观;面试官通常希望听到“事件优先 + 模型兜底”的完整闭环,并追问性能、缓存、多语言、权限冲突等细节。

知识点

  • JForm 与 JFormField 生命周期:loadFile() → getField() → renderField()
  • onContentPrepareForm 事件参数:form是JForm实例,可写;form 是 JForm 实例,可写;data 是即将填充的数组
  • setFieldAttribute(name,name, attribute, value,value, group = null) 用法与返回值
  • 字段属性 whitelist:readonly、disabled、class、onchange 等均可动态注入
  • 用户权限对象:JFactory::getUser() → getAuthorisedViewLevels()
  • 模板覆盖优先级:模板/html/layouts/joomla/form/field/xxx.php > 组件/layout > 全局/libraries
  • 缓存场景:JForm 默认带 MD5 缓存键,动态改属性后需 $form->reset(true) 清缓存
  • 国内常见坑:
    – 把 disabled 当 readonly 用,导致 POST 丢失数据;
    – 直接改 XML 文件,升级被覆盖;
    – 插件未判断 $context,导致后台所有表单都被锁死;
    – 未考虑多语言,硬编码中文提示。

答案

推荐采用“系统插件 + 事件”方案,三步完成:

  1. 新建 plg_system_readonly 插件,在 plugins/system/readonly/ 注册 onContentPrepareForm 事件;
  2. 在插件入口判断上下文与字段名,仅对 com_example 组件的 edit 表单、price 字段生效;
  3. 调用 $form->setFieldAttribute('price', 'readonly', 'true'),并视权限决定是否追加。
    核心代码示例:
public function onContentPrepareForm($form, $data)
{
    if (!($form instanceof JForm)) {
        return true;
    }
    $context = $form->getName();               // com_example.form.edit.item
    if ($context !== 'com_example.form.edit.item') {
        return true;
    }
    $user  = JFactory::getUser();
    $isFinance = $user->authorise('core.edit.price', 'com_example');
    if ($isFinance) {
        return true;                           // 财务组可写
    }
    // 动态加 readonly
    $form->setFieldAttribute('price', 'readonly', 'true');
    // 如需前端提示,可追加描述
    $form->setFieldAttribute('price', 'description', '非财务组只读');
    return true;
}

安装后启用插件,无需改动任何核心文件或 XML,升级无损;若字段位于选项卡分组,把 setFieldAttribute 第四个参数传入分组名即可。
若项目对性能极端敏感,可在模型层直接干预:

$form = $this->loadForm(...);
$form->setFieldAttribute('price', 'readonly', 'true');

但模型层代码分散,不利于后期集中管理,国内团队更倾向插件化。

拓展思考

  1. 如果字段类型是 custom-element 或 layout 自定义渲染,setFieldAttribute 可能失效,此时应优先覆盖 layouts/joomla/form/renderfield.php,在模板里根据 $field->readonly 决定是否加 input 属性。
  2. 国内大型门户常把“只读”与“灰掉”混用,真正需求是“不可改但可提交”,readonly 比 disabled 更安全;面试时可主动指出二者差异,体现细节掌控力。
  3. 若需根据行级别数据动态判断(例如订单状态为已审核才只读),可在插件里把 $data 转成对象,读取状态字段后再决定是否 setFieldAttribute,展示你对事件参数的深度利用。
  4. 面对“如何批量给 50 个字段加 readonly”的追问,可回答:在插件里遍历 $form->getXml(),对满足命名规则的字段统一 setFieldAttribute,并结合缓存键刷新,避免循环性能损耗。