Código Caótico

How I Added a Custom CPF Field to PrestaShop's Customer Form (Step-by-Step Tutorial)

How I Added a Custom CPF Field to PrestaShop's Customer Form (Step-by-Step Tutorial)

How to Add a Custom CPF Field to PrestaShop’s Customer Form

Looking to add custom fields to your PrestaShop store? In this tutorial, I’ll show you step-by-step how I added a CPF field to the customer registration form of my PrestaShop e-commerce platform. CPF (Cadastro de Pessoas Físicas) is essential for Brazilian customers, so extending the default functionality of PrestaShop was a must.

I’ll walk you through the entire process, including:

  • Adding a new CPF field to the database
  • Creating a custom module
  • Overriding the Customer class
  • Modifying the customer-form.tpl template
  • Ensuring proper validation and formatting

Let’s dive in!

Step 1: Adding the CPF Field to the Database

The first step was to modify the ps_customer table in the PrestaShop database to store CPF numbers. I used phpMyAdmin for this. Here’s the SQL command:


ALTER TABLE ps_customer 
ADD cpf VARCHAR(14) NULL;

This command creates a new column called cpf that can store 14-character values, accommodating CPF numbers properly.

Step 2: Creating the Custom Module to Inject the CPF Field

To dynamically inject the CPF field into the customer form, I built a custom module named AddCpf. Below is the code I used:


<?php
if (!defined('_PS_VERSION_')) {
    exit;
}

class AddCpf extends Module {
    public function __construct() {
        $this->name = 'addcpf';
        $this->tab = 'administration';
        $this->version = '1.0.0';
        $this->author = 'Joao Buschinelli';
        parent::__construct();
        $this->displayName = $this->l('Add CPF Field');
    }

    public function install() {
        return parent::install() && $this->registerHook('additionalCustomerFormFields');
    }

    public function hookAdditionalCustomerFormFields(array $params) {
        $params['fields']['cpf'] = (new FormField())
            ->setName('cpf')
            ->setType('text')
            ->setLabel($this->trans('CPF'))
            ->setRequired(true);
    }
}

This module hooks into the form using the additionalCustomerFormFields hook, injecting the CPF field dynamically. Logging ensures that any issues during the hook execution are easily detected.

Step 3: Extending the Customer Class with an Override

I overrode the Customer class to include the CPF field as part of the customer’s data structure:


<?php
class Customer extends CustomerCore {
    /** @var string CPF field */
    public $cpf;

    public static $definition = [
        'table' => 'customer',
        'primary' => 'id_customer',
        'fields' => [
            'cpf' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isGenericName',
            ],
        ],
    ];
}

This override ensures that PrestaShop can handle the new CPF field seamlessly.

Step 4: Modifying the Template to Format CPF Input

I also updated the customer-form.tpl template to ensure the CPF input follows the correct Brazilian format:


document.addEventListener('DOMContentLoaded', () => {
    const cpfInput = document.querySelector('input[name="cpf"]');
    cpfInput.addEventListener('input', (e) => {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length > 3 && value.length <= 6) {
            value = value.slice(0, 3) + '.' + value.slice(3);
        } else if (value.length > 6 && value.length <= 9) {
            value = value.slice(0, 3) + '.' + value.slice(3, 6) + '.' + value.slice(6);
        } else if (value.length > 9) {
            value = value.slice(0, 3) + '.' + value.slice(3, 6) + '.' + value.slice(6, 9) + '-' + value.slice(9, 11);
        }
        e.target.value = value;
    });
});

This ensures the CPF input is automatically formatted as the user types.

Step 5: Testing and Final Adjustments

After implementing the changes, I cleared the cache from the PrestaShop backoffice and tested the registration form. The CPF field worked perfectly, and the data was stored correctly in the database.

Conclusion

Adding a CPF field to PrestaShop involves several steps: modifying the database, creating a custom module, overriding the Customer class, and updating the form template. Following this structured approach ensures a maintainable and future-proof solution for your e-commerce needs.

If you encounter any issues during the process, feel free to reach out! Happy coding!

0 Comments
Comments Reply