How to change the code so that there is no re-saving the image after saving the model? what would the server do extra work and save it all at once? Here is the actual code of the method

public function saveAction() { $id = $this->getRequest()->getParam('id'); if ($data = $this->getRequest()->getPost()) { try { $helper = Mage::helper('ffwposts'); $model = Mage::getModel('ffwposts/posts'); $model->setData($data); if (!$model->getCreated()) { $model->setCreated(now()); } $model->save(); $id = $model->getId(); $model->setImage($model->getId() . ".jpg")->save(); if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') { $uploader = new Varien_File_Uploader('image'); $uploader->setAllowedExtensions(array('jpg', 'jpeg')); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); $uploader->save($helper->getImagePath(), $id . '.jpg'); // Upload the image } else { if (isset($data['image']['delete']) && $data['image']['delete'] == 1) { @unlink($helper->getImagePath($id)); } } Mage::getSingleton('adminhtml/session')->addSuccess($this->__('News was saved successfully')); Mage::getSingleton('adminhtml/session')->setFormData(false); $this->_redirect('*/*/'); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setFormData($data); $this->_redirect('*/*/edit', array( 'id' => $id )); } return; } Mage::getSingleton('adminhtml/session')->addError($this->__('Unable to find item to save')); $this->_redirect('*/*/'); } Надеюсь я понятно изложил свою мысль, заранее спасибо) 

    2 answers 2

    I understand the problem in this piece

     $model->save(); $id = $model->getId(); $model->setImage($model->getId() . ".jpg")->save(); 

    I can offer to create a trigger in the database.

    If you use mysql it will be something like

     CREATE TRIGGER foo AFTER INSERT ON posts FOR EACH ROW IF NEW.image IS NULL THEN SET NEW.image := CONCAT(NEW.id,'.jpg'); END IF;; 

      I went a little different way and the place id assigned to the picture the name consisting of a random string

       $img = $model->setImage(Mage::helper('core')->getRandomString(5) . ".jpg")->save(); $post_img = $model->getImage(); if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') { $uploader = new Varien_File_Uploader('image'); $uploader->setAllowedExtensions(array('jpg', 'jpeg')); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); $uploader->save($helper->getImagePath(), $post_img); 

      and saves 1 time and does not overwrite the name)