Top 5 PrestaShop Questions and Answers of 2016 Part 1

Posted On: Sep 17, 2018

Categories: Shopping Carts & Platforms

It’s been getting quite busy here at FMModules , as we were developing lots of new plugins and also updating them for Multi-store features . Majority of our site visitors asks us about solutions of their problems regarding PrestaShop and we feel happy to help them free of cost. However in some cases, where the problems solving needs time, we have to charge the visitors accordingly.

This article entails the series of PrestaShop queries and answers on FMM blog. Let’s take on to the latest hot questions and answers of 2016.

Question No. 1

Prestashop - AuthController.php is not receiving input values

I'm attempting to include google reCaptcha to prestashop's opc sign up page, I own the checkbox setup and it's operating however the php file is not getting the captcha response. Let me clarify. Here's what I've carried out so far: In my header .tpl I placed

In order-opc-new-account.tpl, I added

<div class="g-recaptcha"data-sitekey="[my_public_key]">

In my AuthController.php I added

if (Tools::isSubmit('submitAccount') OR Tools::isSubmit('submitGuestAccount')) //if statement was already present

{  

    // captcha code I added

    $reCaptchaUrl='https://www.google.com/recaptcha/api/siteverify';

    $reCaptchaSecret = '[my_secret_key]';

    $reCaptchaResponse = $_POST['g-recaptcha-response'];

    $ip = $_SERVER['REMOTE_ADDR'];

 

    $verifyCaptcha = file_get_contents($reCaptchaUrl."?secret=".$reCaptchaSecret."&response=".$reCaptchaResponse."&remoteip=".$ip);

    $captchaReply = json_decode($verifyCaptcha);

 

    if(isset($captchaReply->success) AND $captchaReply->success == true){

        $logger = newFileLogger(0);

        $logger->setFilename(_PS_ROOT_DIR_."/log/debug.log");

        $logger->logDebug("Captcha was successful: ".$reCaptchaResponse);

    } else {

        //captcha failed

        $logger = newFileLogger(0);

        $logger->setFilename(_PS_ROOT_DIR_."/log/debug.log");

        $logger->logDebug("Captcha failed: ".$reCaptchaResponse);

    }

     // ... prestashop registration code

}

I learned with the debugging messages that $reCaptchaResponse variable is actually coming empty everytime, even if the captcha has been checked. Any ideas why?

Edit: The form actually sends the data to authentication.php which has the following lines

require(dirname(__FILE__).'/config/config.inc.php');

ControllerFactory::getController('AuthController')->run();

My thinking is that this part of code forwards the form data to AuthController .php however it only forwards fields that it's been told to forward. It does not knows the new recaptcha field and doesn't forward that information to the file. Therefore I needs to find who chooses which data get's forwarded.

Answer No. 1

Make sure 

 is in the FORM element.

Question No. 2

How to set value of hidden or text field when user clicks save in prestashop1.6

I want to change the value of a field in $this->fields_form when submit is clicked ie before the value enters into the table i want to change the forms value in which i am going to insert 

// This  form is populated  when  add or edit is clicked
   public function renderForm()
  {
    $years        = Tools::dateYears();
    $months       = Tools::dateMonths();
    $days         = Tools::dateDays();
    $ticketSeries = Winners::getTicketSeries();
    $prdtCategory = Winners::getProductCategory();
    $nationality  = Winners::getNationality();
    $firstArray = 
             array(array(
                'type' => 'text',
                'label' => $this->l('Name'),
                'name' => 'name',
                'required' => true,
                'col' => '4',
                'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()@#"°{}_$%:'
            ),
               array(
                'type'     => 'file',
                'label'    => $this->l('Winner Image'),
                'name'     => 'winner_image',
                'display_image' => true,
                'required' => false
            ),
             array(
                'type' => 'text',
                'label' => $this->l('Ticket No'),
                'name' => 'ticket_no',
                'required' => true,
                'col' => '4',
                'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()@#"°{}_$%:'
            ),
            array(
                'type' => 'select',
                'label' => $this->l('Ticket Series'),
                'name' => 'series',
                'required' => true,
                'options' => array(
                    'query' => $ticketSeries,
                    'id' => 'ticket_series_name',
                    'name' => 'ticket_series_name'
                ),
                'col' => '4',
                'hint' => array(
                    $this->l('The ticket series of each draw !!.')
                )
            ),
            array(
                'type' => 'select',
                'label' => $this->l('Category'),
                'name' => 'category',
                'required' => true,
                'options' => array(
                    'query' => $prdtCategory,
                    'id' => 'name',
                    'name' => 'name'
                ),
                'col' => '4',
                'hint' => array(
                    $this->l('Product Category.')
                )
            ),

            array(
                'type' => 'date',
                'label' => $this->l('Draw Date:'),
                'name' => 'draw_date',
                'size' => 10,
                'required' => true,
                'desc' => $this->l('The draw date of this series'),
            ),
                array(
                'type' => 'select',
                'label' => $this->l('Nationality'),
                'name' => 'nationality',
                'required' => true,
                'options' => array(
                    'query' => $nationality,
                    'id' => 'name',
                    'name' => 'name'
                ),
                'col' => '4',
                'hint' => array(
                    $this->l('Nationality the winner Belongs .')
                )
            ),

            array(
                'type' => 'textarea',
                'label' => $this->l('Testimonial'),
                'name' => 'testimonial',
                'required' => true,
                'autoload_rte' => true,
                'rows' => 7,
                'cols' => 40,
                'hint' => $this->l('Invalid characters:').' <>;=#{}'
            ), //  add  tag  'autoload_rte' => true, 'lang' => true, --> lang i removed 
               // since the editor value did not submit  editor                  
        );

    if (Tools::getIsset('addkits_winners') ){
            $secondArray = array(
             array(
                'type' => 'hidden',
                'label' => $this->l('Add Date'),
                'name' => 'date_add',                   
                'col' => '4',                   
                'values'=>date("Y-m-d H:i:s"),
                'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()@#"°{}_$%:'
            ),
            array(
                'type' => 'hidden',
                'label' => $this->l('Winner Image Name'),
                'name' => 'winner_image_name',                   
                'col' => '4',                   
                'values'=>"defalt_value"
            )
            );
            $mainArray = array_merge($firstArray,$secondArray); 
         }  

         if (Tools::getIsset('updatekits_winners') ){
            $thirdArray = array(
             array(
                'type' => 'hidden',
                'label' => $this->l('Update Date'),
                'name' => 'date_upd',                   
                'col' => '4',                   
                'values'=>date("Y-m-d H:i:s"),
                'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()@#"°{}_$%:'
            ),
                array(
                'type' => 'text',
                'label' => $this->l('Winner Image Name'),
                'name' => 'winner_image_name',                   
                'col' => '4',                   
                'values'=>"defalt_value"
            ));
            $mainArray = array_merge($firstArray,$thirdArray); 
         }  


    $this->fields_form = array(
        'tinymce' => true,
        'legend' => array(
            'title' => $this->l('Configure your Winner'),
            'icon' => 'icon-user'
        ),          
        'input' => $mainArray
    );
    //Assign value to hidden 
    $this->fields_value['date_add'] = $date = date("Y-m-d H:i:s");
    $this->fields_value['winner_image_name'] ="default_image.jpg";
    $this->fields_form['submit'] = array(
        'title' => $this->l('Save'),
    );
    $date = date("Y-m-d H:i:s");
    $this->addJqueryUI('ui.datepicker');

   return parent::renderForm();
}

 public function postProcess()
 {
   $this->getContent();
    $winner_image_name         = (string) Tools::getValue('winner_image_name');
    // d($winner_image_name);
    parent::postProcess();

} 

i think you should use postProcess instead OR another way is also possible with Init() but below example is for postProcess

public function getContent()
  { 
    $output = null;     

    if( Tools::isSubmit('submitAddkits_winners') )
    {           
         // d("rechaed  here");      
        $winner_image      = $_FILES['winner_image'];
        $ticket_no         = (string) Tools::getValue('ticket_no');
        //d($ticket_no);

        if( $winner_image['name'] != "" )
        {
            //Format allowed i
            $allowed = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png');

            //check allowed formats
            if( in_array($winner_image['type'], $allowed) )
            {
                $path = '../modules/addwinners/';
                $ext = pathinfo($winner_image['name'], PATHINFO_EXTENSION);

               $newfilename = round(microtime(true)) . '_'.$ticket_no;
               $this->fields_value['winner_image_name']=$newfilename.".".$ext;
               $helper->fields_value['winner_image_name'] = "";

                if( ! move_uploaded_file($winner_image['tmp_name'], $path.$newfilename.".".$ext) )
                {
                    $output .= $this->displayError( $path.$stilogo_image['name'] );
                    return $output.$this->displayForm();
                }
            }
            else
            {
                $output .= $this->displayError( $this->l('Image formated Not Supported.') );
                return $output.$this->displayForm();
            }
        }   


        //Se arrivo qui è perchè tutti i campi obbligatori sono stati riempiti quindi aggiorno i valori

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

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

    return $output.$this->html;;
}

Answer No. 2

i think you should use postProcess instead OR another way is also possible with Init() but below example is for postProcess

public function postProcess() 
{ 
    parent::postProcess(); 
    $id = (int)Tools::getValue('id_blahblah'); 
    $file = Tools::fileAttachment('img_any'); 
    if (!empty($file['name'])  && $id > 0) 
    { 
        if (ImageManager::validateUpload($file, Tools::convertBytes(ini_get('upload_max_filesize')))) 
            die('Image size exceeds limit in your PrestaShop settings'); 
        if (!is_dir(_PS_IMG_DIR_.'blah')) 
            @mkdir(_PS_IMG_DIR_.'blah', 0777, true); 
        if (!is_dir(_PS_IMG_DIR_.'blah/'.$id)) 
            @mkdir(_PS_IMG_DIR_.'blah/'.$id, 0777, true); 

        $path = _PS_IMG_DIR_.'blah/'.$id.'/'; 
        $absolute_path = $path.$file['name']; 
        move_uploaded_file($file['tmp_name'], $absolute_path); 
        $imgPath = 'blah/'.$id.'/'.$file['name']; 

        //Save in DB if needed
        Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'blah` 
        SET `img` = "'.pSQL($imgPath).'" 
        WHERE `id` = '.(int)$id); 
    } 
}

Question No. 3

Override and use front controller features in a PrestaShop module [1.6.x.x]

I need to modify and include functions to the PrestaShop Store Locator page. PrestaShop user manual isn't quite clear, and i want to know if it's possible to apply a Controller in a custom module. I want to develop a module that is able to optimizes StoreFrontController and its features without beginning with scratch. Is it achievable? Have you some information for me?

Answer No. 3

You can start by overriding front controller like

`"/modules/mymodule/override/controllers/front/StoresController.php" and in this fine add class "class StoresControllerCore extends FrontController {
public function initContent()
    {
        parent::initContent();
//here do whatever you like
}
}"

though you must know coding to proceed further.

Question No. 4

Valid Oauth redirect URLs?

I am operating a module on PrestaShop to include the login with facebook on my site but i require the Oauth URLs for my facebook app. i've heard that it's facebook that gives you those URLs but exactly where. Can anybody assist me?

Answer No. 4

You just need these urls in App to proceed with facebook logins which will be your "mydomain.com" see image

Question No. 5

PrestaShop Two actions for two conditions for the same cart rule

I'm using PrestaShop 1 .6 .1

A client is inquiring to make a single voucher that makes a discounted rate of 5€ if the cart is having two items and 7€ if it has 3 items (or even more) .

I am beginner to PrestaShop development and I’ve been trying for 2 days without results.

Any specific tricks to follow? , exactly what hook should i utilize? Or maybe i should modify the core files .

Any kind of tip is much appreciated.

Thank you

Answer No. 5

Sadly PrestaShop doesn't have quantity base discount so you must edit core files to achieve this. Edit "/controllers/admin/AdminCartRulesController.php" to add field for quantity and for front edit "/controllers/front/OrderController.php".