Search code examples
phpmysqlfilejoomlaupload

Joomla set `file` field value after save


For my backend component i need able upload image for my items. It all works fine, i add field for image:

<field
    type="file"
    name="category_image"
    accept="image/*"
    label="COM_SKYCATALOG_ITEM_CATEGORY_IMAGE_LABEL"
    directory=""
    preview="false"
/>

and then update save() method to control upload:

$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');      

$fileinfo =pathinfo($files['category_image']['name']);

$ext = $fileinfo['extension'];
$filename = time().".$ext";     

$tmp_file = $files['category_image']['tmp_name'];

$dest = "../media/com_xxxxx/upload/".$filename;

if (JFile::upload($tmp_file, $dest)) {
      // successed :)
} else {              
     // failed :(
echo "FAAAIL!!!";
die();
}        

When i choose file and save item, file uploaded to folder, but then category image field is empty. And also field for category_image in mysql table did not updated, but when i use media field type it works fine.

What is possible wrong here?

I did not like media manager it to slow to work with.


Solution

  • I manage to solve this problem. You cant set value of input tag with file type, because of security reasons. I mean you can set value attribute but field wil displayed as blank.

    So i just create a custom field like this:

    class JFormFieldSkyupload extends JFormField
    {
        /**
         * The field type.
         *
         * @var         string
         */
        protected $type = 'Skyupload';
    
        /**
         * Method to get a list of options for a list input.
         *
         * @return  array  An array of JHtml options.
         */
        public function getInput() {
            return '<div class="filename_labe">'.$this->value.'</div><input name="'.$this->name.'" id="'.$this->id.'" accept="image/*" aria-invalid="false" type="file" value="'.$this->value.'">';
            // code that returns HTML that will be shown as the form field
        }
    
    }
    

    And also i made some changes in upload code, so even if no new file selected i am able to save form without error:

    if ($files['category_image']['name']!="")
    {
        $fileinfo =pathinfo($files['category_image']['name']);
    
        $ext = JFile::getExt($files['category_image']['name']);
        $filename = time().".$ext";
    
        $tmp_file = $files['category_image']['tmp_name'];
    
        $dest = "../media/com_skycatalog/upload/".$filename;
    
        if (JFile::upload($tmp_file, $dest)) {
        // successed :)
        } else {                  
        // failed :(
        echo "FAAAIL!!!";
        die();      
        }        
    
    $data = JRequest::getVar( 'jform', null, 'post', 'array' );
    $data['category_image'] = strtolower( $filename );
    JRequest::setVar('jform', $data );
    

    }

    Now it will update file name in DB only if i upload new file.