在子组件对话框中获取父组件对话框的属性

AEM - Get property of parent component dilalog inside child component's dialog

本文关键字:对话框 组件 属性 获取      更新时间:2023-09-26

我对AEM和纯前端(html,css,js)非常陌生,所以很抱歉问了这么一个基本的问题。我制作了两个组件,父组件和子组件。这些组件中的每一个都有一个name属性,我在对话框中设置了这个属性。我需要能够在子组件中访问parents name属性,我的页面看起来是这样的。


父组件——parentParsys
——子组件
——childParsys

我只需要在孩子对话框中显示父母的名字,但是我似乎找不到父母的名字。

任何指导将不胜感激。理想情况下,我想在JS中做到这一点,但我很舒服地选择我的方式围绕JSP。

谢谢

为子组件的对话框添加一个侦听器,以便在对话框加载时运行JavaScript。该JavaScript将根据子组件的路径确定父组件的路径。使用Apache Sling的RESTful特性,您只需向父组件的Resource发出GET请求,该请求将返回该资源的属性。然后,您可以使用所需的值更新当前打开的对话框。您需要的所有信息都在CQ Widgets API文档中提供。

将侦听器附加到指向外部JavaScript文件的子对话框:

<instructions
    jcr:primaryType="cq:Widget"
    fieldLabel="Instructions"
    xtype="displayfield">
    <listeners
        jcr:primaryType="nt:unstructured"
        loadcontent="function(field, record, path){ mynamespace.updateWithParentName(field, record, path) }"
    />
</instructions>

将自定义JavaScript添加到创作模式下可用的ClientLib中。可以是cq.authoring.editor,参见使用客户端库。这将在每次对话框打开时运行。本例发出一个同步GET请求并更新一个displayfield。您将根据您想要使用的数据、您想要如何查找父组件以及您还想要添加空检查来更新它。

var mynamespace = {};
mynamespace.updateWithParentName = function(field, record, path) {
  var parentPath = getParentPath(path);
  var parentComponent = CQ.shared.HTTP.eval(CQ.shared.HTTP.noCaching(parentPath + '.json'));
  var parentName = parentComponent.name; // assuming the property name is "name"
  field.setValue('Parent component name is: ' + parentName);
  /* Go up two levels accounting for the current component and the parsys */
  function getParentPath(path) {
    var parts = path.split('/');
    var parentPath = parts.slice(0, parts.length - 2).join('/');
    return parentPath;
  }
}