Прод. – Добавить загрузчика файлов в компонент Joomla Admin
Я смог загрузить файл и сохранить его на диске. Но это не сохранение имени файла в базе данных.
Как мне это сделать ?
Вот контроллер –
class InvoiceManagerControllerInvoiceManager extends JControllerForm { function save(){ $file = JRequest::getVar('jform', null, 'files', 'array'); $path = JPATH_BASE; // Make the file name safe. jimport('joomla.filesystem.file'); $file['name']['invoice'] = JFile::makeSafe($file['name']['invoice']); // Move the uploaded file into a permanent location. if (isset($file['name']['invoice'])) { // Make sure that the full file path is safe. $filepath = JPath::clean($path. DS ."components". DS ."com_invoicemanager". DS ."files". DS .strtolower($file['name']['invoice'])); // Move the uploaded file. JFile::upload( $file['tmp_name']['invoice'], $filepath ); } return parent::save(); } }
Поле формы в XML –
<field name="invoice" type="file"/>
UPDATE: после добавления следующих строк, взятых из кода @Andras Gera
$data = JRequest::getVar( 'jform', null, 'post', 'array' ); $data['invoice'] = strtolower( $file['name']['invoice'] ); JRequest::setVar('jform', $data );
Я столкнулся с той же проблемой, может быть, мы сможем идти вперед вместе. Вот мои коды:
/administrator/components/com_comp_name/models/forms/edit.xml
<?xml version="1.0" encoding="utf-8"?> <form addrulepath="/administrator/components/com_gonewsletter/models/rules"> <fieldset name="details"> <field name="id" type="hidden" /> <field name="title" type="text" label="COM_GONEWSLETTER_EDIT_TITLE_LABEL" description="COM_GONEWSLETTER_EDIT_TITLE_DESC" size="40" class="inputbox" required="true" default="" /> <field name="date" type="calendar" label="COM_GONEWSLETTER_EDIT_DATE_LABEL" description="COM_GONEWSLETTER_EDIT_DATE_DESC" size="40" class="inputbox" required="true" default="" format="%Y-%m-%d" /> <field name="published" type="list" label="JSTATUS" description="COM_GONEWSLETTER_EDIT_PUBLISHED_DESC" class="inputbox" size="1" default="0"> <option value="1">JPUBLISHED</option> <option value="0">JUNPUBLISHED</option> </field> <field type="file" name="pdf_file" label="COM_GONEWSLETTER_EDIT_FILE_LABEL" default="" description="COM_GONEWSLETTER_EDIT_FILE_DESC" size="40" accept="application/pdf" class="fileuploader" /> <field name="file" type="hidden" /> </fieldset> </form>
по<?xml version="1.0" encoding="utf-8"?> <form addrulepath="/administrator/components/com_gonewsletter/models/rules"> <fieldset name="details"> <field name="id" type="hidden" /> <field name="title" type="text" label="COM_GONEWSLETTER_EDIT_TITLE_LABEL" description="COM_GONEWSLETTER_EDIT_TITLE_DESC" size="40" class="inputbox" required="true" default="" /> <field name="date" type="calendar" label="COM_GONEWSLETTER_EDIT_DATE_LABEL" description="COM_GONEWSLETTER_EDIT_DATE_DESC" size="40" class="inputbox" required="true" default="" format="%Y-%m-%d" /> <field name="published" type="list" label="JSTATUS" description="COM_GONEWSLETTER_EDIT_PUBLISHED_DESC" class="inputbox" size="1" default="0"> <option value="1">JPUBLISHED</option> <option value="0">JUNPUBLISHED</option> </field> <field type="file" name="pdf_file" label="COM_GONEWSLETTER_EDIT_FILE_LABEL" default="" description="COM_GONEWSLETTER_EDIT_FILE_DESC" size="40" accept="application/pdf" class="fileuploader" /> <field name="file" type="hidden" /> </fieldset> </form>
по<?xml version="1.0" encoding="utf-8"?> <form addrulepath="/administrator/components/com_gonewsletter/models/rules"> <fieldset name="details"> <field name="id" type="hidden" /> <field name="title" type="text" label="COM_GONEWSLETTER_EDIT_TITLE_LABEL" description="COM_GONEWSLETTER_EDIT_TITLE_DESC" size="40" class="inputbox" required="true" default="" /> <field name="date" type="calendar" label="COM_GONEWSLETTER_EDIT_DATE_LABEL" description="COM_GONEWSLETTER_EDIT_DATE_DESC" size="40" class="inputbox" required="true" default="" format="%Y-%m-%d" /> <field name="published" type="list" label="JSTATUS" description="COM_GONEWSLETTER_EDIT_PUBLISHED_DESC" class="inputbox" size="1" default="0"> <option value="1">JPUBLISHED</option> <option value="0">JUNPUBLISHED</option> </field> <field type="file" name="pdf_file" label="COM_GONEWSLETTER_EDIT_FILE_LABEL" default="" description="COM_GONEWSLETTER_EDIT_FILE_DESC" size="40" accept="application/pdf" class="fileuploader" /> <field name="file" type="hidden" /> </fieldset> </form>
по<?xml version="1.0" encoding="utf-8"?> <form addrulepath="/administrator/components/com_gonewsletter/models/rules"> <fieldset name="details"> <field name="id" type="hidden" /> <field name="title" type="text" label="COM_GONEWSLETTER_EDIT_TITLE_LABEL" description="COM_GONEWSLETTER_EDIT_TITLE_DESC" size="40" class="inputbox" required="true" default="" /> <field name="date" type="calendar" label="COM_GONEWSLETTER_EDIT_DATE_LABEL" description="COM_GONEWSLETTER_EDIT_DATE_DESC" size="40" class="inputbox" required="true" default="" format="%Y-%m-%d" /> <field name="published" type="list" label="JSTATUS" description="COM_GONEWSLETTER_EDIT_PUBLISHED_DESC" class="inputbox" size="1" default="0"> <option value="1">JPUBLISHED</option> <option value="0">JUNPUBLISHED</option> </field> <field type="file" name="pdf_file" label="COM_GONEWSLETTER_EDIT_FILE_LABEL" default="" description="COM_GONEWSLETTER_EDIT_FILE_DESC" size="40" accept="application/pdf" class="fileuploader" /> <field name="file" type="hidden" /> </fieldset> </form>
по<?xml version="1.0" encoding="utf-8"?> <form addrulepath="/administrator/components/com_gonewsletter/models/rules"> <fieldset name="details"> <field name="id" type="hidden" /> <field name="title" type="text" label="COM_GONEWSLETTER_EDIT_TITLE_LABEL" description="COM_GONEWSLETTER_EDIT_TITLE_DESC" size="40" class="inputbox" required="true" default="" /> <field name="date" type="calendar" label="COM_GONEWSLETTER_EDIT_DATE_LABEL" description="COM_GONEWSLETTER_EDIT_DATE_DESC" size="40" class="inputbox" required="true" default="" format="%Y-%m-%d" /> <field name="published" type="list" label="JSTATUS" description="COM_GONEWSLETTER_EDIT_PUBLISHED_DESC" class="inputbox" size="1" default="0"> <option value="1">JPUBLISHED</option> <option value="0">JUNPUBLISHED</option> </field> <field type="file" name="pdf_file" label="COM_GONEWSLETTER_EDIT_FILE_LABEL" default="" description="COM_GONEWSLETTER_EDIT_FILE_DESC" size="40" accept="application/pdf" class="fileuploader" /> <field name="file" type="hidden" /> </fieldset> </form>
и /administrator/components/com_comp_name/controllers/edit.php
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla controllerform library jimport('joomla.application.component.controllerform'); /** * GoNewsletter Controller */ class GoNewsletterControllerEdit extends JControllerForm { function __construct($config = array()) { $this->view_list = 'List'; parent::__construct($config); } function save(){ // ---------------------------- Uploading the file --------------------- // Neccesary libraries and variables jimport( 'joomla.filesystem.folder' ); jimport('joomla.filesystem.file'); $data = JRequest::getVar( 'jform', null, 'post', 'array' ); // Create the gonewsleter folder if not exists in images folder if ( !JFolder::exists( JPATH_SITE . DS . "images" . DS . "gonewsletter" ) ) { JFolder::create( JPATH_SITE . DS . "images" . DS . "gonewsletter" ); } // Get the file data array from the request. $file = JRequest::getVar( 'jform', null, 'files', 'array' ); // Make the file name safe. $filename = JFile::makeSafe($file['name']['pdf_file']); // Move the uploaded file into a permanent location. if ( $filename != '' ) { // Make sure that the full file path is safe. $filepath = JPath::clean( JPATH_SITE . DS . 'images' . DS . 'gonewsletter' . DS . strtolower( $filename ) ); // Move the uploaded file. JFile::upload( $file['tmp_name']['pdf_file'], $filepath ); // Change $data['file'] value before save into the database $data['file'] = strtolower( $filename ); } // ---------------------------- File Upload Ends ------------------------ JRequest::setVar('jform', $data ); return parent::save(); } }
Если вы распечатаете данные $ перед отправкой на родительский :: save ($ data), он содержит правильные поля, которые вы хотите сохранить, но это не так. Я попытался использовать тип ввода = текст вместо type = file, и он корректно сохраняет.
Я попробовал другой способ: input type = file и name = pdf_file, после чего я добавил скрытое поле name = file default = "". И затем я установил это скрытое значение поля для имени файла без успеха. Может быть, я делал что-то неправильно. Продолжайте понимать что-то.
Вы можете использовать move_uploaded_file()
php move_uploaded_file()
//import joomlas filesystem functions, we will do all the filewriting with joomlas functions jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); //this is the name of the field in the html form, filedata is the default name for swfupload $fieldName = 'Filedata'; //the name of the file in PHP's temp directory that we are going to move to our folder $fileTemp = $_FILES[$fieldName]['tmp_name']; //always use constants when making file paths, to avoid the possibilty of remote file inclusion $uploadPath = JPATH_SITE.DS.'path'.DS.'path'.DS.$fileName; if(!JFile::upload($fileTemp, $uploadPath)) { echo JText::_( 'ERROR MOVING FILE' ); return; } else { //Updating the db with the $fileName. $db =& JFactory::getDBO(); $query = $db->getQuery(true); $query->update($db->nameQuote(TABLE_PREFIX.'table_name')); $query->set($column.' = '.$db->quote($fileName)); $query->where($db->nameQuote('id').'='.$db->quote($id)); $db->setQuery($query); $db->query(); }
$ column – имя столбца db файла $ fileName – имя файла
Запрос запускается, если файл успешно загружен.
задайте имя файла в переменной запроса, так как теперь переменная $ _FILES
JRequest::setVar('jform[invoice]',$file['name']['invoice'] );
// полный код
class InvoiceManagerControllerInvoiceManager extends JControllerForm { function save(){ $file = JRequest::getVar('jform', null, 'files', 'array'); $path = JPATH_BASE; // Make the file name safe. jimport('joomla.filesystem.file'); $file['name']['invoice'] = JFile::makeSafe($file['name']['invoice']); // Move the uploaded file into a permanent location. if (isset($file['name']['invoice'])) { // Make sure that the full file path is safe. $filepath = JPath::clean($path. DS ."components". DS ."com_invoicemanager". DS ."files". DS .strtolower($file['name']['invoice'])); // Move the uploaded file. JFile::upload( $file['tmp_name']['invoice'], $filepath ); JRequest::setVar('jform[invoice]',$file['name']['invoice'] ); } return parent::save(); } }
На joomla 3.2.x я должен переопределить функцию сохранения моего класса модели, чтобы сохранить имя загруженного файла в db, например
public function save($data){ $input = JFactory::getApplication()->input; $files = $input->files->get('jform'); $fieldName = 'thumbnail'; $data['thumbnail'] = $files[$fieldName]['name']; return parent::save($data); }