Prestashop .7.6 and 1.7.7 make birthday (age) mandatory and limit 18+ years old

P

Create a new override file in

/override/classes/form/CustomerFormatter.php

 

<?php
use Symfony\Component\Translation\TranslatorInterface;

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

//translator and language are private in parent class, override need
public function __construct(
TranslatorInterface $translator,
Language $language
) {
$this->translator = $translator;
$this->language = $language;

parent::__construct($translator,$language);
}

public function getFormat()
{
$format = parent::getFormat();

//override/add all customisations for fields
$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%)’, array(‘%date_format%’ => Tools::formatDateStr(’31 May 1970′)), ‘Shop.Forms.Help’)
)
->setRequired(true);

//As addConstraints method is private we need to call the logic here. We don’t need to iterate over all the fields again, just the changed ones.
$constraints = Customer::$definition[‘fields’];
$field = $format[‘birthday’];

if (!empty($constraints[$field->getName()][‘validate’])) {
$field->addConstraint(
$constraints[$field->getName()][‘validate’]
);
}

return $format;
}
}

 

 

Create a new file in

/override/classes/Validate.php

<?php

// User has to have a minimum age of 18 years

class Validate extends ValidateCore
{

public static function isBirthDate($date, $format = ‘Y-m-d’)
{
if (empty($date) || $date == ‘0000-00-00’) {
return false;
}

$d = DateTime::createFromFormat($format, $date);
if (!empty(DateTime::getLastErrors()[‘warning_count’]) || false === $d) {
return false;
}

//adding 18 years to the birth date
$d->add(new DateInterval(“P18Y”));

return $d->getTimestamp() < time();
}
}

 

Change translation to include “You must have 18+ years” in the error message shown in front office.

Remember to restart php (fpm or apache) to clear opcache and delete /var/cache/* data to regenerate override

 

sudo service php7.2-fpm restart

sudo rm -rf var/cache/*

About the author