sdlins / yii2-at-least-validator

Makes one or more attributes mandatory inside a set of attributes.
Apache License 2.0
28 stars 19 forks source link

For Only One usage #8

Closed raphaelsoul closed 7 years ago

raphaelsoul commented 8 years ago

I revised your code as below for my situation:

    public function validateAttribute($model, $attribute)
    {
        $attributes = is_array($this->in) ? $this->in : preg_split('/\s*,\s*/', $this->in, -1, PREG_SPLIT_NO_EMPTY);
        $values = [];
        $chosen = 0;
        foreach ($attributes as $attributeName) {
            $value = $model->$attributeName;
            $attributesListLabels[] = '"' . $model->generateAttributeLabel($attributeName) . '"'; // TODO simplify this
            $chosen += !empty($value) ? 1 : 0;

            if ($value) {
                array_push($values,$value);
            }
        }
        if (!$chosen || $chosen < $this->min) {
            $attributesList = implode(', ', $attributesListLabels);
            $message = strtr($this->message, [
                '{min}' => $this->min,
                '{attributes}' => $attributesList,
            ]);
            $model->addError($attribute, $message);
        }
        if (!(count($values) == 1)){
            $model->addError($attribute,'only one of ' . implode(', ', $attributesListLabels) .  'can be filled.');
        }
    }

The usage situation Example is: only attr1 and attr2 is aceptable. when both provided. add erro to the model.

Maybe you can make an enhancement for this situation, and make it configurable?

sdlins commented 7 years ago

@raphaelsoul, If I got you, you should use conditional validation when to achieve this. By the way, could you show your use case for this? (thanks for your contribution)