• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Updating Widget Content Through FormExtensionAbility
2
3
4On the widget page, the **postCardAction** API can be used to trigger a message event to the FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode.
5
6
7- 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 FormExtensionAbility.
8
9  ```ts
10  let storage = new LocalStorage();
11  @Entry(storage)
12  @Component
13  struct WidgetCard {
14    @LocalStorageProp('title') title: string = 'init';
15    @LocalStorageProp('detail') detail: string = 'init';
16
17    build() {
18      Column() {
19        Button ('Update')
20          .onClick(() => {
21            postCardAction(this, {
22              'action': 'message',
23              'params': {
24                'msgTest': 'messageEvent'
25              }
26            });
27          })
28        Text(`${this.title}`)
29        Text(`${this.detail}`)
30      }
31      .width('100%')
32      .height('100%')
33    }
34  }
35  ```
36
37- Call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API to update the widget in the **onFormEvent** callback of the FormExtensionAbility.
38
39  ```ts
40  import formBindingData from '@ohos.app.form.formBindingData';
41  import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
42  import formProvider from '@ohos.app.form.formProvider';
43
44  export default class EntryFormAbility extends FormExtensionAbility {
45    onFormEvent(formId, message) {
46      // Called when a specified message event defined by the form provider is triggered.
47      console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);
48      let formData = {
49        'title':'Title Update Success.', // Matches the widget layout.
50        'detail':'Detail Update Success.', // Matches the widget layout.
51      };
52      let formInfo = formBindingData.createFormBindingData(formData)
53      formProvider.updateForm(formId, formInfo).then((data) => {
54        console.info('FormAbility updateForm success.' + JSON.stringify(data));
55      }).catch((error) => {
56        console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
57      })
58    }
59
60    // ...
61  }
62  ```
63
64  The figure below shows the effect.
65
66  ![WidgetUpdatePage](figures/WidgetUpdatePage.png)
67