---
# System prepended metadata

title: '[Thingsboard] Update entity attributes in a custom widget'
tags: [實作]

---

# Thingsboard - Update entity attributes in a custom widget


* Use attributeService
    * `self.ctx.attributeService`
    * [Check how many methods in attributeService](https://github.com/thingsboard/thingsboard/blob/13e6b10b7ab830e64d31b99614a9d95a1a25928a/ui-ngx/src/app/core/http/attribute.service.ts#L28)

* Create a latestValue-type widget
    * Use `getEntityAttributes` method to get the entity attributes
    * Use `saveEntityAttributes` method to update the entity attributes
     
```javascript
self.onInit = function() {
    const entityId = self.ctx.data[0].datasource.entity
        .id;

    if (self.ctx.data[0].dataKey.type !== "function") {
        
        // use getEntityAttributes method to get the entity attributes
        self.ctx.attributeService
            .getEntityAttributes(entityId,
                'SERVER_SCOPE', ["tempSet", "washTimes"]
            ).subscribe((
                attributes) => {
                console.log(attributes);
            });
        
        // use saveEntityAttributes method to update the entity attributes
        self.ctx.attributeService.saveEntityAttributes(
            entityId,
            'SERVER_SCOPE', [{
                key: "tempSet",
                value: 25
            }, {
                key: "washTimes",
                value: 1
            }]
        ).subscribe((res) => {
            console.log(res);
        })
    }
}
```
>[!Note]
>* ==Remember to add subscribe to to make it work==
>* When use the attributeService:
    >* para => entityId is an object not an id string
    >* entityId example
        >* `{entityType: 'DEVICE', id: '11111abc'}`
```
saveEntityAttributes(entityId: EntityId, 
attributeScope: AttributeScope, 
attributes: Array<AttributeData>,
config?:RequestConfig): Observable<any>
```

---

* If you want to use attributeService in custom action

    `let attributeService = widgetContext.attributeService;`
    or
    ```
    let $injector = widgetContext.$scope.$injector;
    let attributeService = $injector.get(
    widgetContext.servicesMap.get('attributeService'));
    ```

<br/><br/>

## Reference

* [attribute.service.ts](https://github.com/thingsboard/thingsboard/blob/13e6b10b7ab830e64d31b99614a9d95a1a25928a/ui-ngx/src/app/core/http/attribute.service.ts#L28)
* [Saving entity attributes in custom widget #6820](https://github.com/thingsboard/thingsboard/issues/6820)
* [Widget to change attribute values on dashboard #574](https://github.com/thingsboard/thingsboard/issues/574)