CakePHP | Delete attachments when working with CakePHP Media Plugin

When working with CakePHP, everyone certainly benefited with various additives - component, plugin, etc. One of the best plugins is Media. It is used to handle file transfer, create thumbnails of the pictures. The module is well customizable and relatively easy to use.

I use it every day, because it significantly reduces the time it takes to prepare a variety of modules on site. Let's say that you have to prepare the module for storing attachments - send the file and enter a name for him. Sending a file can be already automatically write to the database file information, it is automatic. For more information about Media will be available in another article.

The problem, which often appear when removing attachments, along with the removal of records from the database. To solve the modified model is needed.

var $actsAs = array( 'Media.Transfer', 'Media.Coupler', 'Tree' );

Must first be informed that use with media and the use with Transfer and Coupler this time we do not want generator. This write indicates that we will not upload files to generate thumbnails for images, so then we are interested in the transfer folder in the folder media. The next step is to add functions beforeDelete which is called just before deleting the record from the database.

public function beforeDelete($cascade = true) {   if (!$cascade) {      return true;   }    $result = $this->find('first', array(      'conditions' => array($this->primaryKey => $this->id),      'fields' => array('dirname', 'basename'),      'recursive' => -1   ));   if (empty($result['nazwa_modelu']['basename'])) {      return true;   }    $pattern = MEDIA_FILTER . "*/";   $pattern .= $result[$this->alias]['dirname'] . '/';   $pattern .= pathinfo($result[$this->alias]['basename'], PATHINFO_FILENAME);    $files = glob("{$pattern}.*");    $name = Mime_Type::guessName($result[$this->alias]['basename']);    foreach ($files as $file) {      $File = new File($file);       if (!$File->delete()) {         return false;      }   }   return true; }

This code ensures that with the record will be removed from the server associated file. What the other hand, if we want to delete a record which has not been assigned any file? In such a situation, "turn on" a conditional statement:

if (empty($result['Download']['basename'])) {   return true;}

If the box indicating the name of the file is empty, it is returned TRUE, so let remove the record from the database, thus do not care about deleting files in the following function.

Contact