Customer register - make birthday field required

In my previous article about making gender field required I explained the way of how to mark gender field required. In this guide I want to explain how to make "birthday" field required. In this case steps are the same as steps described previously. But in addition to these steps we need to change ObjectModel.php file too. This file is a base of all objects (like customer, product, cart, etc.) and it is located in classes/ObjectModel.php file.

 

Why we need to change this file too?

because "birthday" field is not a single field, it consists of three other fields: year, month and day. So in effect we will see notification that "birthday field is requried" even if we will fill out year, month and day (because birthday field 'as is', is not send after submit the register form - only year, month, day are submitted - so they arent with 'birthday' name).

 

how to make gender field required in prestashop

 

How to make birthday field required

As I already mentioned in previous tutorial - we need to mark birthday field as a 'required' => true. Details about that you can find here: article about making gender field required. So please mark birthday field as required and go to the next step of this guide.

 

Changing objectModel.php file

Please open file classes/ObjectModel.php. You can find there function public function validateController($htmlentities = true). Inside this function you can find foreach loop that looks like:

foreach ($this->def['fields'] as $field => $data) {
...
...
//foreach loop code here
//foreach loop code here
//foreach loop code here
...
...
}

At the begining of this foreach loop we need to create 'birthday' field that will be build based on posted fields: year, month and day. To create such variable we need to use special code that i attach below:

            if ($field=="birthday"){
                if (isset($_POST['years']) && isset($_POST['months']) && isset($_POST['days'])){
                    $_POST['birthday']=(empty($_POST['years']) ? '' : (int)Tools::getValue('years').'-'.(int)Tools::getValue('months').'-'.(int)Tools::getValue('days'));
                }
            }

 

I attach modified function below (code that I added to create 'birthday' variable is highlighted)

    /**
     * Validates submitted values and returns an array of errors, if any.
     *
     * @param bool $htmlentities If true, uses htmlentities() for field name translations in errors.
     *
     * @return array
     */
    public function validateController($htmlentities = true)
    {
        $this->cacheFieldsRequiredDatabase();
        $errors = array();
        $required_fields_database = (isset(self::$fieldsRequiredDatabase[get_class($this)])) ? self::$fieldsRequiredDatabase[get_class($this)] : array();
        foreach ($this->def['fields'] as $field => $data) {
            
            if ($field=="birthday"){
                if (isset($_POST['years']) && isset($_POST['months']) && isset($_POST['days'])){
                    $_POST['birthday']=(empty($_POST['years']) ? '' : (int)Tools::getValue('years').'-'.(int)Tools::getValue('months').'-'.(int)Tools::getValue('days'));
                }
            }
            
            $value = Tools::getValue($field, $this->{$field});
            // Check if field is required by user
            if (in_array($field, $required_fields_database)) {
                $data['required'] = true;
            }

            // Checking for required fields
            if (isset($data['required']) && $data['required'] && empty($value) && $value !== '0') {
                if (!$this->id || $field != 'passwd') {
                    $errors[$field] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is required.');
                }
            }

            // Checking for maximum fields sizes
            if (isset($data['size']) && !empty($value) && Tools::strlen($value) > $data['size']) {
                $errors[$field] = sprintf(
                    Tools::displayError('%1$s is too long. Maximum length: %2$d'),
                    self::displayFieldName($field, get_class($this), $htmlentities),
                    $data['size']
                );
            }

            // Checking for fields validity
            // Hack for postcode required for country which does not have postcodes
            if (!empty($value) || $value === '0' || ($field == 'postcode' && $value == '0')) {
                $validation_error = false;
                if (isset($data['validate'])) {
                    $data_validate = $data['validate'];
                    if (!Validate::$data_validate($value) && (!empty($value) || $data['required'])) {
                        $errors[$field] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).
                            '</b> '.Tools::displayError('is invalid.');
                        $validation_error = true;
                    }
                }

                if (!$validation_error) {
                    if (isset($data['copy_post']) && !$data['copy_post']) {
                        continue;
                    }
                    if ($field == 'passwd') {
                        if ($value = Tools::getValue($field)) {
                            $this->{$field} = Tools::encrypt($value);
                        }
                    } else {
                        $this->{$field} = $value;
                    }
                }
            }
        }

        return $errors;
    }


If you will replace original function with code above prestashop will spawn information about 'birthday field is required' only if year, month and day fields will not be submitted during customer register process. So everything will work as it should work.

 

author milos myszczuk
Article by Milosz Myszczuk PrestaShop expert, official PrestaShop community moderator. PHP developer, specialist in relative and spatial databases management, GIS Analyst, CEO & founder of VEKIA interactive agency. Read more about VEKIA company
If you like my articles and want much more valuable tips, feel free to send me donation
1.4 version 1.4.11 1.6 404 addon admin advertise ahref ajax alpha animation api app application authentication back office backup badge banner basics block bootstrap button cache carrier cart catalog category certificate changelog chat class clear client clip cms code colors columns comments configuration contact container content controller cookie counter country coupon css csv currency customer dashboard database debug default delete delivery desktop developer device disable discount displayNav displayTop download dynamic editor effect empty encrypt engine error exchange exclude export facebook faceshop fade fancoupon fancybox fanpage fatal feature feed field file fix fixed font footer free friendly url front ftp full gallery generate gift global godaddy google google+ gray grid groupon header help hide highlight homefeatured homepage hook hosting hover howto htaccess html html5 ID image import include input instagram installation integration iPhone issue javascript jquery kgb knowhow languages law left likebox link list livingsocial loading log login logo loyality mail mailing maintenance manufacturer marketing marquee mcrypt menu meta mobile modification module movie moving multilanguage multiupload must have mysql news newsletter notification number open graph order override page password performance PHP phpmyadmin picture pinterest plugin popup post prestashop prestashop 1.0 prestashop 1.1 prestashop 1.2 prestashop 1.3 prestashop 1.4 prestashop 1.5 price rules problem product profile promotion proslider purifier quantity query quick tip random rates register reinsurance release reporting reset responsive restore results ribbon rich text right sales search security seo service shadow share shipping shop shopmania slider smarty social networks SQL SSL statistics stock store style subcategory superuser support switcher tab tablet tag tax template text theme tinyMCE tips and tricks tpl tracking translations tree trends trigger tumblr tutorial twitter update upgrade upload variables video visits voucher vulnerability web2print wide widget width window wishlist wysiwyg youtube zip zopim