2

I have a need to set a property on a plugin Model that is an array of one or more valid values.

I can see that I can use AttributeType::Enum and record and define a set of values but if I'm not mistaken, that enables me to validate a single value against that set of values:

class MyModel extends BaseModel
{
    protected function defineAttributes()
    {
        return [
            'mySetting' => [ AttributeType::Enum, 'values' => 'validOption1,validOption2,validOption3' ]
        ];
     }
}

What I want to do is enable mySetting to be an array that would be valid when set as an array containing any combination of the defined options:

MyModel::populateModel(['mySetting' => [
    'validOption1'
]]); // is valid

MyModel::populateModel(['mySetting' => [
    'validOption1', 
    'validOption3'
]]); // is valid

MyModel::populateModel(['mySetting' => [
    'invalidOption', 
    'validOption3'
]]); // is *not* valid

MyModel::populateModel(['mySetting' => []); // is *not* valid

Etc.

4

Found an answer in the form of a customer validator class on the model:

https://experiencehq.net/blog/the-definitive-guide-to-validation-in-craft-part-5-custom-validators#newsletter

So something like this:

    public function validateMySetting($attribute)
    {
        $values = (is_array($this->$attribute)) ? $this->$attribute : [ $this->$attribute ];

        $validValues = ['validOption1', 'validOption2', 'validOption3'];

        foreach($values as $value)
        {
            if ( ! in_array($value, $validValues))
            {
                $this->addError($attribute, "{$value} is not a valid setting");
            }
        }
    }

And then to call it, override the parent class' rules method:

public function rules ()
{
    return array_merge(parent::rules(), [ 
        'someAttributeName', 'validateMySetting'
    ];
}
  • It is not getting into my custom validator's callback function. How do I do that? – Volatil3 Oct 21 '15 at 7:15
  • @Volatil3 I've updated the answer with details of how to add your custom validator method to the model's validation rules. – Russ Back Oct 23 '15 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.