I have REST web service built and the consumers prefer I return them error codes rather than messages so they can do the localizations easier.
[[‘categoryId’, ‘minQty’], 'integer, ‘code’ => ‘INTEGER_EXPECTED’],
[[‘base_url’, ‘path’, ‘numberOfServes’], ‘string’, ‘max’ => 255, ‘code’ => ‘TOO_SHORT’],
I tried dependency injection, but it doesn’t seem to work
Yii::$container->set(‘yii\validators\Validator’, ‘common\components\validators\Validator’);
Currently, I extended the Model & ActiveRecord classes and put these methods to make it work. They work for custom validators, but not for builtin validators.
private $_errorCodes;
/**
* Adds a new error to the specified attribute.
* @param string $attribute attribute name
* @param string $error new error message
*/
public function addErrorCode($attribute, $error = '')
{
$this->_errorCodes[$attribute][] = $error;
}
/**
* Returns a value indicating whether there is any validation error.
* @param string|null $attribute attribute name. Use null to check all attributes.
* @return boolean whether there is any error.
*/
public function hasErrorCodes($attribute = null)
{
return $attribute === null ? !empty($this->_errorCodes) : isset($this->_errorCodes[$attribute]);
}
public function getErrorCodes($attribute = null)
{
if ($attribute === null) {
return $this->_errorCodes === null ? [] : $this->_errorCodes;
} else {
return isset($this->_errorCodes[$attribute]) ? $this->_errorCodes[$attribute] : [];
}
}
Any idea?