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:
- // YourForm.class.php
- /**
- * Overrides the updateObject method to customize the filename of a file field
- *
- * @param <type> $values
- */
- public function updateObject($values = null)
- {
- if($this->object->isNew())
- {
- if($values == null)
- $values = $this->values;
- // We save the thumbnail and the gamefile to the correct folder
- if($values['thumbnail'] != null)
- {
- $slugifiedName = Doctrine_Inflector::urlize($values['object_name']);
- {
- throw new sfException('Game class requires ' . $method . ' method');
- }
- $filename = $this->object->$method($values['thumbnail'], $slugifiedName);
- $this->object->thumbnail = $this->saveFile('thumbnail', $filename);
- // We need to unset the field so that the file is not saved twice
- }
- }
- }
- parent::updateObject($values);
- }
Then, you need to create the generateXxxFilename method in your model's class:
- /**
- *
- * @param sfValidatedFile $file File to generate a filename to
- * @param string $objectSlug Slugged name of the object
- * @return string Filename of the object to be saved
- */
- public function generateThumbnailFilename(sfValidatedFile $file, $objectSlug = null)
- {
- $objectSlug = $this->slug;
- return "";
- return $objectSlug . '/thumbnail' . $file->getExtension();
- }
Submitted by miguelSantirso over 2 years ago — last modified less than a minute ago