Port of Yii2 DynamicModel for inline data validation

Yii2 has new feature called DynamicModel which allows you to validate any data in your code using well known model validators. This is a port of that feature for Yii 1.1.

CSDynamicModel is a model class primarily used to support ad-hoc data validation.

The typical usage of CSDynamicModel is as follows,

public function actionSearch( $name, $email ) {
    $model = CSDynamicModel::validateData( compact( 'name', 'email' ), array(
        array( 'name, email', 'length', 'max' => 128 ),
        array( 'email', 'email' ),
    ) );
    if( $model->hasErrors() ) {
        // validation fails
    } else {
        // validation succeeds

The above example shows how to validate $name and $email with the help of CSDynamicModel. The validateData() method creates an instance of CSDynamicModel, defines the attributes using the given data (name and email in this example), and then calls Model::validate().

You can check the validation result by hasErrors(), like you do with a normal model. You may also access the dynamic attributes defined through the model instance, e.g., $model->name and $model->email.

Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:

$model = new CSDynamicModel( compact( 'name', 'email' ) );
$model->addRule( array( 'name, email', 'string', 'max' => 128 ) )
    ->addRule( array( 'email', 'email' ) )
if( $model->hasErrors() ) {
    // validation fails
} else {
    // validation succeeds

CSDynamicModel implements the above ad-hoc data validation feature by supporting the so-called "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor or defineAttribute().


extract to your project structure and use it :) unit test included

Total 4 comments

#16306 report it
Maciej Liżewski at 2014/02/08 05:18am
re: re: Error on attributeNames()

OK... you are totally right. I confused function names as they are different in Yii2 and Yii 1.1. I thought it should return attribute labels. Posting fixed version.

#16299 report it
Wiseon3 at 2014/02/07 10:15am
re: Error on attributeNames()

I don't think there's any need to use array_combine(), as attributeNames() should return "the list of attribute names of the model". Neither CActiveRecord nor CFormModel return an associative array. Both return the attribute names as an indexed array.

#16297 report it
Maciej Liżewski at 2014/02/07 07:11am
re: Error on attributeNames()

you are right, but partially - it should return array_combine( $attrs, $attrs );

#16296 report it
Wiseon3 at 2014/02/07 07:09am
Error on attributeNames()

There's an error on line 194:

public function attributeNames() {
        $attrs = array_keys( $this->_attributes );
        return array_combine( $attr, $attrs );

The function should return $attrs directly, as $attr does not exist.

Leave a comment

Please to leave your comment.

Create extension