Jump to content

Modifier les champs d'inscription depuis un module


Recommended Posts

Bonjour,

Je suis développeur en alternance pour une boite, ils m'ont demandé de rajouter un champ "Comment nous avez vous connu ?" sur la page d'inscription, avec des stats visibles dans le BO.

Ayant très peu d'expérience avec Prestashop en général voici ce que j'ai réalisé :

image.png.4fa05b0b4484c8f02bff9df14903bcad.png

Pour cela j'ai Override la classe Customer ainsi que form/CustomerFormatter pour pouvoir ajouter mon champs et ces sélections possible.

Pour l'affichage des stats dans le BO j'ai fais un module qui affiche ceci :

image.png.44036179b41786ed8a47e7c42a163e3e.png

Avec simplement un Hook('displayAdminStatsModules'); ainsi qu'une fonction hookDisplayAdminStatsModules qui retourne le html souhaité.

Cela fonctionne très bien mais je voudrais améliorer le module afin d'éviter d'override et que simplement en installant le module sur une autre boutique il y est l'ajout du champ automatiquement sur la page d'inscription avec un hook inscription je suppose mais je ne trouve rien de concret sur ça.

Je vous remercie pour votre aide

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

  • 2 weeks later...
  • 2 weeks later...

pour faire ca sans overrider la classe customer j'ai fais un petit module

fichier principal

cafe_customermodifier.php

<?php

if (!defined('_PS_VERSION_')) {
    exit;
}


require_once __DIR__ . '/classes/CustomerModifier.php';

class cafe_customermodifier extends Module
{
    public function __construct()
    {
        $this->name = 'cafe_customermodifier';
        $this->tab = 'administration';
        $this->version = '1.0.0';
        $this->author = 'presta.cafe';
        $this->need_instance = 0;
        $this->bootstrap = true;
        parent::__construct();
        $this->displayName = $this->l('cafe_customermodifier');
        $this->description = $this->l('Allow you to add informations fields for customer');
        $this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
    }

    public function install()
    {
        if (!parent::install()
        || !$this->registerHook([
            'additionalCustomerFormFields',
            'actionObjectCustomerAddAfter',
            'actionObjectCustomerUpdateAfter',

        ])
        || !CustomerModifier::installSql()
        ) {
            return false;
        }
        return true;
    }

    public function uninstall()
    {
        if (
            !parent::uninstall()
            || !CustomerModifier::uninstallSql()
        ) {
            return false;
        }
        return true;
    }

    //front
    public function hookAdditionalCustomerFormFields($params)
    {

        $ifExist = CustomerModifier::getHowYouKnowByIdCustomer($this->context->customer->id);

        if ($ifExist === false) {

            $value = null;
                
        } else {

            $customer_modifier = new CustomerModifier((int)$ifExist);
            $value = $customer_modifier->how_you_know;

        }

        $format = $params['fields'];
        $format['how_you_know'] = (new FormField())
            ->setName('how_you_know')
            ->setType('select')
            ->setAvailableValues(
                [
                    'Instagram' => 'Instagram',
                    'Facebook' => 'Facebook',
                    'LinkedIn' => 'LinkedIn',
                    'Moteur de recherche' => 'Moteur de recherche',
                    'Bouche à oreille' => 'Bouche à oreille',
                    'Parution Presse' => 'Parution Presse',
                    'Mailing' => 'Mailing',
                    'Boutique' => 'Boutique',
                    'Autre' => 'Autre'
                ]
            )
            ->setLabel($this->trans('Comment vous nous avez connu ?', [], 'Modules.cafe_customermodifier'))
            ->setRequired(true)
            ->setValue($value)
            ;
        $params['fields'] = $format;
    }

    public function hookActionObjectCustomerAddAfter(array $params)
    {
        return $this->createCustomerFields($params);
    }
    
    public function hookActionObjectCustomerUpdateAfter(array $params)
    {
        return $this->createCustomerFields($params);
    }

    private function createCustomerFields(array $params) 
    {

        $id_customer = $params['object']->id;

        $ifExist = CustomerModifier::getHowYouKnowByIdCustomer($id_customer);
        
        try {

            $how_you_know = Tools::getValue('how_you_know');

            if ($ifExist === false) {
                
                $customer_modifier = new CustomerModifier();
                $customer_modifier->id_customer= (int)$id_customer;
                $customer_modifier->how_you_know= $how_you_know;
                $customer_modifier->add();

            } else {

                $customer_modifier = new CustomerModifier((int)$ifExist);
                $customer_modifier->id_customer= (int)$id_customer;
                $customer_modifier->how_you_know= $how_you_know;
                $customer_modifier->update();

            }
        
        } catch (ReviewerException $exception) {
            throw new \PrestaShop\PrestaShop\Core\Module\Exception\ModuleErrorException($exception);
        }

    }

 
}

/classes/CustomerModifier.php

<?php

use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;

if (!defined('_PS_VERSION_')) {
    exit;
}

class CustomerModifier extends ObjectModel
{
    public $id_cafe_customermodifier;
    public $id_customer;
    public $how_you_know;
    public $date_add;
    public $date_upd;

    public static $definition = [
        'table' => 'cafe_customermodifier',
        'primary' => 'id_cafe_customermodifier',
        'fields' => [
            'id_cafe_customermodifier' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'length' => 10],
            'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'length' => 10],
            'how_you_know' => ['type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'length' => 50],
            'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
            'date_upd' => ['type' => self::TYPE_DATE,'validate' => 'isDate'],
        ]
    ];

    public static function installSql(): bool
    {
        try {
            $createTable = Db::getInstance()->execute(
                "CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."cafe_customermodifier`(
                `id_cafe_customermodifier` int(10)  NOT NULL AUTO_INCREMENT,
                `id_customer` int(10)  NOT NULL,
                `how_you_know` VARCHAR (255),
                `date_add` datetime NOT NULL,
                `date_upd` datetime NOT NULL,
                PRIMARY KEY (`id_cafe_customermodifier`)
                ) ENGINE=InnoDB DEFAULT CHARSET=UTF8;"
            );
        } catch (PrestaShopException $e) {
            return false;
        }

        return $createTable;
    }

    public static function uninstallSql()
    {
        return Db::getInstance()->execute("DROP TABLE IF EXISTS "._DB_PREFIX_."cafe_customermodifier");
    }

    public static function getHowYouKnowByIdCustomer($id_customer) {

        $sql = new DbQuery();
        $sql->from('cafe_customermodifier', 'cm');
        $sql->where('cm.id_customer = '.(int)$id_customer);
        $query = Db::getInstance()->getValue($sql);

        return $query;

    }
}

 

  • Like 1
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...