Jump to content

añadir campos a formulario de registro en front y back version 1.7.7.1


victorweb

Recommended Posts

- Hola :

He conseguido añadir dos campos al formulario de registro de clientes en el front . Para ello he hecho override en el fichero:

1 - override/classes/form/CustomerFormatter.php 

2 - override/classes/customer.php 

He añadido los campos a la tabla ps_customer y en el front todo funciona correctamente creando/editando. Pero no consigo reflejar estos dos nuevos campos en el back al editar/crear un cliente. He leído que se trataba de hacer  override/controllers/admin/adminCustomerController.php pero en la versión 1.7.7.1 ese controlador ya no esta, esta adminCustomerThreadsController.php y lo he modificado pero no refleja los cambios. 

Alguien sabe por donde seguir el asunto ? 

Link to comment
Share on other sites

 

NOTA:  Lo de negrita es la ruta  y lo cursivo es el archivo

NOTA: Los archivos a modificar son para los datos del BackOffice

 

 

 

====== ARCHIVOS PARA AGREGAR UN NUEVO CLIENTE  ===========

public_html/src/PrestaShopBundle/Form/Admin/Sell/Customer
* CustomerType.php
 ## INPUTS--> la comparte con el formulario de edición


public_html/src/PrestaShopBundle/Resources/views/Admin/Sell/Customer/Blocks
form.html.twig
## LABELS -> la comparte con el formulario de edicion  //


public_html/src/Adapter/Customer/CommandHandler
AddCustomerHandler.php


public_html/src/Core/Domain/Customer/Command
* AddCustomerCommand.php 


public_html/src/Core/Form/IdentifiableObject/DataHandler
* CustomerFormDataHandler.php

        

 

 

 

======== ARCHIVOS PARA EDITAR UN CLIENTE ===================

 

 

public_html/src/PrestaShopBundle/Form/Admin/Sell/Customer

* CustomerType.php

    
public_html/src/PrestaShopBundle/Resources/views/Admin/Sell/Customer/Blocks

* form.html.twig


public_html/src/Adapter/Customer/QueryHandler

* GetCustomerForEditingHandler.php

 
public_html/src/Adapter/Customer/CommandHandler

* EditCustomerHandler.php

 


public_html/src/Core/Domain/Customer/QueryResult

* EditableCustomer.php

 


public_html/src/Core/Domain/Customer/Command

* EditCustomerCommand.php

 

public_html/src/Core/Form/IdentifiableObject/DataHandler

* CustomerFormDataHandler.php

 

public_html/src/Core/Form/IdentifiableObject/DataProvider

* CustomerFormDataProvider.php

 

 

 

=======  vista de datos desde el panel de PRINCIPAL DE CLIENTES  ===================== 


### -----------> (se agregaron las variables y metodos)
 public_html/src/Core/Domain/Customer/QueryResult/PersonalInformation.php

### -----------> (obtiene los valores para la vista)
 public_html/src/Adapter/Customer/QueryHandler/GetCustomerForViewingHandler.php

### -----------> (muestra en info del cliente los datos obtenidos)
 public_html/src/PrestaShopBundle/Resources/views/Admin/Sell/Customer/Blocks/View/personal_information.html.twig

 

PD: ESTO NO ES NECESARIO, SOLAMNETE SI QUIERES MOSTRAR LOS DATOS/CAMPOS QUE AGREGASTE AL PANEL DE CLINTES

518757560_Capturadepantalla(236).thumb.png.d98303efb5435b7f75065945cf1a3ee1.png

 

hace 6 horas, victorweb dijo:

- Hola :

He conseguido añadir dos campos al formulario de registro de clientes en el front . Para ello he hecho override en el fichero:

1 - override/classes/form/CustomerFormatter.php 

2 - override/classes/customer.php 

He añadido los campos a la tabla ps_customer y en el front todo funciona correctamente creando/editando. Pero no consigo reflejar estos dos nuevos campos en el back al editar/crear un cliente. He leído que se trataba de hacer  override/controllers/admin/adminCustomerController.php pero en la versión 1.7.7.1 ese controlador ya no esta, esta adminCustomerThreadsController.php y lo he modificado pero no refleja los cambios. 

Alguien sabe por donde seguir el asunto ? 

Edited by alex222er (see edit history)
  • Thanks 2
Link to comment
Share on other sites

Gracias @alex222er !!, soy nuevo con esto de presta y de los pocos overrides que he hecho nunca han sido de la parte nueva con Symfony o sería directamente en estos ficheros que indicas?? ... tienes algún tutorial o algo para que vaya metiendo mano al asunto? es para no marearte mucho con esto ..

 

Por ejemplo, he intentado mostrar los datos en el panel de cliente (añadi 2 campos zipcode y phonemobile se llaman igual en la tabña ps_customer) : 

1 - public_html/src/Core/Domain/Customer/QueryResult/PersonalInformation.php 

he añadido a la clase :

class PersonalInformation {

/**
* @var string
*/

private $zipcode;

/**
* @var string
*/

private $phonemobile;

    public function __construct(
        $firstName,
        $lastName,
        $zipcode,
        $phonemobile,
        $email,
        $isGuest,
        $socialTitle,
        $birthday,
        $registrationDate,
        $lastUpdateDate,
        $lastVisitDate,
        $rankBySales,
        $shopName,
        $languageName,
        Subscriptions $subscriptions,
        $isActive
    ) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->zipcode = $zipcode;
        $this->phonemobile = $phonemobile;
        $this->email = $email;
        $this->isGuest = $isGuest;
        $this->socialTitle = $socialTitle;
        $this->birthday = $birthday;
        $this->registrationDate = $registrationDate;
        $this->lastUpdateDate = $lastUpdateDate;
        $this->lastVisitDate = $lastVisitDate;
        $this->rankBySales = $rankBySales;
        $this->shopName = $shopName;
        $this->languageName = $languageName;
        $this->subscriptions = $subscriptions;
        $this->isActive = $isActive;
    }

    /**
     * @return string
     */
    public function getzipcode()
    {
        return $this->zipcode;
    }

    /**
     * @return string
     */
    public function getphonemobile()
    {
        return $this->phonemobile;
    }



}

 

2- public_html/src/Adapter/Customer/QueryHandler/GetCustomerForViewingHandler.php

final class GetCustomerForViewingHandler implements GetCustomerForViewingHandlerInterface
{
 private function getPersonalInformation(Customer $customer)
    {
        $customerStats = $customer->getStats();

        $gender = new Gender($customer->id_gender, $this->contextLangId);
        $socialTitle = $gender->name ?: $this->translator->trans('Unknown', [], 'Admin.Orderscustomers.Feature');

        if ($customer->birthday && '0000-00-00' !== $customer->birthday) {
            $birthday = sprintf(
                $this->translator->trans('%1$d years old (birth date: %2$s)', [], 'Admin.Orderscustomers.Feature'),
                $customerStats['age'],
                Tools::displayDate($customer->birthday)
            );
        } else {
            $birthday = $this->translator->trans('Unknown', [], 'Admin.Orderscustomers.Feature');
        }

        $registrationDate = Tools::displayDate($customer->date_add, null, true);
        $lastUpdateDate = Tools::displayDate($customer->date_upd, null, true);
        $lastVisitDate = $customerStats['last_visit'] ?
            Tools::displayDate($customerStats['last_visit'], null, true) :
            $this->translator->trans('Never', [], 'Admin.Global');

        $customerShop = new Shop($customer->id_shop);
        $customerLanguage = new Language($customer->id_lang);

        $customerSubscriptions = new Subscriptions(
            (bool) $customer->newsletter,
            (bool) $customer->optin
        );

        return new PersonalInformation(
            $customer->firstname,
            $customer->lastname,
            $customer->zipcode,
            $customer->phonemobile,
            $customer->email,
            $customer->isGuest(),
            $socialTitle,
            $birthday,
            $registrationDate,
            $lastUpdateDate,
            $lastVisitDate,
            $this->getCustomerRankBySales($customer->id),
            $customerShop->name,
            $customerLanguage->name,
            $customerSubscriptions,
            (bool) $customer->active
        );
    }
}

3 -  public_html/src/PrestaShopBundle/Resources/views/Admin/Sell/Customer/Blocks/View/personal_information.html.twig

<div class="card customer-personal-informations-card">
  <h3 class="card-header">
    <i class="material-icons">person</i>
    {{ customerInformation.personalInformation.firstName }}
    {{ customerInformation.personalInformation.lastName }}
    {{ customerInformation.personalInformation.zipcode }}
    {{ customerInformation.personalInformation.phonemobile }}
    ......

y no he conseguido que se muestre en el panel de control ...

 

panelcontrol.jpg

Edited by victorweb
mas informacion (see edit history)
Link to comment
Share on other sites

hace 8 horas, victorweb dijo:

Gracias @alex222er !!, soy nuevo con esto de presta y de los pocos overrides que he hecho nunca han sido de la parte nueva con Symfony o sería directamente en estos ficheros que indicas?? ... tienes algún tutorial o algo para que vaya metiendo mano al asunto? es para no marearte mucho con esto ..

 

Por ejemplo, he intentado mostrar los datos en el panel de cliente (añadi 2 campos zipcode y phonemobile se llaman igual en la tabña ps_customer) : 

1 - public_html/src/Core/Domain/Customer/QueryResult/PersonalInformation.php 

he añadido a la clase :


class PersonalInformation {

/**
* @var string
*/

private $zipcode;

/**
* @var string
*/

private $phonemobile;

    public function __construct(
        $firstName,
        $lastName,
        $zipcode,
        $phonemobile,
        $email,
        $isGuest,
        $socialTitle,
        $birthday,
        $registrationDate,
        $lastUpdateDate,
        $lastVisitDate,
        $rankBySales,
        $shopName,
        $languageName,
        Subscriptions $subscriptions,
        $isActive
    ) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->zipcode = $zipcode;
        $this->phonemobile = $phonemobile;
        $this->email = $email;
        $this->isGuest = $isGuest;
        $this->socialTitle = $socialTitle;
        $this->birthday = $birthday;
        $this->registrationDate = $registrationDate;
        $this->lastUpdateDate = $lastUpdateDate;
        $this->lastVisitDate = $lastVisitDate;
        $this->rankBySales = $rankBySales;
        $this->shopName = $shopName;
        $this->languageName = $languageName;
        $this->subscriptions = $subscriptions;
        $this->isActive = $isActive;
    }

    /**
     * @return string
     */
    public function getzipcode()
    {
        return $this->zipcode;
    }

    /**
     * @return string
     */
    public function getphonemobile()
    {
        return $this->phonemobile;
    }



}

 

2- public_html/src/Adapter/Customer/QueryHandler/GetCustomerForViewingHandler.php


final class GetCustomerForViewingHandler implements GetCustomerForViewingHandlerInterface
{
 private function getPersonalInformation(Customer $customer)
    {
        $customerStats = $customer->getStats();

        $gender = new Gender($customer->id_gender, $this->contextLangId);
        $socialTitle = $gender->name ?: $this->translator->trans('Unknown', [], 'Admin.Orderscustomers.Feature');

        if ($customer->birthday && '0000-00-00' !== $customer->birthday) {
            $birthday = sprintf(
                $this->translator->trans('%1$d years old (birth date: %2$s)', [], 'Admin.Orderscustomers.Feature'),
                $customerStats['age'],
                Tools::displayDate($customer->birthday)
            );
        } else {
            $birthday = $this->translator->trans('Unknown', [], 'Admin.Orderscustomers.Feature');
        }

        $registrationDate = Tools::displayDate($customer->date_add, null, true);
        $lastUpdateDate = Tools::displayDate($customer->date_upd, null, true);
        $lastVisitDate = $customerStats['last_visit'] ?
            Tools::displayDate($customerStats['last_visit'], null, true) :
            $this->translator->trans('Never', [], 'Admin.Global');

        $customerShop = new Shop($customer->id_shop);
        $customerLanguage = new Language($customer->id_lang);

        $customerSubscriptions = new Subscriptions(
            (bool) $customer->newsletter,
            (bool) $customer->optin
        );

        return new PersonalInformation(
            $customer->firstname,
            $customer->lastname,
            $customer->zipcode,
            $customer->phonemobile,
            $customer->email,
            $customer->isGuest(),
            $socialTitle,
            $birthday,
            $registrationDate,
            $lastUpdateDate,
            $lastVisitDate,
            $this->getCustomerRankBySales($customer->id),
            $customerShop->name,
            $customerLanguage->name,
            $customerSubscriptions,
            (bool) $customer->active
        );
    }
}

3 -  public_html/src/PrestaShopBundle/Resources/views/Admin/Sell/Customer/Blocks/View/personal_information.html.twig


<div class="card customer-personal-informations-card">
  <h3 class="card-header">
    <i class="material-icons">person</i>
    {{ customerInformation.personalInformation.firstName }}
    {{ customerInformation.personalInformation.lastName }}
    {{ customerInformation.personalInformation.zipcode }}
    {{ customerInformation.personalInformation.phonemobile }}
    ......

y no he conseguido que se muestre en el panel de control ...

 

panelcontrol.jpg

Debido a las prisas que tenía y a la falta de conocimiento de overrides y siguiendo el hilo de Victor Rodenas https://victor-rodenas.com/anadir-campos-en-el-formulario-de-registro-en-prestashop-1-7/ No hice uso de overrides en estos archivos modificados (solamente de controladores y clases)

 

 

Link to comment
Share on other sites

============== vista de datos desde el panel de Clientes  =========================== 

 


### Se agregaron las variables y métodos...
 public_html/src/Core/Domain/Customer/QueryResult/PersonalInformation.php

##Declaras variable
private $copy_phone;

##Añades dentro del constructor (si tu variable es la ultima va sin , (coma) )
public function __construct(
  $copy_phone,
    ){
  ##Devuelves en las llaves posteriores al constructor
  $this->copy_phone =  $copy_phone;
  }

  ##funcion que retorna el valor de la variable
public function copy_phone() {
  return $this->copy_phone;
   }

## obtiene los valores para la vista....
 public_html/src/Adapter/Customer/QueryHandler/GetCustomerForViewingHandler.php


##Donde devuelve la info. Añades el campo que deseas (si es el ultimo dato va sin la , (coma) )
 return new PersonalInformation( 
    $customer->copy_phone,
    );


## muestra en info del cliente los datos obtenidos...
 public_html/src/PrestaShopBundle/Resources/views/Admin/Sell/Customer/Blocks/View/personal_information.html.twig

##Añades el campo que deseas
    <div class="row mb-1">
      <div class="col-4 text-right">  {{ 'Teléfono'|trans({}, 'Admin.Global') }}  </div>
      <div class="col-8 customer-last-visit-date">  {{ customerInformation.personalInformation.copy_phone}}   </div>
    </div>
    

 

PD: En mi caso para evitar errores maneje en todos los archivos y base de datos el mismo nombre de variable   copy_phone  (en micaso)

Edited by alex222er (see edit history)
  • Thanks 1
Link to comment
Share on other sites

hace 7 horas, victorweb dijo:

@alex222er gracias!! Con el último post he conseguido mostrarlo en Ver Cliente de control panel ... Sigo sin conseguir mostrar los campos en el listado de clientes ni para modificar/editar cliente 

========================    CLIENTES PANEL PRINCIPAL=====================================
 
##--->  (se añanden los encabezados de FILTROS/BUSQUEDAS)

public_html/src/Core/Grid/Definition/Factory/CustomerGridDefinitionFactory.php

    protected function getColumns(){
       ->add(
                (new DataColumn('copy_phone'))
                ->setName($this->trans('Tel.', [], 'Admin.Global'))
                ->setOptions(['field' => 'copy_phone',]))
          
        ### ... otros campos
      }

##--->  (se establecen los parametros de datos/campos de FILTROS/BUSQUEDAS)
public_html/src/Core/Grid/Query/CustomerQueryBuilder.php

------- funcion --------------   
 public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria) {
        $searchQueryBuilder = $this->getCustomerQueryBuilder($searchCriteria)
            ->select('c.copy_ncliente, #... otros campos ')
            ->addSelect('c.date_add, gl.name as social_title, s.name as shop_name, c.company');

      ##... más codigo
    }


------- otra funcion --------------
  private function applyFilters(array $filters, QueryBuilder $qb) {
        $allowedFilters = [
            'copy_phone',
            ##otros campos..
        ];


------- otra funcion --------------

    private function applySorting(QueryBuilder $searchQueryBuilder, SearchCriteriaInterface $searchCriteria) {
        switch ($searchCriteria->getOrderBy()) { 
            case 'copy_ncliente':
            ## otros campos ...
            $orderBy = 'c.' . $searchCriteria->getOrderBy();

           ##más codigo...
        }

##--->  (se establecen los parametros de datos/campos de EXPORTACION DE DATOS CLIENTES)
public_html/src/PrestaShopBundle/Controller/Admin/Sell/Customer/CustomerController.php
 

 -------- funcion ----------   
public function exportAction(CustomerFilters $filters)
    {
        $filters = new CustomerFilters(['limit' => null] + $filters->all());
        $gridFactory = $this->get('prestashop.core.grid.factory.customer');
        $grid = $gridFactory->getGrid($filters);

        $headers = [ 
            'copy_ncliente' => $this->trans('#Cliente', 'Admin.Global'),
            ## otros campos ....
             ];

        $data = [];

        foreach ($grid->getData()->getRecords()->all() as $record) {

            $data[] = [ 
                'copy_phone' => $record['copy_phone'],
                 ## ottos campos ...
                ];
            }
        ## más codigo 

      }

NOTA:  las modificaciones son en cada método o función, de igual manera utilicé el mismo nombre de variable copy_phone

  • Thanks 1
Link to comment
Share on other sites

hace 1 hora, victorweb dijo:

@alex222er muchas gracias!! va perfecto!! hasta la exportación de los clientes!! conseguido ver/crear/modificar!!!

Me alegra ayudarte, con lo de la modificación y creación de clientes te puedo ayudar más tarde si aún te sirve..

 

Link to comment
Share on other sites

  • 3 weeks later...
  • 1 year later...

Buenos días, todo esto esta hecho sin overrides, no creo que sea la forma correcta de hacerlo... A parte tocáis directamente el Core de prestashop. No hay ninguna otra forma de realizarlo?

El tutorial de Víctor rodenas esta bien pero llega un momento que no puedes seguir y es en la parte de administración ya que los archivos de los que habla ya no existen, sabéis otra solución?

 

Un saludo y gracias.

Link to comment
Share on other sites

  • 9 months later...
On 5/27/2022 at 3:58 AM, david19942 said:

Buenos días, todo esto esta hecho sin overrides, no creo que sea la forma correcta de hacerlo... A parte tocáis directamente el Core de prestashop. No hay ninguna otra forma de realizarlo?

El tutorial de Víctor rodenas esta bien pero llega un momento que no puedes seguir y es en la parte de administración ya que los archivos de los que habla ya no existen, sabéis otra solución?

 

Un saludo y gracias.

Precisamente hice este proceso usando overrides y ayudado obivamente por este post. Aquí les dejo mi versión con los overrides usados (este es u n proyecto aparte solo reemplacen los campos )

override\classes\Customer.php

Aquí solo agreguen los campos nuevos, no hace falta re insertar toda la clase original. El coreException y el Service locator son indispensables. No los remuevan.

<?php
/**
 * Copyright since 2007 PrestaShop SA and Contributors
 * PrestaShop is an International Registered Trademark & Property of PrestaShop SA
 *
 */
use PrestaShop\PrestaShop\Adapter\CoreException;
use PrestaShop\PrestaShop\Adapter\ServiceLocator;

/***
 * Class CustomerCore
 */
class Customer extends CustomerCore
{
    public $retail;
    public $addressC;
    public $cityC;
    public $stateC;
    public $countryC; 
    public $zipC;
    public $phoneC;
    public $mobileC;
    public $aboutus;
    public $extrainfo;

   

    /**
     * @see ObjectModel::$definition
     */
    public static $definition = [
        'table' => 'customer',
        'primary' => 'id_customer',
        'fields' => [
            'secure_key' => ['type' => self::TYPE_STRING, 'validate' => 'isMd5', 'copy_post' => false],
            'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 255],
            'firstname' => ['type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 255],
            'email' => ['type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true, 'size' => 255],
            'passwd' => ['type' => self::TYPE_STRING, 'validate' => 'isPasswd', 'required' => true, 'size' => 255],
            'last_passwd_gen' => ['type' => self::TYPE_STRING, 'copy_post' => false],
            'id_gender' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
            'birthday' => ['type' => self::TYPE_DATE, 'validate' => 'isBirthDate'],
            'newsletter' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'newsletter_date_add' => ['type' => self::TYPE_DATE, 'copy_post' => false],
            'ip_registration_newsletter' => ['type' => self::TYPE_STRING, 'copy_post' => false],
            'optin' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'website' => ['type' => self::TYPE_STRING, 'validate' => 'isUrl'],
            'company' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName'],
            //Campos nuevos
            'retail' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
            'addressC' => array('type' => self::TYPE_STRING,),
            'aboutus' => array('type' => self::TYPE_STRING,),
            'extrainfo' => array('type' => self::TYPE_STRING,),
            'stateC' => array('type' => self::TYPE_STRING,),
            'countryC' => array('type' => self::TYPE_STRING,),
            'zipC' => array('type' => self::TYPE_STRING,),
            'cityC' => array('type' => self::TYPE_STRING,),
            'phoneC' => array('type' => self::TYPE_STRING,),
            'mobileC' => array('type' => self::TYPE_STRING,),
            //End Campos nuevos
            'siret' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName'],
            'ape' => ['type' => self::TYPE_STRING, 'validate' => 'isApe'],
            'outstanding_allow_amount' => ['type' => self::TYPE_FLOAT, 'validate' => 'isFloat', 'copy_post' => false],
            'show_public_prices' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool', 'copy_post' => false],
            'id_risk' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'copy_post' => false],
            'max_payment_days' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'copy_post' => false],
            'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool', 'copy_post' => false],
            'deleted' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool', 'copy_post' => false],
            'note' => ['type' => self::TYPE_HTML, 'size' => 65000, 'copy_post' => false],
            'is_guest' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool', 'copy_post' => false],
            'id_shop' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'copy_post' => false],
            'id_shop_group' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'copy_post' => false],
            'id_default_group' => ['type' => self::TYPE_INT, 'copy_post' => false],
            'id_lang' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'copy_post' => false],
            'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false],
            'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false],
            'reset_password_token' => ['type' => self::TYPE_STRING, 'validate' => 'isSha1', 'size' => 40, 'copy_post' => false],
            'reset_password_validity' => ['type' => self::TYPE_DATE, 'validate' => 'isDateOrNull', 'copy_post' => false],
        ],
    ];  
}

 

classes\form\CustomerPersister.php

<?php
/**
 * Copyright since 2007 PrestaShop SA and Contributors
 * 
 */
use PrestaShop\PrestaShop\Core\Crypto\Hashing as Crypto;
use Symfony\Component\Translation\TranslatorInterface;
class CustomerPersister extends CustomerPersisterCore
{   
    private $errors = [];
    private $context;
    private $crypto;
    private $translator;
    private $guest_allowed;

    public function __construct(
        Context $context,
        Crypto $crypto,
        TranslatorInterface $translator,
        $guest_allowed
    ) {
        $this->context = $context;
        $this->crypto = $crypto;
        $this->translator = $translator;
        $this->guest_allowed = $guest_allowed;
    }
    

    public function getErrors()
    {
        return $this->errors;
    }

    public function save(Customer $customer, $clearTextPassword, $newPassword = '', $passwordRequired = true)
    {
        if ($customer->id) {
            return $this->update($customer, $clearTextPassword, $newPassword, $passwordRequired);
        }

        return $this->create($customer, $clearTextPassword);
    }

    private function update(Customer $customer, $clearTextPassword, $newPassword, $passwordRequired = true)
    {
        if (!$customer->is_guest && $passwordRequired && !$this->crypto->checkHash(
            $clearTextPassword,
            $customer->passwd,
            _COOKIE_KEY_
        )) {
            $msg = $this->translator->trans(
                'Invalid email/password combination',
                [],
                'Shop.Notifications.Error'
            );
            $this->errors['email'][] = $msg;
            $this->errors['password'][] = $msg;

            return false;
        }

        if (!$customer->is_guest) {
            $customer->passwd = $this->crypto->hash(
                $newPassword ? $newPassword : $clearTextPassword,
                _COOKIE_KEY_
            );
        }

        if ($customer->is_guest || !$passwordRequired) {
            // TODO SECURITY: Audit requested
            if ($customer->id != $this->context->customer->id) {
                // Since we're updating a customer without
                // checking the password, we need to check that
                // the customer being updated is the one from the
                // current session.

                // The error message is not great,
                // but it should only be displayed to hackers
                // so it should not be an issue :)

                $this->errors['email'][] = $this->translator->trans(
                    'There seems to be an issue with your account, please contact support',
                    [],
                    'Shop.Notifications.Error'
                );

                return false;
            }
        }

        $guest_to_customer = false;

        if ($clearTextPassword && $customer->is_guest) {
            $guest_to_customer = true;
            $customer->is_guest = false;
            $customer->passwd = $this->crypto->hash(
                $clearTextPassword,
                _COOKIE_KEY_
            );
        }

        if ($customer->is_guest || $guest_to_customer) {
            // guest cannot update their email to that of an existing real customer
            if (Customer::customerExists($customer->email, false, true)) {
                $this->errors['email'][] = $this->translator->trans(
                    'An account was already registered with this email address',
                    [],
                    'Shop.Notifications.Error'
                );

                return false;
            }
        }

        if ($customer->email != $this->context->customer->email) {
            $customer->removeResetPasswordToken();
        }

        $ok = $customer->save();

        if ($ok) {
            $this->context->updateCustomer($customer);
            $this->context->cart->update();
            Hook::exec('actionCustomerAccountUpdate', [
                'customer' => $customer,
            ]);
            if ($guest_to_customer) {
                $this->sendConfirmationMail($customer);
                $this->sendConfirmationAdminMail($customer);
            }
        }

        return $ok;
    }

    private function create(Customer $customer, $clearTextPassword)
    {
        if (!$clearTextPassword) {
            if (!$this->guest_allowed) {
                $this->errors['password'][] = $this->translator->trans(
                    'Password is required',
                    [],
                    'Shop.Notifications.Error'
                );

                return false;
            }

            /**
             * Warning: this is only safe provided
             * that guests cannot log in even with the generated
             * password. That's the case at least at the time of writing.
             */
            $clearTextPassword = $this->crypto->hash(
                microtime(),
                _COOKIE_KEY_
            );

            $customer->is_guest = true;
        }

        $customer->passwd = $this->crypto->hash(
            $clearTextPassword,
            _COOKIE_KEY_
        );

        if (Customer::customerExists($customer->email, false, true)) {
            $this->errors['email'][] = $this->translator->trans(
                'An account was already registered with this email address',
                [],
                'Shop.Notifications.Error'
            );

            return false;
        }

        $ok = $customer->save();

        if ($ok) {
            $this->context->updateCustomer($customer);
            $this->context->cart->update();
            $this->sendConfirmationMail($customer);
            Hook::exec('actionCustomerAccountAdd', [
                'newCustomer' => $customer,
            ]);
        }

        return $ok;
    }

    private function sendConfirmationMail(Customer $customer)
    {
        if ($customer->is_guest || !Configuration::get('PS_CUSTOMER_CREATION_EMAIL')) {
            return true;
        }

        return Mail::Send(
            $this->context->language->id,
            'account',
            $this->translator->trans(
                'Welcome!',
                [],
                'Emails.Subject'
            ),
            [
                '{firstname}' => $customer->firstname,
                '{lastname}' => $customer->lastname,
                '{email}' => $customer->email,
            ],
            $customer->email,
            $customer->firstname . ' ' . $customer->lastname
        );
    }
    private function sendConfirmationAdminMail(Customer $customer)
    {
        if ($customer->is_guest || !Configuration::get('PS_CUSTOMER_CREATION_EMAIL')) {
            return true;
        }

        return Mail::Send(
            $this->context->language->id,
            'account_for_admin',
            $this->translator->trans(
                'New Client!',
                array(),
                'Emails.Subject'
            ),
            array(
                '{firstname}' => $customer->firstname,
                '{lastname}' => $customer->lastname,
                '{type}' => $customer->retail,
                '{email}' => $customer->email,
                '{company}' => $customer->company,
                '{website}' => $customer->website,
                '{phone}' => $customer->phoneC,
                '{mobil}' => $customer->mobileC,
                '{address}' => $customer->addressC,
                '{zip}' => $customer->zipC, 
                '{city}' => $customer->cityC,
                '{state}' => $customer->stateC,
                '{country}' => $customer->countryC,
                '{about}' => $customer->aboutus,   
                '{extrainfo}' => $customer->extrainfo

            ),
            '[email protected]',
            Configuration::get('PS_SHOP_NAME')
        );
    }
}

 

override\classes\form\CustomerFormatter.php

Desafortunadamente tuvo un problema con las traducciones en este sitio que no me permitia entrar directo a traducir los textos, Y tuve que hacer adaptaciones por las prisas, pero se puede entender la idea en este override.

<?php
/**
 * @Override CustomerFormatter
 */
 
use Symfony\Component\Translation\TranslatorInterface;

class CustomerFormatter extends CustomerFormatterCore
{
    private $translator;
    private $language;

    private $ask_for_birthdate = true;
    private $ask_for_partner_optin = true;
    private $partner_optin_is_required = true;
    private $ask_for_password = true;
    private $password_is_required = true;
    private $ask_for_new_password = false;

    public function __construct(
        TranslatorInterface $translator,
        Language $language
    ) {
        $this->translator = $translator;
        $this->language = $language;
    }

    public function setAskForBirthdate($ask_for_birthdate)
    {
        $this->ask_for_birthdate = $ask_for_birthdate;

        return $this;
    }

    public function setAskForPartnerOptin($ask_for_partner_optin)
    {
        $this->ask_for_partner_optin = $ask_for_partner_optin;

        return $this;
    }

    public function setPartnerOptinRequired($partner_optin_is_required)
    {
        $this->partner_optin_is_required = $partner_optin_is_required;

        return $this;
    }

    public function setAskForPassword($ask_for_password)
    {
        $this->ask_for_password = $ask_for_password;

        return $this;
    }

    public function setAskForNewPassword($ask_for_new_password)
    {
        $this->ask_for_new_password = $ask_for_new_password;

        return $this;
    }

    public function setPasswordRequired($password_is_required)
    {
        $this->password_is_required = $password_is_required;

        return $this;
    }

    public function getFormat()
    {
        $format = [];

        $genders = Gender::getGenders($this->language->id);
        if ($genders->count() > 0) {
            $genderField = (new FormField())
                ->setName('id_gender')
                ->setType('radio-buttons')
                ->setLabel(
                    $this->translator->trans(
                        'Social title',
                        [],
                        'Shop.Forms.Labels'
                    )
                );
            foreach ($genders as $gender) {
                $genderField->addAvailableValue($gender->id, $gender->name);
            }
            $format[$genderField->getName()] = $genderField;
        }

        $format['firstname'] = (new FormField())
            ->setName('firstname')
            ->setLabel(
                $this->translator->trans(
                    'First name',
                    [],
                    'Shop.Forms.Labels'
                )
            )
            ->setRequired(true)
            ->addAvailableValue(
                'comment',
                $this->translator->trans('Only letters and the dot (.) character, followed by a space, are allowed.', [], 'Shop.Forms.Help')
            );

        $format['lastname'] = (new FormField())
            ->setName('lastname')
            ->setLabel(
                $this->translator->trans(
                    'Last name',
                    [],
                    'Shop.Forms.Labels'
                )
            )
            ->setRequired(true)
            ->addAvailableValue(
                'comment',
                $this->translator->trans('Only letters and the dot (.) character, followed by a space, are allowed.', [], 'Shop.Forms.Help')
            );

        if (Configuration::get('PS_B2B_ENABLE')) {
            $format['company'] = (new FormField())
                ->setName('company')
                ->setType('text')
                ->setLabel($this->translator->trans(
                    'Company',
                    [],
                    'Shop.Forms.Labels'
                ));
            $format['siret'] = (new FormField())
                ->setName('siret')
                ->setType('text')
                ->setLabel($this->translator->trans(
                    // Please localize this string with the applicable registration number type in your country. For example : "SIRET" in France and "Código fiscal" in Spain.
                    'Identification number',
                    [],
                    'Shop.Forms.Labels'
                ));
        }

        $format['email'] = (new FormField())
            ->setName('email')
            ->setType('email')
            ->setLabel(
                $this->translator->trans(
                    'Email',
                    [],
                    'Shop.Forms.Labels'
                )
            )
            ->setRequired(true);

        if ($this->ask_for_password) {
            $format['password'] = (new FormField())
                ->setName('password')
                ->setType('password')
                ->setLabel(
                    $this->translator->trans(
                        'Password',
                        [],
                        'Shop.Forms.Labels'
                    )
                )
                ->setRequired($this->password_is_required);
        }

        if ($this->ask_for_new_password) {
            $format['new_password'] = (new FormField())
                ->setName('new_password')
                ->setType('password')
                ->setLabel(
                    $this->translator->trans(
                        'New password',
                        [],
                        'Shop.Forms.Labels'
                    )
                );
        }

        
            //////////////////////////////////////////////            
            //Adding extrafields
            //////////////////////////////////////////////
                            //Translations (the native translations does not work well anymore, use this instead.)
                            if ($this->language->id == 1){//EN
                                $Op_TypeC =     ["I'm residential customer",
                                                "I'm a residential builder or contractor",
                                                "I'm an architect or designer",
                                                "I'm a commercial general contractor",
                                                "Other"];
                                $Op_Company =   'Company';
                                $Op_State =     'State / Province';
                                $Op_Zip =       'Zip / Postal Code';
                                $Op_How =       'How did you hear about us?';
                                $Op_mobileC =   'Cell Phone';
                                $Op_website =   'Website';
                                $Op_HowOP =     ["Online Search","Online Ads","Print Ads","Word of mouth","i'm already a client","Other"];
                                $Op_ExtraIn =   'Additional Information';
                            
                            }
                            if ($this->language->id == 2){//FR
                                $Op_TypeC =     ['Je suis un client résidentiel',
                                                'Je suis un constructeur résidentiel ou un entrepreneur',
                                                'Je suis architecte ou designer',
                                                'Je suis un entrepreneur général commercial',
                                                'Autre'];
                                $Op_Company =   'Entreprise';
                                $Op_State =     'Province';
                                $Op_Zip =       'Code postal';
                                $Op_How =       'Comment avez-vous entendu parler de nous?';
                                $Op_mobileC =   'Cellulaire';
                                $Op_website =   'Site Web';
                                $Op_HowOP =     ["Recherche en ligne","Annonces en ligne","Annonces imprimées (magazines, journaux, etc.)","Bouche à oreille","Je suis déjà client","Autre"];
                                $Op_ExtraIn =   'Information additionnelle';
                            }
                $format['retail'] = (new FormField)
                    ->setName('retail')
                    ->setType('select') 
                    ->setLabel(
                        $this->translator->trans(
                            'Client type', [], 'Shop.Forms.MM'
                        )
                    )               
                    ->addAvailableValue('Residential customer', $Op_TypeC[0])        
                    ->addAvailableValue('Residential builder', $Op_TypeC[1])
                    ->addAvailableValue('Architect', $Op_TypeC[2])
                    ->addAvailableValue('General contractor', $Op_TypeC[3])
                    ->addAvailableValue('other', $Op_TypeC[4])
                    ->setRequired(true)
                ;
            
                $format['company'] = (new FormField)
                ->setName('company')
                ->setLabel(
                    $this->translator->trans(
                        $Op_Company, [], 'Shop.Forms.Labels'
                    )
                )
                ->setRequired(false)
                ;
                $format['addressC'] = (new FormField)
                    ->setName('addressC')
                    ->setLabel(
                        $this->translator->trans(
                            'Address', [], 'Shop.Forms.Labels'
                        )
                    )
                    ->setRequired(true)
                ;
                $format['cityC'] = (new FormField)
                    ->setName('cityC')
                    ->setLabel(
                        $this->translator->trans(
                            'City', [], 'Shop.Forms.Labels'
                        )
                    )
                    ->setRequired(true)
                ;
                $format['countryC'] = (new FormField)
                    ->setName('countryC')
                    ->setType('countrySelect')
                    ->setLabel(
                        $this->translator->trans(
                            'Country', [], 'Shop.Forms.Labels'
                        )
                    )
                    ->addAvailableValue('Canada', $this->translator->trans(
                        'Canada', [], 'Shop.Forms.Labels'
                    ))
                    ->addAvailableValue('United States', $this->translator->trans(
                        'United States', [], 'Shop.Forms.Labels'
                    ))
                    
                    ->setRequired(true)
                ;
                $format['stateC'] = (new FormField)
                    ->setName('stateC')
                    ->setLabel(
                        $this->translator->trans(
                            $Op_State,[],'Shop.Forms.Labels'
                        )
                    )
                    ->setRequired(true)
                ;
                $format['zipC'] = (new FormField)
                    ->setName('zipC')
                    ->setLabel(
                        $this->translator->trans(
                            $Op_Zip,[],'Shop.Forms.Labels'
                        )
                    )
                    ->setRequired(true)
                ;
                $format['phoneC'] = (new FormField)
                    ->setName('phoneC')
                    ->setType('text')
                    ->setLabel(
                        $this->translator->trans(
                            'Phone', [], 'Shop.Forms.Labels'
                        )
                    )
                    ->setRequired(true)
                ;
                $format['mobileC'] = (new FormField)
                    ->setName('mobileC')
                    ->setType('text')
                    ->setLabel($Op_mobileC)
                    ->setRequired(false)
                ;
                $format['website'] = (new FormField)
                    ->setName('website')
                    ->setType("UrlType")
                    ->setLabel($Op_website)
                    ->setRequired(false)
                ;
                $format['aboutus'] = (new FormField)
                    ->setName('aboutus')
                    ->setType('select')
                    ->setLabel($Op_How)                    
                    ->addAvailableValue('Online Search',$Op_HowOP[0])
                    ->addAvailableValue('Online Ads',$Op_HowOP[1])
                    ->addAvailableValue('Print Ads',$Op_HowOP[2])
                    ->addAvailableValue('Word of mouth',$Op_HowOP[3])
                    ->addAvailableValue("i'm already a client",$Op_HowOP[4])
                    ->addAvailableValue("Other",$Op_HowOP[5])
                    ->setRequired(true)
                ;
                $format['extrainfo'] = (new FormField)
                    ->setName('extrainfo')
                    ->setType('textarea')
                    ->setLabel($Op_ExtraIn)
                    ->setRequired(false)
                ;



            ////////////////////////////////////////////////////////
            //End
            ////////////////////////////////////////////////////////
        

        if ($this->ask_for_birthdate) {
            $format['birthday'] = (new FormField())
                ->setName('birthday')
                ->setType('text')
                ->setLabel(
                    $this->translator->trans(
                        'Birthdate',
                        [],
                        'Shop.Forms.Labels'
                    )
                )
                ->addAvailableValue('placeholder', Tools::getDateFormat())
                ->addAvailableValue(
                    'comment',
                    $this->translator->trans('(E.g.: %date_format%)', ['%date_format%' => Tools::formatDateStr('31 May 1970')], 'Shop.Forms.Help')
                );
        }

        if ($this->ask_for_partner_optin) {
            $format['optin'] = (new FormField())
                ->setName('optin')
                ->setType('checkbox')
                ->setLabel(
                    $this->translator->trans(
                        'Receive offers from our partners',
                        [],
                        'Shop.Theme.Customeraccount'
                    )
                )
                ->setRequired($this->partner_optin_is_required);
        }

        // ToDo, replace the hook exec with HookFinder when the associated PR will be merged
        $additionalCustomerFormFields = Hook::exec('additionalCustomerFormFields', ['fields' => &$format], null, true);

        if (is_array($additionalCustomerFormFields)) {
            foreach ($additionalCustomerFormFields as $moduleName => $additionnalFormFields) {
                if (!is_array($additionnalFormFields)) {
                    continue;
                }

                foreach ($additionnalFormFields as $formField) {
                    $formField->moduleName = $moduleName;
                    $format[$moduleName . '_' . $formField->getName()] = $formField;
                }
            }
        }

        // TODO: TVA etc.?

        return $this->addConstraints($format);
    }

    private function addConstraints(array $format)
    {
        $constraints = Customer::$definition['fields'];

        foreach ($format as $field) {
            if (!empty($constraints[$field->getName()]['validate'])) {
                $field->addConstraint(
                    $constraints[$field->getName()]['validate']
                );
            }
        }

        return $format;
    }
}

Por ultimo resaltar que si no encuentras archivos  como por ememplo "personal_information.html.twig" Es porque estas usando un PS inferior donde todavia se usa Smarty en el backend. Espero haber ayudado. Saludos!!!

 

 

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...