CRUD controller

Administrative actions (create, view, update, delete) with objects of different classes are repeated from one controller to another and can be assembled in a single base class.

module/admin/component/CrudController.js

const Base = require('./Controller');

module.exports = class CrudController extends Base {
  // place methods here
};

The actionCreate method is responsible for creating a new instance of the class derived from getModelClass. The create scenario, filtering validation rules, used to create a model.

The GET request renders empty model form. THe POST request loads attribute values, checks and if successful stores a new object. If validation fails, then form is filled with obtained values and found errors. After model saving action will redirect to the referral page.

module/admin/component/CrudController.js

async actionCreate () {
  const model = this.spawn(this.getModelClass());
  model.scenario = 'create';
  this.isPost() && await model.load(this.getPostParams()).save()
    ? this.redirectToReferrer()
    : await this.render('create', {model});
}

The actionView method displays a model. It can be overridden by target controller to load a model together with relations.

module/admin/component/CrudController.js

async actionView (params) {
  const model = await this.getModel(params);
  await this.render('view', {model});
}

The actionUpdate, actionCreate methods differ validation scenario. Furthermore, the actionUpdate method loads a model to update.

module/admin/component/CrudController.js

async actionUpdate (params) {
  const model = await this.getModel(params);
  model.scenario = 'update';
  this.isPost() && await model.load(this.getPostParams()).save()
    ? this.redirectToReferrer()
    : await this.render('update', {model});
}

The actionDelete method removes a model with identifier obtained from the GET request. If AJAX request has been received, then, after deletion, a response will contain the identifier of deleted object. Otherwise, there will redirect to previous page.

module/admin/component/CrudController.js

async actionDelete (params) {
  const model = await this.getModel(params);
  await model.delete();
  this.isAjax()
    ? this.send(model.getId())
    : this.redirectToReferrer();
}