Question

This is my first time with prestashop and following the docs I was able to create a simple module that store some text.
I want to modify it and add the possibility to upload an image...on this scenario the docs is very poor so I tried myself and I was ablo to upload it but if I try to pass the image to the fronend all I get is NULL.

This is my configuration file:

<?php if ( ! defined('_PS_VERSION_') ) exit;


class Stilogopopup extends Module
{
    public function __construct()
    {
        $this->name                   = 'stilogopopup';
        $this->tab                    = 'front_office_features';        //Indica dove posizionare il modulo (http://doc.prestashop.com/display/PS15/Creating+a+PrestaShop+module)
        $this->version                = '1.0.0';
        $this->author                 = 'Christian Giupponi STILOGO';
        $this->need_instance          = 0;                              //Indica se il modulo deve essere caricato quando si entra nel backoffice 0=no 1=si
        $this->ps_versions_compliancy = array('min' => '1.5');

        parent::__construct();

        $this->displayName        = $this->l('STILOGO PopUp');
        $this->description        = $this->l('Permette di mostrare un PopUp contenente un testo o una immagine');
        $this->confirmUninstall   = $this->l('Sicuro di voler disinstallare questo modulo?');

        if( ! Configuration::get('STILOGOPOPUP_NAME') )
        {
            $this->warning = $this->l('Non è stato fornito nessun nome');
        }
    }

    /*
     *  Installazione
     *  In questa funzione definisco anche gli hook per il frontend.
     *  Un elenco degli hook disponibili:   
     *      http://doc.prestashop.com/display/PS15/Hooks+in+PrestaShop+1.5
     */
    public function install()
    {
        if( parent::install() == false )
        {
            return false;
        }               

        //Registro un hook per la homepage
        if( ! $this->registerHook('displayHome') )
            return false;

        //Registro un hook per aggiungere dati all'header
        if( ! $this->registerHook('displayHeader') )
            return false;

        Configuration::updateValue('STILOGOPOPUP_NAME', 'popup');

        //Fatto
        return true;
    }

    public function uninstall()
    {
        if( ! parent::uninstall() )
        {
            return false;
        }

        if( ! Configuration::deleteByName('STILOGOPOPUP_NAME') )
        {
            return false;
        }

        return true;
    }

    /*
     *  Questa funzione viene richiamata dal frontend quando viene eseguito l'hook:
     *      displayHome
     *  In questo modo posso inviare al frontend delle variabili per essere utilizzate
     *  dal template engine smarty.
     *  E' un semplice array che assegna alle variabili il valore delle configurazioni
     *  e recupera il file template che contiene il codice da mostrare in home
     */
    public function hookDisplayHome( $params )
    {
        $this->context->smarty->assign(
            array(
                'stilogopopup_testo'    => Configuration::get('STILOGOPOPUP_TEXT'),
                'stilogopopup_titolo'   => Configuration::get('STILOGOPOPUP_TITLE'),
                'stilogopopup_image'    => Configuration::get('STILOGOPOPUP_IMAGE'),
                'stilogopopup_link'     => $this->context->link->getModuleLink('stilogopopup', 'display')
            )
        );

        return $this->display(__FILE__ , 'stilogopopup.tpl');
    }

    /*
     *  Questa funzione viene richiamata dal frontend quando viene eseguito l'hook:
     *      displayHeader
     *  e permette di inserire all'interno dei tag <head> del codice aggiuntivo,
     *  Utile quando si ha la necessità di inserire file css o js
    */
    public function HookDisplayHeader()
    {
        $this->context->controller->addCSS($this->_path.'css/stilogopopup.css', 'all');
        $this->context->controller->addJS($this->_path.'js/stilogopopup.js', 'all');
    }

    /*
     *  Questa funzione è utilizzata nel backend di prestashop per mostrare il form di configurazione
     *  del modulo.
     *  Gestisce sia il salvataggio dei parametri di configurazione che la stampa del form (tramite funzione esterna)
     */
    public function getContent()
    {
        $output = null;     

        //Controllo se devo salvare dei dati
        if( Tools::isSubmit('submit'.$this->name) )
        {           
            //Recupero i valori degli input
            $stilogopopup_text  = strval(Tools::getValue('STILOGOPOPUP_TEXT'));
            $stilogopopup_title = strval(Tools::getValue('STILOGOPOPUP_TITLE'));            
            $stilogo_image      = $_FILES['STILOGOPOPUP_IMAGE'];

            //Controllo se c'è una immagine da salvare
            if( $stilogo_image['name'] != "" )
            {
                //Formati accettati
                $allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');

                //Controllo che l'immagine sia in un formato accettato
                if( in_array($stilogo_image['type'], $allowed) )
                {
                    $path = '../upload/';

                    //Controllo se esiste già un file con questo nome

                    //Carico il file
                    if( ! move_uploaded_file($stilogo_image['tmp_name'], $path.$stilogo_image['name']) )
                    {
                        $output .= $this->displayError( $path.$stilogo_image['name'] );
                        return $output.$this->displayForm();
                    }
                }
                else
                {
                    $output .= $this->displayError( $this->l('Formato immagine non valido.') );
                    return $output.$this->displayForm();
                }
            }   

            //Controllo se i campi obbligatori sono effettivamente stati riempiti
            if( ! $stilogopopup_title || empty($stilogopopup_title) || ! Validate::isGenericName($stilogopopup_title) )
            {
                $output .= $this->displayError( $this->l('Devi inserire un titolo.') );
                return $output.$this->displayForm();
            }


            //Se arrivo qui è perchè tutti i campi obbligatori sono stati riempiti quindi aggiorno i valori
            Configuration::updateValue('STILOGOPOPUP_TEXT', $stilogopopup_text);
            Configuration::updateValue('STILOGOPOPUP_TITLE', $stilogopopup_title);
            Configuration::updateValue('STILOGOPOPUP_IMAGE', $stilogopopup_image['name']);

            $output .= $this->displayConfirmation( $this->l('Impostazioni salvate') );                      
        }   

        //Richiamo la funzione di stampa del form e concateno il ritultato (se c'è) del salvataggio
        return $output.$this->displayForm();
    }

    /*
     *  Questa è la funzione che si occupa di generare il form di configurazione del modulo.
     *  Viene richiamata dalla funzione getContent e permette di definire dei campi da mostrare all'utente.
     *  Per generare i campi si utilizza un semplice array.
     *  Qui un elenco di tutti i tipi supportati:
     *      http://doc.prestashop.com/display/PS15/HelperForm
     */
    public function displayForm()
    {
        //Recupero la lingua di default
        $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');

        //Creo i campi del form
        $fields_form[0]['form'] = array(
            'legend' => array(
                'title' => $this->l('Impostazioni')
            ),
            'input' => array(
                array(
                    'type'     => 'text',
                    'label'    => $this->l('Titolo del PopUp'),
                    'name'     => 'STILOGOPOPUP_TITLE',
                    'required' => true
                ),
                array(
                    'type'     => 'textarea',
                    'label'    => $this->l('Testo del PopUp'),
                    'name'     => 'STILOGOPOPUP_TEXT',
                    'required' => false
                ),
                array(
                    'type'     => 'file',
                    'label'    => $this->l('Inserisci una immagine'),
                    'name'     => 'STILOGOPOPUP_IMAGE',
                    'display_image' => true,
                    'required' => false
                ),
            ),
            'submit' => array(
                'title' => $this->l('Salva'),
                'class' => 'button'             
            ),          
        );

        $helper = new HelperForm();

        // Module, token and currentIndex
        $helper->module            = $this;
        $helper->name_controller   = $this->name;
        $helper->token             = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex      = AdminController::$currentIndex.'&configure='.$this->name;

        // Language
        $helper->default_form_language     = $default_lang;
        $helper->allow_employee_form_lang  = $default_lang;

        // Title and toolbar
        $helper->title             = $this->displayName;
        $helper->show_toolbar      = true;        // false -> rimuove la toolbar
        $helper->toolbar_scroll    = true;      // yes - > Toolbar is always visible on the top of the screen.
        $helper->submit_action     = 'submit'.$this->name;
        $helper->toolbar_btn       = array(
                                            'save' => array(
                                                            'desc' => $this->l('Salva'),
                                                            'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
                                                            '&token='.Tools::getAdminTokenLite('AdminModules'),
                                                      ),
                                            'back' => array(
                                                            'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
                                                            'desc' => $this->l('Back to list')
                                                      )
                                    );

        // Carico i valori correnti
        $helper->fields_value['STILOGOPOPUP_TEXT']     = Configuration::get('STILOGOPOPUP_TEXT');
        $helper->fields_value['STILOGOPOPUP_TITLE']    = Configuration::get('STILOGOPOPUP_TITLE');

        //Genero il form
        return $helper->generateForm($fields_form);
    }
}

?>

As you can see I have added in the displayForm function this code that should add a file input:

array(
    'type'     => 'file',
    'label'    => $this->l('Inserisci una immagine'),
    'name'     => 'STILOGOPOPUP_IMAGE',
    'display_image' => true,
    'required' => false
),

and it does...in the getContent, where according to the docs all the save/display should live I get the image with PHP (does prestashop have a better built in solution for this?) in this way:

$stilogo_image      = $_FILES['STILOGOPOPUP_IMAGE'];

            //Controllo se c'è una immagine da salvare
            if( $stilogo_image['name'] != "" )
            {
                //Formati accettati
                $allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');

                //Controllo che l'immagine sia in un formato accettato
                if( in_array($stilogo_image['type'], $allowed) )
                {
                    $path = '../upload/';

                    //Controllo se esiste già un file con questo nome

                    //Carico il file
                    if( ! move_uploaded_file($stilogo_image['tmp_name'], $path.$stilogo_image['name']) )
                    {
                        $output .= $this->displayError( $path.$stilogo_image['name'] );
                        return $output.$this->displayForm();
                    }
                }
                else
                {
                    $output .= $this->displayError( $this->l('Formato immagine non valido.') );
                    return $output.$this->displayForm();
                }
            }   

Then I saved just the image name here:

Configuration::updateValue('STILOGOPOPUP_IMAGE', $stilogopopup_image['name']);

and I send it to the front end in the hookDisplayHome function in this way:

$this->context->smarty->assign(
            array(
                'stilogopopup_testo'    => Configuration::get('STILOGOPOPUP_TEXT'),
                'stilogopopup_titolo'   => Configuration::get('STILOGOPOPUP_TITLE'),
                'stilogopopup_image'    => Configuration::get('STILOGOPOPUP_IMAGE'),
                'stilogopopup_link'     => $this->context->link->getModuleLink('stilogopopup', 'display')
            )
        );

        return $this->display(__FILE__ , 'stilogopopup.tpl');

The problem is that the smarty variable $stilogopopup_image is NULL and I can see it just if I add in my view the {debug} tag.

What is the problem? The other fields works

Was it helpful?

Solution

in getContent() function you use the "$stilogo_image" variable, but for save to DB (Configuration::updateValue()) you are use another variable the "$stilogopopup_image".

I think this is the main reason of empty value in Configuration::get('STILOGOPOPUP_IMAGE')

Regards

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top