Are you new? Read the FAQ and catch up on!
1k views

Change the filename of an upload field according to other fields in a symfony form

When you need to customize the filename of an uploaded file in symfony, you have to use the generateXxxFilename function in the model. However, you can not access the data of the object (its name, for instance) when the object is new because it has not been saved yet. I needed to do this, and with some help from the symfony users group, I found a solution:

The solution is to override the updateObject method in the form Class. In my case, the file to upload is thumbnail and the code is something like this:

PHP
  1. // YourForm.class.php
  2.  
  3. /**
  4.  * Overrides the updateObject method to customize the filename of a file field
  5.  *
  6.  * @param <type> $values
  7.  */
  8. public function updateObject($values = null)
  9. {
  10.     if($this->object->isNew())
  11.     {
  12.         if($values == null)
  13.             $values = $this->values;
  14.  
  15.             // We save the thumbnail and the gamefile to the correct folder
  16.             if($values['thumbnail'] != null)
  17.             {
  18.                 $slugifiedName = Doctrine_Inflector::urlize($values['object_name']);
  19.  
  20.                 $method = sprintf('generate%sFilename', $this->camelize('thumbnail'));
  21.  
  22.                 if (!method_exists($this->object, $method))
  23.                 {
  24.                     throw new sfException('Game class requires ' . $method . ' method');
  25.                 }
  26.  
  27.                 $filename = $this->object->$method($values['thumbnail'], $slugifiedName);
  28.                 $this->object->thumbnail = $this->saveFile('thumbnail', $filename);
  29.  
  30.                 // We need to unset the field so that the file is not saved twice
  31.                 unset($values['thumbnail']);
  32.             }
  33.         }
  34.     }
  35.  
  36.     parent::updateObject($values);
  37. }
  38.  

­

Then, you need to create the generateXxxFilename method in your model's class:

PHP
  1. /**
  2.  *
  3.  * @param sfValidatedFile $file File to generate a filename to
  4.  * @param string $objectSlug Slugged name of the object
  5.  * @return string Filename of the object to be saved
  6.  */
  7. public function generateThumbnailFilename(sfValidatedFile $file, $objectSlug = null)
  8. {
  9.     if(is_null($objectSlug))
  10.         $objectSlug = $this->slug;
  11.  
  12.     if(is_null($objectSlug))
  13.         return "";
  14.  
  15.     return $objectSlug . '/thumbnail' . $file->getExtension();
  16. }
  17.  

­

Tags: PHP symfony sfValidator sfForm symfony forms

Embed: