2
votes

when i use custom validations on yii2 dynamic forms it doesn't show any error messages below the input field.Below I have posted my model. It doesn't show any error messges when qty field gets validated

namespace frontend\models;

use Yii;

class OrderD extends \yii\db\ActiveRecord {

public static function tableName()
{
    return 'order_d';
}


public function rules()
{
    return [
        [['item_id', 'qty', 'price', 'value'], 'required'],
        [['item_id'], 'integer'],
        [['price', 'value'], 'number'],
        [['order_code'], 'string', 'max' => 10],
        [['item_id'], 'exist', 'skipOnError' => true, 'targetClass' => Item::className(), 'targetAttribute' => ['item_id' => 'id']],
        [['order_code'], 'exist', 'skipOnError' => true, 'targetClass' => OrderH::className(), 'targetAttribute' => ['order_code' => 'code']],
        ['qty', 'validateQty']
    ];
}

public function validateQty($attribute)
{
    $qty = $this->$attribute;
    if ($qty >= 5)
    {
        $this->addError('qty', "qty validation successful");
    }
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'item_id' => 'Item ID',
        'order_code' => 'Order Code',
        'qty' => 'Qty',
        'price' => 'Price',
        'value' => 'Value',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getItem()
{
    return $this->hasOne(Item::className(), ['id' => 'item_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getOrderCode()
{
    return $this->hasOne(OrderH::className(), ['code' => 'order_code']);
}

}

3

3 Answers

0
votes

Be sure to know custom validations are php functions and not convert as javascript to validate in runtime .. those will work after the page has submit and send to controller ..

here is simple sample you want :

              ['qty','custom_function_validation'],



        ];
    }



 public function custom_function_validation($attribute, $params){
     if($this->$attribute>5){
        $this->addError($attribute,'it\'s more than 5');
     }
}
0
votes

To create a validator that supports client-side validation, you should implement the yii\validators\Validator::clientValidateAttribute() method which returns a piece of JavaScript code that performs the validation on the client-side.

public function clientValidateAttribute($model, $attribute, $view)
{
    return <<<JS
// your validation
JS;
}

See the documentation here: http://www.yiiframework.com/doc-2.0/guide-input-validation.html#implementing-client-side-validation

0
votes

Use method addError() in a controller and then just render your view file

Example

    if ($promo_code) {
        if ($promo_code->status == '1') {
            $message = 'This combination is incorrect.';
            $model->addError('promo_code', $message);
            return $this->render('index', compact('model'));
        }
        $promo_code->status = '1';
        $promo_code->save();
        $model->save();
    }