XF 2.0 Easy way to validate "Custom Fields"?

DragonByte Tech

Well-known member
I'm using the custom fields system to let admins ask users for license information (such as a website URL). In my License entity, I have
PHP:
    public function getLicenseFields()
    {
        $fieldDefinitions = $this->app()->container('customFields.dbtechEcommerceLicenses');
        
        return new Set($fieldDefinitions, $this, 'license_fields');
    }
And that all works swimmingly.

What I want to know is; is there an easy way to check that all required fields have been filled out, and that their values are valid?

I can see there isn't a validator in the Set class, ideally I'd be looking at something like:

PHP:
    public function validate($editMode = 'user', &$errors = [])
    {
        $definitions = $this->getDefinitionSet();

        foreach ($definitions as $fieldId => $field)
        {
            $value = $this->get($fieldId);

            $valid = $field->isValid($value, $error, $value);
            if (!$valid)
            {
                $errors[] = $error;
            }

            if ($field->isRequired($editMode) && ($value === '' || $value === []))
            {
                $errors[] = \XF::phraseDeferred('please_enter_value_for_required_field_x', ['field' => $field->title]);
            }
        }

        return !$errors;
    }
(Untested)

Is there an alternative already present, or do I have to build that myself?


Fillip
 
There isn't anything like that -- we (intentionally) only validate fields when trying to change them.
 
There isn't anything like that -- we (intentionally) only validate fields when trying to change them.
I see, while it isn't a massive problem to copy my function across as needed, do you think there would be any value to adding this to the core, in case other addons use custom fields the same way I do?

If so I can post my completed / tested code in the suggestions forum :)


Fillip
 
Back
Top Bottom