Validation callbacks on admin option fields

SneakyDave

Well-known member
A couple of questions regarding assigning validation callbacks to option fields to validate or render them.

It appears that if a callback is assigned to an option, to validate the value, that callback is also executed when the addon is installed.

So, for instance, let's say I have an string option that requires a value to be entered. So I create a validation callback that throws a DataWriter error and returns false if the option is empty. In this case, the addon can't be installed, because the installation routine exist with that error.

I could create the option with a default value, mabe "This field is required..." but that's just a little sloppy.

I was wondering if 1) There's a way to tell if the callback is being called from the install routine or from saving the options and 2) If that's really the best way to handle this type of event.

The other question I have is regarding sanitizing/cleaning the admin options. If I have a text box as an admin option, is there a filter method I can apply similar to $this->_input->filterSingle() that I can use in a validation callback?
 
I was wondering if 1) There's a way to tell if the callback is being called from the install routine or from saving the options and 2) If that's really the best way to handle this type of event.
Yep, there's some examples in the XF code of how this is handled.

Obviously you have access to the DataWriter object which is inserting the option into the database. DataWriters are aware of whether new data is being inserted or existing data is being updated.

With that in mind, during install the option is being inserted, therefore you can do this:
PHP:
if ($dw->isInsert())
{
    return true;
}

So, if the option is being inserted (e.g. during install) you can just return true.

The other question I have is regarding sanitizing/cleaning the admin options. If I have a text box as an admin option, is there a filter method I can apply similar to $this->_input->filterSingle() that I can use in a validation callback?
That is taken care of automatically. The input is filtered using filter / filterSingle. In the validation callback, the value you have has already been sanitised.
 
Great, that makes a lot of sense, thanks Chris.

Regarding my second question, maybe something is wrong with my option.

I can create a textbox option, with no callback, and I can put javascript popup in it, and when that option is rendered, the javascript fires, which is obviously not what I want. Is this because admin options are allowed to contain html?

It's not a big issue, because admins wouldn't be using javascript in this textbox anyway, but to fix it, I created a validation callback that uses a strip_tags on the value.
 
Top Bottom