Closed magic-77 closed 2 years ago
i need to set the behaviors config in a Method to avoid that images are missing when Entiy is Duplicated at Products Controller.
ProductImagesController
public function add($productId) { $productImage = $this->ProductImages->newEntity(); if ($this->getRequest()->is('post')) { $productImage = $this->ProductImages->addImage($productImage, $this->getRequest()->getData()); if ($this->ProductImages->save($productImage)) { $this->Flash->success(__('The product image has been saved.')); return $this->redirect(['controller' => 'product-images', 'action' => 'add', $productImage->product_id]); } $this->Flash->error(__('The product image could not be saved. Please, try again.')); } $productImage->product_id = $productId; $product = $this->ProductImages->Products->get($productId, ['contain' => ['ProductImages', 'Categories']]); $this->set(compact('productImage', 'product')); $this->set('_serialize', ['productImage']); }
ProductImagesTable
public function initialize(array $config) { parent::initialize($config); $this->table('product_images'); $this->displayField('alt_tag'); $this->primaryKey('id'); $this->addBehavior('Josegonzalez/Upload.Upload'); $this->addBehavior('Search.Search'); $this->belongsTo('Products', [ 'className' => 'Products', 'foreignKey' => 'product_id' ]); } public function addImage($productImage, $request) { $this->behaviors()->get('Upload')->setConfig([ 'filename' => [ 'path' => 'webroot{DS}uploads{DS}product_images{DS}', 'nameCallback' => function (array $data, array $settings) { $ext = pathinfo($data['name'], PATHINFO_EXTENSION); $filename = pathinfo($data['name'], PATHINFO_FILENAME); return $filename . '-' . uniqid() . '.' . $ext; }, 'transformer' => function (\Cake\Datasource\RepositoryInterface $table, \Cake\Datasource\EntityInterface $entity, $data, $field, $settings) { $filename = pathinfo($data['name'], PATHINFO_FILENAME); $extension = pathinfo($data['name'], PATHINFO_EXTENSION); $tsTmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension; $smlTmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension; $tsSize = new \Imagine\Image\Box(339, 339); $smlSize = new \Imagine\Image\Box(678, 678); $mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET; $imagine = new \Imagine\Gd\Imagine(); $imagine->open($data['tmp_name']) ->thumbnail($tsSize, $mode) ->save($tsTmp); $imagine->open($data['tmp_name']) ->thumbnail($smlSize, $mode) ->save($smlTmp); return [ $data['tmp_name'] => $data['name'], $tsTmp => 'thumbs' . DS . $filename . '-339.' . $extension, $smlTmp => 'thumbs' . DS . $filename . '-678.' . $extension, ]; }, 'keepFilesOnDelete' => false, ], ]); return $this->patchEntity($productImage, $request); }
what i'm missing here?
i need to set the behaviors config in a Method to avoid that images are missing when Entiy is Duplicated at Products Controller.
ProductImagesController
ProductImagesTable
what i'm missing here?