Ad

OctoberCMS: Detect If New Image Uploaded

How do I detect if new images have been uploaded to a gallery from the backend form, so I could manipulate them before saving.

I've tried the following, but it didn't work:

<?php namespace Author\Plugin\Models;

use Model;

class ModelName extends Model
{
    public $attachMany = [
        'gallery' => 'System\Models\File',
    ];

    public function beforeSave()
    {
        if (Input::hasFile('gallery')) {
            trace_log('new files');
        } else {
            trace_log('no new files');
        }
    }
}

-- it keeps giving me no new files message, regardless whether I upload new files or not.

Ad

Answer

You can use this code to resize image of your model

Its little tricky as it is using differed binding so.

you can use this code in your plugin's plugin.php's boot method

use October\Rain\Database\Attach\Resizer;
// .. other code ...

public function boot() {

  \Hardik\SoTest\Models\Item::extend(function($model) {
    // for create time only
      $model->bindEvent('model.beforeCreate', function() use ($model) {

        $records = \October\Rain\Database\Models\DeferredBinding::where([
          'master_type' => 'Hardik\SoTest\Models\Item', // <- REPLACE WITH YOUR MODEL(ModelName)
          "master_field" => "picture", // <- REPLACE WITH ATTACHEMNT MODEL (gallery)
          "slave_type" => "System\Models\File",
          "session_key" => post('_session_key')
        ])->get();

        foreach($records as $record) {
          $fileRecord = \System\Models\File::find($record->slave_id);

          // code to resize image
          $width = 100;
          $height = 100;
          $options = []; // or ['mode' => 'crop']

          // just in place resize image
          Resizer::open($fileRecord->getLocalPath()) // create from real path
                    ->resize($width, $height, $options)
                    ->save($fileRecord->getLocalPath());
        }
      });
  });      
}

if any doubt please comment.

Ad
source: stackoverflow.com
Ad