Jump to content

Module configuration [Resolved]


Recommended Posts

Hello,

I use Prestashop 1.7.5.2.

In the configuration page of my module, I try to allow the user to enter different values one by one in a defined field and these values are added to a list. In another field the user has access to this list and can delete values from the list. My problem is the display of the list in the defined field to delete items from the list.

I started on an idea to create an array() in the getContent() function, as soon as you validate a value in the field to add it, it adds it to the array: $array[ ]=$new_value. And when we choose a value in the list of the other field we would make an unset($array[$value_a_delete]).

My problem comes in the displayForm() function, for the field of the elements to delete I need a list and I can't get it to display it.

Edited by thomasjrsn (see edit history)
Link to comment
Share on other sites

How about creating an input hidden and reading values from the JavaScript into the input.
It is difficult to advise without codes.

Link to comment
Share on other sites

    public function getContent()
    {
        $output = null;


        if (Tools::isSubmit('submit'.$this->name)) {
            $nouveauchampclient = strval(Tools::getValue('NOUVEAU_CHAMP_CLIENT'));
            $supprchampclient = strval(Tools::getValue('SUPPR_CHAMP_CLIENT'));

            if (
                !Validate::isGenericName($nouveauchampclient)
            ) {
                $output .= $this->displayError($this->l('Invalid Configuration value'));
            } else {
                Configuration::updateValue('NOUVEAU_CHAMP_CLIENT', $nouveauchampclient);
                $output .= $this->displayConfirmation($this->l('Paramètres mis à jour'));
                $sqli = "ALTER TABLE " . _DB_PREFIX_ . "customer "
                        . "ADD ".str_replace(' ', '_', $nouveauchampclient)." VARCHAR(255) NULL";
                Db::getInstance()->execute($sqli);
            }

            if (
                !Validate::isGenericName($supprchampclient)
            ) {
                $output .= $this->displayError($this->l('Invalid Configuration value'));
            } else {
                Configuration::updateValue('SUPPR_CHAMP_CLIENT', $supprchampclient);
                $output .= $this->displayConfirmation($this->l('Paramètres mis à jour'));
                $sqlui = "ALTER TABLE " . _DB_PREFIX_ . "customer "
                        . "DROP ".str_replace(' ', '_', $supprchampclient);
                Db::getInstance()->execute($sqlui);
            }
        }
        return $output.$this->displayForm();
    }

    public function displayForm()
    {
        // Get default language
        $defaultLang = (int)Configuration::get('PS_LANG_DEFAULT');

        // Init Fields form array
        $fieldsForm[0]['form'] = [
            'legend' => [
                'title' => $this->l('Modifier les champs clients'),
            ],
            'input' => array(
                array(
                    'type' => 'text',
                    'label' => $this->l('Nom du nouveau champ client'),
                    'name' => 'NOUVEAU_CHAMP_CLIENT',
                    'size' => 20,
                    'required' => false
                ),
                array(
                  'type' => 'text',
                  'label' => $this->l('Nom du champ client à supprimer'),
                  'name' => 'SUPPR_CHAMP_CLIENT',
                  'size' => 20,
                  'required' => false
                )
            ),
            'submit' => [
                'title' => $this->l('Save'),
                'class' => 'btn btn-default pull-right'
            ]
        ];

        $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 = $defaultLang;
        $helper->allow_employee_form_lang = $defaultLang;

        // Title and toolbar
        $helper->title = $this->displayName;
        $helper->show_toolbar = true;        // false -> remove 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 = [
            'save' => [
                'desc' => $this->l('Save'),
                'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
                '&token='.Tools::getAdminTokenLite('AdminModules'),
            ],
            'back' => [
                'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
                'desc' => $this->l('Back to list')
            ]
        ];

        // Load current value
        $helper->fields_value['NOUVEAU_CHAMP_CLIENT'] = Configuration::get('NOUVEAU_CHAMP_CLIENT');

        return $helper->generateForm($fieldsForm);
    }

Here is the code i use, i don't know how to read values from the JavaScript. Can you show me an example maybe?

Link to comment
Share on other sites

I just want the second input to be a 'type' => 'select'. But i can't get the list $list_field i want to create in getContent().

array(
                  'type' => 'select',
                  'list' => $list_field,
                  'label' => $this->l('Nom du champ client à supprimer'),
                  'name' => 'SUPPR_CHAMP_CLIENT',
                  'size' => 20,
                  'required' => false
                )

 

config.PNG

Link to comment
Share on other sites

Thank you for translating the names into English 🙂
I'm starting to understand.
You want to add new columns 'NOUVEAU_CHAMP_CLIENT' to the ps_customer table and also have a list of columns that have already been created and have the option 'SUPPR_CHAMP_CLIENT'.
When you select multiple items in 'SUPPR_CHAMP_CLIENT', the columns are removed from the ps_customer table, and when the 'SUPPR_CHAMP_CLIENT' field is filled, you want to add a column.
Easier than saving to config, it will be better to create your own table and save, read, delete names in it.

Link to comment
Share on other sites

custom_module.php

<?php
/**
 *  E-APPS.EU - Module for Prestashop 1.6.1 > 1.7
 *  @author    Guest <[email protected]>
 *  @copyright 2019 Guest
 *  @license   https://e-apps.eu/content/6-licencni-podminky-k-modulum
 *  https://e-apps.eu/content/3-obchodni-podminky
 *  https://e-apps.eu/content/2-pravni-ustanoveni
 *  https://e-apps.eu/
 */

class custom_module extends Module {

    private $_html = '';
    private $html_suppr_champ_client = '';

    
        
    public function __construct()
    {
        $this->author = 'Guest';
        $this->author_email = '[email protected]';
        $this->author_website = 'https://e-apps.eu';
        $this->name = 'custom_module';
        $this->tab = 'other';
        $this->version = '1.0.0';
        $this->need_instance = 1;
      

        $this->bootstrap = true;
        parent::__construct();

        $this->displayName = $this->l('Modifier les champs clients');
        $this->description = $this->l('Modul Modifier les champs clients');

        $this->confirmUninstall = $this->l('Uninstall?');
        $this->ps_versions_compliancy = array('min' => '1.7.0', 'max' => '1.7.9.9');
        $this->default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
             
    }



    public function install() 
    {
       
        if (Shop::isFeatureActive())
        {
            Shop::setContext(Shop::CONTEXT_ALL);
        }
        
        if (!parent::install())
        {
            return false;
        }
        
        // create custom table
        $sql_create = 'CREATE TABLE `champ_client` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `champ_column_name` varchar(255) NOT NULL,
                        PRIMARY KEY (`id`)
                        );';
      
        Db::getInstance()->Execute($sql_create);

        return true;
    }
    
    public function uninstall()
    {       
                
        $get_columns = Db::getInstance()->executeS('SELECT * FROM `champ_client`');
        
        // delete all created columns in ps_customer table
        foreach ($get_columns as $col) {
            Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'customer` DROP '.pSQL($col['champ_column_name']));
        }
        
        // delete custom table 
        $sql_drop = 'DROP TABLE `champ_client`';
      
        Db::getInstance()->Execute($sql_drop);
        
        if (Shop::isFeatureActive())
        {
            Shop::setContext(Shop::CONTEXT_ALL);
        }
        
        if (!parent::uninstall())
        {
            return false;
        }
  
        return true;
    }
    
    public function postProcess()
    {
        if (Tools::isSubmit('submit'.$this->name)) {
            
            // create new column
            if (Tools::getValue('NOUVEAU-CHAMP-CLIENT')) {
                // check if column exits
                $column_exists = Db::getInstance()->getValue('SELECT `champ_column_name` FROM `champ_client` WHERE `champ_column_name` = '.pSQL(Tools::getValue('NOUVEAU-CHAMP-CLIENT')));
                
                // if column not exists create
                if (!$column_exists) {
                    // create column name
                    $new_column_name = str_replace('-','_',Tools::str2url(Tools::getValue('NOUVEAU-CHAMP-CLIENT')));
                     // add column to ps_customer table
                    Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'customer` ADD '.pSQL($new_column_name).' VARCHAR(255)');
                    
                    // add new insert to custom table
                    Db::getInstance()->execute('INSERT INTO `champ_client` (`id`, `champ_column_name`) VALUES (NULL, '."'".$new_column_name."'".')');
                }      
            } 
            
            // delete columns if selected
            if (Tools::getValue('SUPPR-CHAMP-CLIENT')) {
                
                // delete selected columns
                foreach (Tools::getValue('SUPPR-CHAMP-CLIENT') as $selected){
                    Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'customer` DROP '.pSQL($selected));
                    Db::getInstance()->execute('DELETE FROM `champ_client` WHERE `champ_column_name` = '."'".$selected."'");
                }
            }
            
            // clear tools data
            Tools::redirectAdmin('index.php?controller=AdminModules&configure=custom_module&token='.Tools::getAdminTokenLite('AdminModules'));
        
            
        }
        

    }


    public function getContent()
    {
        
        $this->html_suppr_champ_client = '<select name="SUPPR-CHAMP-CLIENT[]" class=" fixed-width-xl" id="SUPPR-CHAMP-CLIENT" multiple="multiple" onChange="myFunctionDelete()">';
        
        $cb_list_champ = Db::getInstance()->ExecuteS('SELECT * FROM champ_client ORDER BY id');
        foreach ($cb_list_champ as $cb_champ) {                         
				$this->html_suppr_champ_client .= '<option value="'.$cb_champ['champ_column_name'].'">'.$cb_champ['champ_column_name'].'</option>';
        }                    
                            
                            
        $this->html_suppr_champ_client .= '</select>
                        <input type="hidden" id="SUPPR-CHAMP-CLIEN" name="SUPPR-CHAMP-CLIEN" value="">'; 
                        
                        
        $this->_html .= $this->postProcess();

        $this->_html .= $this->renderForm();
        
        return $this->_html;
    }


    public function renderForm()
    {
        $this->fields_form = array();
        
    
        $fields_form[0] = array(
            'form' => array(
                
                'legend' => array(
                    'title' => $this->l('Modifier les champs clients'),
                    'icon' => 'icon-cogs',
                ),
                'input' => array(
                    
                     array(
                        'type' => 'text',
                        'label' => $this->l('Nom du nouveau champ client'),
                        'name' => 'NOUVEAU-CHAMP-CLIENT',
                        'required' => false,
                        'size' => 20,
                    ),
                    
                     array(
                        'type' => 'html',
                        'id' => 'SUPPR-CHAMP-CLIENT',
                        'label' => $this->l('Nom du champ client a supprimer'),
                        'name' => 'SUPPR-CHAMP-CLIENT',
                        'required' => false,
                        'html_content' => $this->html_suppr_champ_client,
                        'desc' => $this->l('you can select multiple items by holding down the Ctrl key'),
                    ),

                    
                ),
                'submit' => array(
                    'title' => $this->l('Save'),
                    'class' => 'button btn btn-default pull-right',
                )
            ),

        );
            

        $helper = new HelperForm();
        $helper->show_toolbar = true;
        $helper->table =  $this->table;
        $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
        $helper->default_form_language = $lang->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submit'.$this->name;
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
			'fields_value' => $this->getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );

        return $helper->generateForm(array($fields_form[0]));

    }

    public function getConfigFieldsValues()
    {

        $return_array = array();
        
        $return_array['NOUVEAU-CHAMP-CLIENT'] = Tools::getValue('NOUVEAU-CHAMP-CLIENT', '');
                
        return $return_array;
    }
    
}

 

Link to comment
Share on other sites

You also have a demonstration of using the str2url and str_replace functions.
So you can type the name of the new column, including characters and accents.
You can add a new column with one click and delete other columns at the same time.

Link to comment
Share on other sites

That's perfect, thanks a lot! This will help me a lot.

If i understand it correctly, i can acces the different fields created in the table champ_client? But i don't understand what is the purpose of the id.

I'm sorry to take more of your time, i want to be sure how I'm going to retrieve the list of fields in other functions.

Link to comment
Share on other sites

id is like an index. Indexed items are faster. You can also reference the index in other tables.
These are the basics of SQL 😉

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...