Photo controller

The PhotoController class defines a controller of photo model.

module/admin/controller/PhotoController.js

const Base = require('../component/CrudController');

module.exports = class PhotoController extends Base {

  static getConstants () {
    return {
      METHODS: {
        'assign-main': ['post']
      }
    };
  }
};
module.exports.init(module);

const Article = require('../model/Article');
const File = require('../model/File');
const Photo = require('../model/Photo');
Create photo

The actionCreate method creates a photo model. The async.series array of asynchronous methods receives data to select one article of the list (Article.findToSelect). You can assign a photo to it.

module/admin/controller/PhotoController.js

async actionCreate () {
  const model = this.spawn(Photo);
  model.scenario = 'create';
  if (this.isPost() && model.load(this.getPostParams()).save()) {
    return this.redirectToReferrer();
  }
  const articles = await Article.findToSelect().all();
  await this.render('create', {articles, model});
}
View uploaded photo

The actionView method calls the parent to get necessary relations.

module/admin/controller/PhotoController.js

async actionView () {
  await super.actionView({with: ['article']});
}
Update photo

The actionUpload method uploads a file to server. If the file is validated, a photo model will be created. Initial model is not linked to any article.

module/admin/controller/PhotoController.js

async actionUpload () {
  const file = this.spawn(File);
  if (!await file.upload(this)) {
    return this.sendText(this.translate(file.getFirstError()), 400);
  }
  const photo = this.spawn(Photo);
  photo.set('file', file.getId());
  await photo.validate(['file'])
    ? this.sendText(file.getId())
    : this.sendText(this.translate(photo.getFirstError()), 400);
}

The actionAssignMain method sets the main photo of article. The forceSave function saves article without any data validation. If the photo is not related to any article, then set flash error messages (one-off message to a user session), and user will be redirected to viewing page.

module/admin/controller/PhotoController.js

async actionAssignMain () {
  const model = await this.getModel({with: ['article']});
  const article = model.get('article');
  if (!article) {
    this.setFlash('danger', 'Article not found');
    return this.redirect(['view', model]);
  }
  article.set('mainPhotoId', model.getId());
  await article.forceSave();
  this.redirect(['article/view', article]);
}