Prestashop : Remove Lastname Field Rules Validation From B.O - prestashop

I am trying to remove rules validation for customer's Lastname field..
I have succeed to do it in the front page for customer registration by editing Classes/Customer.php file like this:
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32),
to :
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32),
I have simply used isAnything in validation.
But that's not working in the Backoffice, so i can't edit customers from BO.
Can't find what file to change exactly.
I am using Prestashop V1.7.6.8.
Need help please. Thanks

You must modify two methods in two files.
src/Core/ConstraintValidator/CustomerNameValidator.php, method isNameValid
private function isNameValid($name)
{
return true; // Here true or your own validation.
// Down the original code.
$pattern = $this->characterCleaner->cleanNonUnicodeSupport(self::PATTERN_NAME);
return (bool) preg_match($pattern, $name);
}
src/Core/Domain/Customer/ValueObject/LastName.php, method assertLastNameIsValid
private function assertLastNameIsValid($lastName)
{
return true; // Here true or your own validation.
// Down the original code.
$matchesLastNamePattern = preg_match('/^[^0-9!<>,;?=+()##"°{}_$%:¤|]*$/u', stripslashes($lastName));
if (!$matchesLastNamePattern) {
throw new CustomerConstraintException(sprintf('Customer last name %s is invalid', var_export($lastName, true)), CustomerConstraintException::INVALID_LAST_NAME);
}
}

Related

How to remove validation lastname from prestashop 1.7.8.3 backoffice

I have a question how to remove validation from LastName inside client address edit. I need to allow numbers inside this field.
I found here thread Prestashop : Remove Lastname Field Rules Validation From B.O, but this solution is not working.
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
Change this to isAnything
Step 2 - src\PrestaShopBundle\Form\Admin\Sell\Address/CustomerAddressType.php
Change your code to below code:
line 209: add('last_name', TextType::class, [
'label' => $this->trans('Last name', 'Admin.Global'),
'help' => $genericInvalidCharsMessage,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
'Admin.Notifications.Error',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH]
),
]),
],
])
Now, you are ready to go and check.
Go to the file classes/Address.php file:
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32),
to :
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32),
validate to isAnything.
I think you were modifying in customer class. Please try with Address.php.
Thanks for sharing the files.
I have resolved the case. You need to modify the classes/form/CustomerAddressForm.php
line 229
$isValid &= $this->validateField('lastname', 'isName', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
Change to:
$isValid &= $this->validateField('lastname', 'isAnything', $this->translator->trans(
'Invalid name',
[],
'Shop.Forms.Errors'
));
I want to do this good with override. I have an issue with override this class. I have created module to override but it is not working. There is a way to override this without editing core files?
services:
_defaults:
public: true
form.type.customer_address:
class: 'Playdev\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType'
public: true
arguments:
- '#prestashop.adapter.form.choice_provider.country_state_by_id'
- '#=service("prestashop.adapter.legacy.context").getContext().country.id'
- '#router'
tags:
- { name: form.type }
https://ibb.co/VVjnJYr
There is a file class override:
\modules\pd_overridemodule\src\PrestaShopBundle\Form\Admin\Sell\Address\CustomCustomerAddressType.php
https://ibb.co/7QPHrqx
And I have an error when I am inside Edit Address Form Backoffice
Type error: Too few arguments to function PrestaShopBundle\Form\Admin\Sell\Address\CustomerAddressType::__construct(), 0 passed in C:\laragon\www\prestabiolab\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 92 and exactly 5 expected
[Symfony\Component\Debug\Exception\FatalThrowableError 0]
https://ibb.co/YfwhtKq
I have found a solution
Need to create module and call hookactionCustomerAddressFormBuilderModifier.
public function hookactionCustomerAddressFormBuilderModifier(array $params)
{
/** #var $formBuilder \Symfony\Component\Form */
$formBuilder = $params['form_builder'];
// remove lastname field
$formBuilder->remove('last_name');
// get all fields without removed
$allFields = $formBuilder->all();
// remove all fields
foreach ($allFields as $inputField => $input) {
$formBuilder->remove($inputField);
}
foreach ($allFields as $inputField => $input) {
// normally add fields
$formBuilder->add($input);
// add fields after firstname
if ($inputField == 'first_name') {
$formBuilder->add('last_name', TextType::class, [
'label' => $this->trans('Last name', [], 'Admin.Global'),
'help' => $this->trans(
'Invalid characters:',
[],
'Admin.Notifications.Info'
) . ' ' . TypedRegexValidator::GENERIC_NAME_CHARS,
'required' => true,
'constraints' => [
new NotBlank([
'message' => $this->trans(
'This field cannot be empty.', [], 'Admin.Notifications.Error'
),
]),
new CleanHtml(),
new TypedRegex([
'type' => TypedRegex::TYPE_GENERIC_NAME,
]),
new Length([
'max' => AddressConstraint::MAX_LAST_NAME_LENGTH,
'maxMessage' => $this->trans(
'This field cannot be longer than %limit% characters',
['%limit%' => AddressConstraint::MAX_LAST_NAME_LENGTH],
'Admin.Notifications.Error',
),
]),
],
]);
}
}
}
Now I think it works okey with override :)

Prestashop custom module add table header

I am developing a custom module in Prestashop. In that module I want to show my custom saved values like the table order. So basically the table should have header part and in that header part there would input fields to search the record for the corresponding data header. So the module custom page header should show like this reference image
So can some one tell me how to do this in a custom module? Any help and suggestions will be really appreciable. Thanks
You need some effort to make it all work but for displaying table header, and I do hope you are using HelperList class,
$helper->simple_header = false;
Check official documentation.
Assuming you know how to make a module, all you need is this (bear in mind it is an example and you'll have to replace bits and pieces here and there).
file /modules/mymodule/controllers/admin/AdminRulesController.php
class AdminRulesController extends ModuleAdminController
{
public function __construct()
{
$this->module = 'mymodule';
$this->table = 'rules'; //table queried for the list
$this->className = 'Rules';//class of the list items
$this->lang = false;
$this->bootstrap = true;
$this->context = Context::getContext();
$this->fields_list = array(
'id_rule' => array(
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs',
'search' => false, //in case you want certain fields to not be searchable/sortable
'orderby' => false,
),
'name' => array(
'title' => $this->l('Rule name'),
'align' => 'center',
),
'is_active' => array(
'title' => $this->l('Active'),
'align' => 'center',
'type' => 'bool',
'active' => 'status',
),
'comment' => array(
'title' => $this->l('Comment'),
'align' => 'center',
'callback' => 'displayOrderLink' //will allow you to display the value in a custom way using a controller callback (see lower)
)
);
parent::__construct();
}
public function renderList()
{
$this->addRowAction('edit');
$this->addRowAction('delete');
return parent::renderList();
}
public function displayOrderLink($comment)
{
switch($comment)
{
case 'value1':
return '<span style="color:red">mytext</span>';
case 'value2':
return '<strong>mytext</strong>';
default:
return 'defaultValue';
}
}
}

cakephp save is not working 2.X

I am using CakePHP 2.3, I want to save data as follows follows:
$insertUser = array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
);
$this->SystemUser->saveAll($insertUser) // save record in table.
The above code is not working. I tried another method like:
$this->SystemUser->query("INSERT INTO system_users(Name,LastName,password,email,TimeStamp,RefererUserId) VALUES ('{$Name}','{$lastName}','{$password}','{$email}','{$presentTime}','{$refererId}')");
How can I now get the last inserted id? I used getLastInsertId() to get last inserted id, as below:
$lastid = $this->SystemUser->getLastInsertId();
But it does not seem to work.
Please try the below code. SystemUser is assumed as your model name.
$this->user_data = array(
'SystemUser' => array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
));
if ($this->SystemUser->save($this->user_data)) {
$lastid = $this->SystemUser->getLastInsertId();
} else {
// do something
}
Your $insertUser should be the following
$insertUser['SystemUser'] = array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
);
Then you should be save data as like
if($this->SystemUser->save($insertUser)) {
$lastid = $this->SystemUser->getLastInsertId();
} else {
debug($this->SystemUser->validationErrors); die();
}
This will probably give you the info you need (assuming it's not saving because of invalid data, of course):
debug($this->SystemUser->validationErrors); die();
That's it.

Yii select2 - returned data cannot be selected

I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920

Attach inputFilter to dynamcially created field elements

Until now I have been binding input filters to the form in the module, in other words I have been creating elements in the form, adding input filters to the elements on the module side.
For example check this example
Right now im creating text field elements dynamically depending upon the requirements, like this in my form
//Form
public function addNamesTextFieldElement($names)
{
foreach($names as $name)
{
$nameTextField = new Element\Text($name->getName());
$nameTextField->setAttribute('type', "text");
$nameTextField->setLabel($name->getName());
$this->add($nameTextField );
}
}
What would be best approach where to add/attach input filters to such dynamically generated elements.
I probably wouldn't use this approach, but something like this would work, providing you have already assigned an InputFilter to the form:
public function addNamesTextFieldElement($names)
{
$factory = new InputFactory();
foreach($names as $name)
{
$nameTextField = new Element\Text($name->getName());
$nameTextField->setAttribute('type', "text");
$nameTextField->setLabel($name->getName());
$this->add($nameTextField );
$this->getInputFilter()->add(
$factory->createInput(array(
'name' => $name->getName(),
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
))
);
}
}