• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Updating Widget Content Through the router or call Event
2
3
4On the widget page, the **postCardAction** API can be used to trigger a router or call event to start a UIAbility, which then updates the widget content. The following is an example of this widget update mode.
5
6## Updating Widget Content Through the router Event
7
8- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the router event to the FormExtensionAbility.
9
10  ```ts
11  let storage = new LocalStorage();
12  @Entry(storage)
13  @Component
14  struct WidgetCard {
15    @LocalStorageProp('detail') detail: string = 'init';
16
17    build() {
18      Column() {
19        Button ('Redirect')
20          .margin('20%')
21          .onClick(() => {
22            console.info('postCardAction to EntryAbility');
23            postCardAction(this, {
24              'action': 'router',
25              'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed.
26              'params': {
27                'detail': 'RouterFromCard'
28              }
29            });
30          })
31        Text(`${this.detail}`).margin('20%')
32      }
33      .width('100%')
34      .height('100%')
35    }
36  }
37  ```
38
39- In the **onCreate()** or **onNewWant()** lifecycle callback of the UIAbility, use the input parameter **want** to obtain the ID (**formID**) and other information of the widget, and then call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API to update the widget.
40
41  ```ts
42  import UIAbility from '@ohos.app.ability.UIAbility';
43  import formBindingData from '@ohos.app.form.formBindingData';
44  import formProvider from '@ohos.app.form.formProvider';
45  import formInfo from '@ohos.app.form.formInfo';
46
47  export default class EntryAbility extends UIAbility {
48    // If the UIAbility is started for the first time, onCreate is triggered after the router event is received.
49    onCreate(want, launchParam) {
50      console.info('Want:' + JSON.stringify(want));
51      if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
52        let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
53        let message = JSON.parse(want.parameters.params).detail;
54        console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
55        let formData = {
56          "detail": message +': onCreate UIAbility.', // Matches the widget layout.
57        };
58        let formMsg = formBindingData.createFormBindingData(formData)
59        formProvider.updateForm(curFormId, formMsg).then((data) => {
60          console.info('updateForm success.' + JSON.stringify(data));
61        }).catch((error) => {
62          console.error('updateForm failed:' + JSON.stringify(error));
63        })
64      }
65    }
66    // If the UIAbility is running in the background, onNewWant is triggered after the router event is received.
67    onNewWant(want, launchParam) {
68      console.info('onNewWant Want:' + JSON.stringify(want));
69      if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
70        let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
71        let message = JSON.parse(want.parameters.params).detail;
72        console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
73        let formData = {
74          "detail": message +': onNewWant UIAbility.', // Matches the widget layout.
75        };
76        let formMsg = formBindingData.createFormBindingData(formData)
77        formProvider.updateForm(curFormId, formMsg).then((data) => {
78          console.info('updateForm success.' + JSON.stringify(data));
79        }).catch((error) => {
80          console.error('updateForm failed:' + JSON.stringify(error));
81        })
82      }
83    }
84
85    ...
86  }
87  ```
88
89## Updating Widget Content Through the call Event
90
91- When using the call event of the **postCardAction** API, the value of **formId** must be updated in the **onAddForm** callback of the FormExtensionAbility.
92
93   ```ts
94   import formBindingData from '@ohos.app.form.formBindingData';
95   import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
96
97   export default class EntryFormAbility extends FormExtensionAbility {
98     onAddForm(want) {
99      let formId = want.parameters["ohos.extra.param.key.form_identity"];
100      let dataObj1 = {
101        "formId": formId
102      };
103      let obj1 = formBindingData.createFormBindingData(dataObj1);
104      return obj1;
105    }
106
107     ...
108   };
109   ```
110
111- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the UIAbility.
112
113  ```ts
114  let storage = new LocalStorage();
115  @Entry(storage)
116  @Component
117  struct WidgetCard {
118    @LocalStorageProp('detail') detail: string = 'init';
119    @LocalStorageProp('formId') formId: string = '0';
120
121    build() {
122      Column() {
123        Button ('Start in Background')
124          .margin('20%')
125          .onClick(() => {
126            console.info('postCardAction to EntryAbility');
127            postCardAction(this, {
128              'action': 'call',
129              'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed.
130              'params': {
131                'method': 'funA',
132                'formId': this.formId,
133                'detail': 'CallFromCard'
134              }
135            });
136          })
137        Text(`${this.detail}`).margin('20%')
138      }
139      .width('100%')
140      .height('100%')
141    }
142  }
143  ```
144
145- Listen for the method required by the call event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API in the corresponding method to update the widget.
146
147  ```ts
148  import UIAbility from '@ohos.app.ability.UIAbility';
149  import formBindingData from '@ohos.app.form.formBindingData';
150  import formProvider from '@ohos.app.form.formProvider';
151
152  const MSG_SEND_METHOD: string = 'funA'
153
154  // After the call event is received, the method listened for by the callee is triggered.
155  function FunACall(data) {
156    // Obtain all parameters transferred in the call event.
157    let params = JSON.parse(data.readString())
158    if (params.formId !== undefined) {
159      let curFormId = params.formId;
160      let message = params.detail;
161      console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
162      let formData = {
163        "detail": message
164      };
165      let formMsg = formBindingData.createFormBindingData(formData)
166      formProvider.updateForm(curFormId, formMsg).then((data) => {
167        console.info('updateForm success.' + JSON.stringify(data));
168      }).catch((error) => {
169        console.error('updateForm failed:' + JSON.stringify(error));
170      })
171    }
172    return null;
173  }
174  export default class EntryAbility extends UIAbility {
175    // If the UIAbility is started for the first time, onCreate is triggered after the call event is received.
176    onCreate(want, launchParam) {
177      console.info('Want:' + JSON.stringify(want));
178      try {
179         // Listen for the method required by the call event.
180        this.callee.on(MSG_SEND_METHOD, FunACall);
181      } catch (error) {
182        console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
183      }
184    }
185    ...
186  }
187  ```
188