-
Notifications
You must be signed in to change notification settings - Fork 20
/
AtLeastValidator.php
173 lines (156 loc) · 5.41 KB
/
AtLeastValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
<?php
namespace codeonyii\yii2validators;
use Yii;
use yii\base\InvalidConfigException;
use yii\i18n\PhpMessageSource;
use yii\validators\Validator;
/**
* Checks if one or more in a list of attributes are filled.
*
* In the following example, the `attr1` and `attr2` attributes will
* be verified. If none of them are filled `attr1` will receive an error:
*
* ~~~[php]
* // in rules()
* return [
* ['attr1', AtLeastValidator::className(), 'in' => ['attr1', 'attr2']],
* ];
* ~~~
*
* In the following example, the `attr1`, `attr2` and `attr3` attributes will
* be verified. If at least 2 (`min`) of them are not filled, `attr1` will
* receive an error:
*
* ~~~[php]
* // in rules()
* return [
* ['attr1', AtLeastValidator::className(), 'min' => 2, 'in' => ['attr1', 'attr2', 'attr3']],
* ];
* ~~~
*
* If you want to show errors in a summary instead in the own attributes, you can do this:
* ~~~[php]
* // in rules()
* return [
* ['!id', AtLeastValidator::className(), 'in' => ['attr1', 'attr2', 'attr3']], // where `id` is the pk
* ];
*
* // view:
* ...
* echo yii\helpers\Html::errorSummary($model, ['class' => ['text-danger']]);
* // OR, to show only `id` errors:
* echo yii\helpers\Html::error($model, 'id', ['class' => ['text-danger']]);
* ~~~
*
*
* @author Sidney Lins <[email protected]>
*/
class AtLeastValidator extends Validator
{
/**
* @var integer the minimun required quantity of attributes that must to be filled.
* Defaults to 1.
*/
public $min = 1;
/**
* @var string|array the list of attributes that should receive the error message. Required.
*/
public $in;
/**
* @inheritdoc
*/
public $skipOnEmpty = false;
/**
* @inheritdoc
*/
public $skipOnError = false;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->in === null) {
throw new InvalidConfigException('The `in` parameter is required.');
} elseif (! is_array($this->in) && count(preg_split('/\s*,\s*/', $this->in, -1, PREG_SPLIT_NO_EMPTY)) <= 1) {
throw new InvalidConfigException('The `in` parameter must have at least 2 attributes.');
}
if (!isset(Yii::$app->get('i18n')->translations['message*'])) {
Yii::$app->get('i18n')->translations['message*'] = [
'class' => PhpMessageSource::className(),
'basePath' => __DIR__ . '/messages',
'sourceLanguage' => 'en-US'
];
}
if ($this->message === null) {
$this->message = Yii::t('messages', 'You must fill at least {min} of the attributes {attributes}.');
}
}
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
$attributes = is_array($this->in) ? $this->in : preg_split('/\s*,\s*/', $this->in, -1, PREG_SPLIT_NO_EMPTY);
$chosen = 0;
foreach ($attributes as $attributeName) {
$value = $model->$attributeName;
$attributesListLabels[] = '"' . $model->getAttributeLabel($attributeName). '"';
$chosen += !empty($value) ? 1 : 0;
}
if (!$chosen || $chosen < $this->min) {
$attributesList = implode(', ', $attributesListLabels);
$message = strtr($this->message, [
'{min}' => $this->min,
'{attributes}' => $attributesList,
]);
$model->addError($attribute, $message);
}
}
/**
* @inheritdoc
* @since: 1.1
*/
public function clientValidateAttribute($model, $attribute, $view)
{
$attributes = is_array($this->in) ? $this->in : preg_split('/\s*,\s*/', $this->in, -1, PREG_SPLIT_NO_EMPTY);
$attributes = array_map('strtolower',$attributes); // yii lowercases attributes
$attributesJson = json_encode($attributes);
$attributesLabels = [];
foreach ($attributes as $attr) {
$attributesLabels[] = '"' . addcslashes($model->getAttributeLabel($attr), "'") . '"';
}
$message = strtr($this->message, [
'{min}' => $this->min,
'{attributes}' => implode(Yii::t('messages', ' or '), $attributesLabels),
]);
$form = $model->formName();
return <<<JS
function atLeastValidator() {
var atributes = $attributesJson;
var formName = '$form';
var chosen = 0;
$.each(atributes, function(key, attr){
var obj = $('#' + formName.toLowerCase() + '-' + attr);
if(obj.length == 0){
obj = $("[name=\""+formName + '[' + attr + ']'+"\"]");
}
var val = obj.val();
chosen += val ? 1 : 0;
});
if (!chosen || chosen < $this->min) {
messages.push('$message');
} else {
$.each(atributes, function(key, attr){
var attrId = formName.toLowerCase() + '-' + attr;
if($('#' + attrId).length == 0){
attrId = $("[name=\""+formName + '[' + attr + ']'+"\"]").attr('id');
}
\$form.yiiActiveForm('updateAttribute', attrId, '');
});
}
}
atLeastValidator();
JS;
}
}