Update preferences field from code

Hi All,

Is there any way to dynamically fill a preferences field from code?

In my SmartApp, I am expanding on @brianwilson’s ThingSpeak code, but making the interface a little more user-friendly by automatically creating a channel on the user’s behalf.

My approach is to give the user an option to use an existing channel or create a new one. That means that I have options in my settings for “Channel ID” and “Channel Key”, but if those are empty, I create a new channel. I would like to fill in those fields once I create a channel and then use those values for my actual POSTs.

Does anybody know how to do this? Are preferences uni-directional?

Thanks,

Dan Kurin

Other than setting a default, I do not think it’s possible to programmaticly change these.
Hopefully someone will chime in and say I’m wrong…

I don’t know if this will work, but it’s worth a shot. I think I’ve seen this method work for options:

In the options for the input, set default to a function. Then return the value you want in the function.

default: getName()

//

def getName() {
     return 'name-' + preference1 + '-' + preference2
}

Let me know if this works.

Here’s my solution.
I use a dynamic page and set the description as a state variable (to my knowledge, “Default” is only available for device handlers)

input(name: "channelID", type: "number", title: "Channel ID", required: false, description: state.channelID)
input(name: "channelKey", type: "text", title: "Channel key", required: false, description: state.channelKey)

Then in my installed(), I check to see if either field is filled, otherwise I create a new channel:

if (channelID != null || channelKey != null) {
    state.channelID = channelID
    state.channelKey = channelKey.toUpperCase()
} else {
    createChannel()
}

In my updated(), I check again to see if the user specified a channel, otherwise we use what’s already in state:

if (channelID != null || channelKey != null) {
    state.channelID = channelID
    state.channelKey = channelKey.toUpperCase()
}

Because I’m using “Description” instead of “Default”, the returned value is still null even though text “appears” in the input box.

It’s a little hacky, but it serves the purpose. Any feedback?

It appears you can now use:

app.updateSetting(inputName, [type: type, value: value]) 
app.updateSetting(inputName, value)
// or for DTHs:
device.updateSetting(inputName, [type: type, value: value]) 
device.updateSetting(inputName, value)

However, while the above code seems to be able to change settings with existing non-null values, it does not appear to be able to add values to settings that are currently empty. So half-way there at least…

1 Like

I wouldn’t expect a ton of responses regarding this, though it’s huge. Unless you’ve tried writing some pretty complex apps/handlers most wouldn’t even understand the implications here…

1 Like

Thanks for the update!