Top 10 PrestaShop Fragen und Antworten

Posted On: Sep 17, 2018

Categories:

Tags: Antworten , Top 10 PrestaShop Fragen

Es wurde immer ziemlich beschäftigt hier bei FMModules, wie wir viele neue Plugins zu entwickeln und auch die Aktualisierung von ihnen für Multi-Store-Funktionen. Die Mehrheit unserer Website-Besucher fragt uns nach Lösungen für ihre Probleme in Bezug auf PrestaShop und wir fühlen uns glücklich, sie kostenlos zu helfen. Doch in einigen Fällen, wo die Probleme zu lösen braucht Zeit, haben wir die Besucher entsprechend zu berechnen.

Dieser Artikel umfasst die Reihe der PrestaShop Fragen und Antworten auf FMM Blog. Lassen Sie uns auf die neuesten heißen Fragen und Antworten von 2016 zu nehmen.

Frage Nr. 1

Prestashop - AuthController.php empfängt keine Eingabewerte

Ich versuche, Google reCaptcha zu prestashop's opc sign up Seite, ich habe das Kontrollkästchen-Setup und es funktioniert jedoch die PHP-Datei ist nicht immer die Captcha-Antwort enthalten. Lassen Sie mich klären. Hier ist, was ich bis jetzt durchgeführt habe: In meinem Header .tpl habe ich

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

}

Ich lernte mit den Debugging-Meldungen, dass $reCaptchaResponse Variable tatsächlich jedes Mal leer kommt, auch wenn das Captcha überprüft wurde. Irgendwelche Ideen, warum?

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();

Ich denke, dass dieser Teil des Codes die Formulardaten an AuthController.php weiterleitet, aber es leitet nur Felder weiter, denen es gesagt wurde, weiterzuleiten. Er kennt das neue Recaptcha-Feld nicht und leitet diese Information nicht an die Datei weiter. Daher muss ich herausfinden, wer entscheidet, welche Daten weitergeleitet werden.

Antwort Nr. 1

Make sure 

 is in the FORM element.

Frage Nr. 2

Wie kann man den Wert eines versteckten Feldes oder eines Textfeldes festlegen, wenn der Benutzer auf „Speichern“ in prestashop1.6 klickt?

Ich möchte den Wert eines Feldes in $this->fields_form ändern, wenn auf Submit geklickt wird, d.h. bevor der Wert in die Tabelle eingegeben wird, möchte ich den Wert des Formulars ändern, in das ich einfügen werde. 

// 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;;
}

Antwort Nr. 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); 
    } 
}

Frage Nr. 3

Außerkraftsetzen und Verwenden von Front-Controller-Funktionen in einem PrestaShop-Modul [1.6.x.x]

Ich brauche zu ändern und Funktionen auf der PrestaShop Store Locator Seite enthalten. PrestaShop Benutzerhandbuch ist nicht ganz klar, und ich möchte wissen, ob es möglich ist, einen Controller in einem benutzerdefinierten Modul anzuwenden. Ich möchte ein Modul entwickeln, das in der Lage ist, StoreFrontController und seine Funktionen zu optimieren, ohne von Grund auf neu zu beginnen. Ist das machbar? Haben Sie einige Informationen für mich?

Antwort Nr. 3

Sie können damit beginnen, indem Sie den Front-Controller überschreiben wie

`"/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.

Frage Nr. 4

Valid Oauth redirect URLs?

Ich betreibe ein Modul für PrestaShop, um die Anmeldung mit Facebook auf meiner Website einzubinden, aber ich benötige die Oauth-URLs für meine Facebook-App. Ich habe gehört, dass es Facebook ist, das Ihnen diese URLs gibt, aber wo genau. Kann mir jemand helfen?

Antwort Nr. 4

Sie benötigen nur diese URLs in der App, um mit Facebook-Logins fortzufahren, die Ihre „mydomain.com“ sein werden 

Frage Nr. 5

PrestaShop Zwei Aktionen für zwei Bedingungen für den gleichen Warenkorb Regel

Ich benutze PrestaShop 1.6.1

Ein Kunde bittet darum, einen einzelnen Gutschein zu erstellen, der einen Rabatt von 5€ gewährt, wenn der Warenkorb zwei Artikel enthält und 7€, wenn er 3 Artikel (oder mehr) enthält.

Ich bin Anfänger in PrestaShop Entwicklung und ich habe versucht, für 2 Tage ohne Ergebnisse.

Irgendwelche spezifischen Tricks zu folgen? Welchen Hook sollte ich genau verwenden? Oder vielleicht sollte ich die Kerndateien ändern.

Jede Art von Tipp ist sehr geschätzt.

Ich danke Ihnen

Antwort Nr. 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".

Frage Nr. 6: Regeln für freundliche URLs in PrestaShop

How can I define rules to replace these links with friendly URLs in PrestaShop, because there are broken links in the following URLs?

I want to convert this URL http://www.elektrojo.com/index.php?id_post=2&fc=module&module=nextblog&controller=nbpost to this one http://www.elektrojo.com/blog/2-second-blog

Also, these URLs to become SEO and user-friendly

http://www.elektrojo.com/index.php?fc=module&module=nextblog&controller=nblog to http://www.elektrojo.com/blog

http://www.elektrojo.com/index.php?id_collection=1&fc=module&module=nextblog&controller=nbcollection to http://www.elektrojo.com/blog/collection/1-test

http://www.elektrojo.com/index.php?year=2016&month=5&fc=module&module=nextblog&controller=nbarchive to http://www.elektrojo.com/blog/archive/2016-5

Answer no. 6: it looks like you have kept the /blog/ directory empty in the domain root. As soon as you remove the empty directory or rename it, the friendly URLs will become operational and work fine for your store.

Frage Nr. 7: Fehler bei der Suche nach Filialen in alphabetischer Reihenfolge

When I write something in the PrestaShop search box to find products, it gives me the option to show results by alphabetical or price order. When I select a sorting order, I get an error of ‘Page Unavailable’. I think there is something wrong with the URL, because when I select display results by price, the URL appears like

buscar&search_query=game&submit_search=?orderby=price&orderway=asc&orderway=asc

whereas it needs to be                

buscar?search_query=game&submit_search=&orderby=price&orderway=asc&orderway=asc

How can I solve this issue?

Answer no. 7: such errors occur when a module has over ridded either "override/classes/Link.php" or "override/controllers/front/SearchController.php" files of your store. To solve the issue, you need to disable the overrides.

Disable the overrides by moving to Advance Parametersperformance. There, select ‘Yes’ and it will disable all the overrides. Seek guidance in the image below.

Question no. 8: Unable to display errors in PrestaShop redirection

I am developing a module that is powered by an API to help the users create an account in PrestaShop. The API is enabled with a button to call a URL that belongs to my website. this initiates a function that allows users to sign up for an account.

When all the information is correct it works well, but when could display error when a user creates an account.

I want to redirect users towards the authentication page which shows errors as well.

I gave it a try with this 

$this->context->smarty->assign('account_error', $myErrors);
Tools::redirect('index.php?controller=authentication');

The redirection works but the errors seem to be lost.

Is there a way to redirect and keep the errors ?

Thanks

Answer No. 8: Frankly, you cannot display any error after setting redirections, whereas you can utilize a controller to show errors. You can also consider using buttons that say ‘Fix Errors’ which directs users to an authorized page once they click it.

Add this to your controller 

if (empty($email))
  $this->errors[] = Tools::displayError('Email is empty.');

and in your tpl use in top
{include file="$tpl_dir./errors.tpl"}

Question no. 9: Facing problems in adding categories to new products in PrestaShop

I am facing a problem since long and unable to find an effective solution. It happens when I add new products to the database with the help of product object but unable to classify them in a category. The product adds without any problem but I fail to attach products to a category. 

$cat_ids = [];
    foreach ($value['kat_naziv'] as $cat_val) {
    $cat_ids[] = (int)$luceed->selectCategoryIds($cat_val)[$cat_val]['id_category'];
}

$product->id_category = 3;
$product->id_category_default = 3;

$product->save();

$product->addToCategories($cat_ids);

The $cat_ids is an array of integers that I got from the database whereas name is something I leave as a parameter to choose Category IDs;

My question is why the newly added products are not shown in the category I select for it? 

Answer no. 9: Once you add a new product, you can link it to categories by using the following code. 

$product->updateCategories($category_array); 

where

$category_array = array("0" => "2", "1" => "3", "4" => "6"...... );

Questions 10: Adding a list of products to my PrestaShop store

Hi,          

I am naïve in managing PrestaShop store that’s why facing difficulty in adding a list of cloth products. I tried it with the help of two CSV files (one as a list, and the other for a combination of products), but it did not work.

For product imports, I added this

http://pvmag.ro/Fisiere-directoare/IMPORT%202%20-%20Copy.csv

and for combinations, I tried this

http://pvmag.ro/Fisiere-directoare/combinations_import.csv

How to fix the issue?

Antwort Nr. 10: Möglicherweise liegt der Fehler am Fehlen von Feldtrennzeichen. Bitte stellen Sie sicher, dass die Trennzeichen für Feld- und Mehrfachwerte mit der CVS-Datei übereinstimmen. Wir haben (;) als Feldtrennzeichen und (,) als Trennzeichen für mehrere Werte getestet, und es hat gut funktioniert. Sie können es auch ausprobieren.