I'm developing a custom component for creating, editing and saving data of single records including images. I know that in admin/models/forms/record.xml there must be field name="image" type="file" accept="image/*" but how and where do I need to write the simple php-code for uploading images to specific folder, in which file and how? Where to write the code from example by the link https://docs.joomla.org/How_to_use_the_filesystem_package ?
EDITED: Now I added in my admin/com_mycom/controllers/record.php the code:
public function save($data = array(), $key = 'id') { $file = JRequest::getVar('image', null, 'files', 'array'); $filename = JFile::makeSafe($file['name']); $src = $file['tmp_name']; $dest = "media/com_mycom/img/".$filename; if (JFile::upload($src, $dest)) { //Redirect to a page of your choice } else { //Redirect and throw an error message } parent::save(); } $data = array(), $key = 'id' I got from function allowEdit()
SOLVED BUT... So the problem was in the name of input. JRequest::getVar contains 'image' but input type="file" has name="jform[image]". I've found the code:
$jinput = JFactory::getApplication()->input; $files = $jinput->files->get('jform'); $file = $files['image']; instead of
$file = JRequest::getVar('image', null, 'files', 'array'); and now the file is being uploaded but unfortunately its name is not being updated in the DB
Ok, I've added under if (JFile::upload($src, $dest)) { the code:
$thisID = JRequest::getVar('id'); $db = JFactory::getDbo(); $query = $db->getQuery(true); $fields = array($db->quoteName('image') . " = " . $db->quote($filename)); $conditions = array($db->quoteName('id') . " = " . $thisID); $query->update($db->quoteName('#__mycom'))->set($fields)->where($conditions); $db->setQuery($query); $db->execute($query); but is there some simplest way to update filename in the DB ?