How to extend a model that is part of an Yii2 extension?

985 Views Asked by At

In my application I'm using an extension (which I own and may modify). This extension has an ActiveRecord based class that I want to extend in the application with another property. Can I do this somehow? Can a Factory help anyhow or Yii behaviour?

Class in extension:

namespace extension;

/**
 * @property integer $id
 * @property string  $name
 */
class Product extends ActiveRecord {

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'name'], 'required'],
            [['id'], 'integer'],
            [['name'], 'string'],
        ];
    }
}

There is also a ProductController and the corresponding view files (index, create, update, view, _form) in the extension which were regularly produced with gii. I just would like to add another property $description (string, required) to the Product. A migration in order to add the required column is available.

Do I have to overwrite the model and controller class and the view files? Or is the a more elegant solution?

E.g., consider the standard object creation that takes place within the extension:

public function actionCreate() {
    $model = new Product();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'language' => $model->language]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

From my understanding I cannot influence the creation. Or am I wrong?

My impression is that I have to override everything (also the view files since the property has to be displayed) and then change controllerNamespace.

1

There are 1 best solutions below

2
On

As far as extending a class, just go ahead and add the property. Your new class will have inherited everything from the parent class plus have your new property.

Concerning overwriting the generated files, there is a diff option in gii when you generate the files, so you can preview and decide what to keep and what to overwrite. Be aware that you have to merge any changes manually however.