Yii2, optional parameter in the rounte - yii

During the development, I have faced to the one issue with urlManager.
I have SiteController with "category" action.
public function actionCategory($id = null, $city = null, $location = null)
{
echo $id;
echo $city;
echo $location;
}
All possible combination that can be used with this action:
id, city, location = null
id, city = null, location
id, city = null, location = null
id = null, city = null, location = null
id = null, city = null, location
I do not know how to write the rules in the UrlManager, after that I will get the following values in the variables after press the links:
<h4><?= Html::a('ID City', ['/site/category', 'id' => 'barbershop', 'city' => 'Praha'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:
id = 'barbershop'
city = 'Praha'
location = ''
<h4><?= Html::a('ID Location', ['/site/category', 'id' => 'barbershop', 'location' => '23,65'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:
id = 'barbershop'
city = ''
location = '23,65'
<h4><?= Html::a('ID', ['/site/category', 'id' => 'barbershop'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:
id = 'barbershop'
city = ''
location = ''
<h4><?= Html::a('City', ['/site/category', 'city' => 'Praha'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:
id = ''
city = 'Praha'
location = ''
<h4><?= Html::a('Location', ['/site/category', 'location' => '14,23'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:
id = ''
city = ''
location = '14,23'
Would you like you help me with this issue?

As per your requirements you need to set rules only for Controller and action name. All other fields are passed through $_GET. and you can fetch them using Yii::$app->getRequest()->getQueryParam('param') method.
For you url you can use normal rules for pretty url like
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],

Related

Cakephp 4 save delete auto_increment

I'm doing cakephp4 controller test with phpUnit but when I call save my id auto_increment disapear.
My table before save():
Image before save
The test:
public function testAdd(): void
{
$this->session([
'Auth' => [
'id' => 1,
'DNI_CIF' => '22175395Z',
'name' => 'Prueba',
'lastname' => 'Prueba Prueba',
'username' => 'Pruebatesting',
'password' => 'prueba',
'email' => 'prueba#gmail.com',
'phone' => '639087621',
'role' => 'admin',
'addres_id' => 1
]
]);
$this->get('animal/add');
$this->assertResponseOk();
$data=[
'id' => 1,
'name' => 'AñadirAnimal',
'image' => '',
'specie' => 'dog',
'chip' => 'no',
'sex' => 'intact_male',
'race' => 'cat',
'age' => 1,
'information' => 'Es un animal.',
'state' => 'sick',
'animal_shelter' => [
'id' => 1,
'start_date' => '2022-11-03 10:47:38',
'end_date' => '2022-11-03 10:47:38',
'user_id' => 1,
'animal_id' => 1
]
];
$this->enableCsrfToken();
$this->post('animal/add',$data);
$this->assertResponseOk();
}
The controller:
public function add()
{
$animal = $this->Animal->newEmptyEntity();
if ($this->request->is('post')) {
$animal = $this->Animal->patchEntity($animal, $this->request->getData());
if(!$animal->getErrors){
$image = $this->request->getData('image_file');
if($image !=NULL){
$name = $image->getClientFilename();
}
if( !is_dir(WWW_ROOT.'img'.DS.'animal-img') ){
mkdir(WWW_ROOT.'img'.DS.'animal-img',0775);
if($name){
$targetPath = WWW_ROOT.'img'.DS.'animal-img'.DS.$name;
$image->moveTo($targetPath);
$animal->image = 'animal-img/'.$name;
}
}
if ($this->Animal->save($animal)) {
$this->Flash->success(__('El animal se ha añadido.'));
return $this->redirect(['action' => 'index']);
}
}
$this->Flash->error(__('El animal no se ha podido añadir, por favor intentalo de nuevo'));
}
$allUsers = $this->getTableLocator()->get('User');
$user = $allUsers->find('list', ['limit' => 200])->all();
$this->set(compact('animal','user'));
}
My table after:
Image after save
The error:
1) App\Test\TestCase\Controller\AnimalControllerTest::testAdd
Possibly related to PDOException: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"
…
Failed asserting that 500 is between 200 and 204.
I don't know why this is happening or how to know the reason. In the app the controller works fine. Data in the app:
Data in app
Data in test:
Data in test
I hope someone can help me, I don't know what to try anymore or how to know where the problem is...
I tried to look at the data but it doesn't apear to have any errors so I don't know where the error can be.
It was that the sql file used in the bootstrap didn't have the autoincrement value.

Error message : Unknown column 'a.id_configuration' in 'order clause'

With this code i would like print a tab with some fields in prestashop back office. But i got an error message: : Unknown column 'a.id_configuration' in 'order clause'
<?php
public function __construct()
{
parent::__construct();
$this->table = 'order_invoice'; // SQL table name, will be prefixed with _DB_PREFIX_
$this->className = 'OrderInvoice'; // PHP class name
$this->allow_export = true; // allow export in CSV, XLS..
$this->fields_list = [
'id_order_invoice' => ['title' => $this->trans('ID', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
'number' => ['title' => $this->trans('Number', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
'date_add' => ['title' => $this->trans('Date', [], 'Admin.Global'), 'type'=>'datetime'],
'total_products_wt' => ['title' => $this->trans('Total products', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
'total_shipping_tax_incl' => ['title' => $this->trans('Total shipping', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
'total_paid_tax_incl' => ['title' => $this->trans('Total paid', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
];
}
?>
```
Since it states it's an error within the order clause (ORDER BY), we'd edit the orderBy variable like this:
$this->_orderBy = 'id_order_invoice';
You can also edit the identifier since it seems to be using the wrong identifier to begin with:
$this->identifier = 'id_order_invoice';
Hope this helps.

Redirect user after saving data in admin controller Prestashop

I have an admin controller which displays the list of data on clicking edit on an entry or adding a new entry I am showing renderForm() but after saving the data (either by edit or add) I want to redirect the user to another controller in place of showing the same controller list.
Bellow is the code which I am currently using for example of my requirements I trying to do something which I have done below in initcontent() but that is not working so I want to know where should I call this in place of initcontent()
<?php
/**
* The file is controller. Do not modify the file if you want to upgrade the module in future
*
* #author Globo Jsc <contact#globosoftware.net>
* #copyright 2016 Globo., Jsc
* #link http://www.globosoftware.net
* #license please read license in file license.txt
*/
include_once(_PS_MODULE_DIR_ . 'cardelivery/classes/AdditionalServicesModel.php');
class AdminAdditionalServiceController extends ModuleAdminControllerCore {
public $name;
public function __construct() {
$this->name = 'AdminAdditionalService';
$this->className = 'AdditionalServicesModel';
$this->table = 'additional_service';
$this->meta_title = $this->l('Additional Services');
$this->deleted = false;
$this->explicitSelect = true;
$this->context = Context::getContext();
$this->bootstrap = true;
$this->_defaultOrderBy = 'id_additional_service';
$this->filter = true;
if (Shop::isFeatureActive()) {
Shop::addTableAssociation($this->table, array('type' => 'shop'));
}
$this->position_identifier = 'id_additional_service';
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->fields_list = array(
'id_additional_service' => array(
'title' => $this->l('ID'),
'type' => 'int',
'width' => 'auto',
'orderby' => false),
'service_name' => array(
'title' => $this->l('Icon'),
'width' => 'auto',
'orderby' => false,
),
'service_desc' => array(
'title' => $this->l('service_desc'),
'type' => 'text'
),
'active' => array(
'title' => $this->l('Status'),
'width' => 'auto',
'active' => 'status',
'type' => 'bool',
'orderby' => false),
);
parent::__construct();
}
function initContent() {
parent::initContent();
if (Tools::isSubmit('submit')) {
Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminCategories') . '&conf=7');
}
}
public function initPageHeaderToolbar() {
$this->page_header_toolbar_btn['back_to_list'] = array(
'href' => Context::getContext()->link->getAdminLink('AdminGCardeliverycity', true),
'desc' => $this->l('Back to list', null, null, false),
'icon' => 'process-icon-back'
);
parent::initPageHeaderToolbar();
}
public function renderForm() {
$id_citydelivery = (int) Tools::getValue('id_citydelivery');
if ($id_citydelivery == 0) {
$addSerModObj = new AdditionalServicesModel((int) Tools::getValue('id_additional_service'));
$id_citydelivery = $addSerModObj->id_citydelivery;
}
$fields_form_1 = array(
'form' => array(
'legend' => array('title' => $this->l('Additional Service'), 'icon' => 'icon-cogs'),
'input' => array(
array(
'type' => 'hidden',
'name' => 'id_citydelivery'
),
array(
'type' => 'text',
'label' => $this->l('Service_name'),
'name' => 'service_name',
'size' => 255,
'required' => true,
'desc' => $this->l('Enter name of Arrival port')
),
array(
'type' => 'text',
'label' => $this->l('service_desc'),
'name' => 'service_desc',
'size' => 255,
'required' => true,
'desc' => $this->l('Enter name of Arrival port')
),
array(
'type' => 'text',
'label' => $this->l('charge'),
'name' => 'charge',
'size' => 255,
'required' => true,
'desc' => $this->l('Enter name of Arrival port')
),
array(
'type' => 'switch',
'label' => $this->l('Active'),
'name' => 'active',
'required' => false,
'is_bool' => true,
'values' => array(array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Active')), array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Inactive')))),
),
'submit' => array('title' => $this->l('Save')),
'buttons' => array(
array(
'href' => Context::getContext()->link->getAdminLink('AdminGCardeliverycity', true) . '&updatecitydelivery&id_citydelivery=' . $id_citydelivery,
'title' => $this->l('Cancle'),
'icon' => 'process-icon-cancel'
)
)
)
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->toolbar_scroll = true;
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submit';
$helper->currentIndex = AdminController::$currentIndex;
$helper->token = Tools::getAdminTokenLite($this->name);
$id_additional_service = (int) Tools::getValue('id_additional_service');
$additionalServiceObj = new AdditionalServicesModel($id_additional_service);
$helper->tpl_vars = array(
'fields_value' => $this->getFormValues($additionalServiceObj),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
$_1 = $helper->generateForm(array($fields_form_1));
$return = $_1;
return $return;
}
function getFormValues($additionalServiceObj) {
return array(
'service_name' => Tools::getValue('service_name ', $additionalServiceObj->service_name),
'service_desc' => Tools::getValue('service_desc', $additionalServiceObj->service_desc),
'charge' => Tools::getValue('charge', $additionalServiceObj->charge),
'active' => Tools::getValue('active', $additionalServiceObj->active)
);
}
}
First of all, it seems that you redirect your page to the same URL. Try to use this
Tools::redirectAdmin($this->context->link->getAdminLink('AdminHome'));
where
AdminHome
is a redirect URL, you need to replace it with yours.
And second, try to use
Tools::getIsset('yourButtonName')
instead of
Tools::isSubmit('yourButtonName')
and the last, if nothing mentioned above will not help, try to move
parent::initContent();
and put it after your condition
Probably redirect_after may be useful
$this->redirect_after = 'Your custom address';

Prestashop add another field to the the address form

I have been trying to add another two non-mandatory fields to the address pages, (user page, admin page, etc)
I created two columns in the ps_address and named address3 and address4 and changed available files in version 1.6.0.11 according to this article
I was able to add the new adreess3 and address4 fields in the country address settings. But there is no text field to add address3 and address4 in the AddressesController and the customer add addresses list.
Following is my modified AddressesController file.
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* #author PrestaShop SA <contact#prestashop.com>
* #copyright 2007-2015 PrestaShop SA
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AdminAddressesControllerCore extends AdminController
{
/** #var array countries list */
protected $countries_array = array();
public function __construct()
{
$this->bootstrap = true;
$this->required_database = true;
$this->required_fields = array('company', 'address2', 'address3', 'address4', 'postcode', 'other', 'phone', 'phone_mobile', 'vat_number', 'dni');
$this->table = 'address';
$this->className = 'Address';
$this->lang = false;
$this->addressType = 'customer';
$this->explicitSelect = true;
$this->context = Context::getContext();
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash'
)
);
$this->allow_export = true;
if (!Tools::getValue('realedit'))
$this->deleted = true;
$countries = Country::getCountries($this->context->language->id);
foreach ($countries as $country)
$this->countries_array[$country['id_country']] = $country['name'];
$this->fields_list = array(
'id_address' => array('title' => $this->l('ID'), 'align' => 'center', 'class' => 'fixed-width-xs'),
'firstname' => array('title' => $this->l('First Name'), 'filter_key' => 'a!firstname'),
'lastname' => array('title' => $this->l('Last Name'), 'filter_key' => 'a!lastname'),
'address1' => array('title' => $this->l('Address')),
'postcode' => array('title' => $this->l('Zip/Postal Code'), 'align' => 'right'),
'city' => array('title' => $this->l('City')),
'country' => array('title' => $this->l('Country'), 'type' => 'select', 'list' => $this->countries_array, 'filter_key' => 'cl!id_country'));
parent::__construct();
$this->_select = 'cl.`name` as country';
$this->_join = '
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (cl.`id_country` = a.`id_country` AND cl.`id_lang` = '.(int)$this->context->language->id.')
LEFT JOIN `'._DB_PREFIX_.'customer` c ON a.id_customer = c.id_customer
';
$this->_where = 'AND a.id_customer != 0 '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER, 'c');
}
public function initToolbar()
{
parent::initToolbar();
if (!$this->display)
$this->toolbar_btn['import'] = array(
'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=addresses',
'desc' => $this->l('Import')
);
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
$this->page_header_toolbar_btn['new_address'] = array(
'href' => self::$currentIndex.'&addaddress&token='.$this->token,
'desc' => $this->l('Add new address', null, null, false),
'icon' => 'process-icon-new'
);
parent::initPageHeaderToolbar();
}
public function renderForm()
{
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Addresses'),
'icon' => 'icon-envelope-alt'
),
'input' => array(
array(
'type' => 'text_customer',
'label' => $this->l('Customer'),
'name' => 'id_customer',
'required' => false,
),
array(
'type' => 'text',
'label' => $this->l('Identification Number'),
'name' => 'dni',
'required' => false,
'col' => '4',
'hint' => $this->l('DNI / NIF / NIE')
),
array(
'type' => 'text',
'label' => $this->l('Address alias'),
'name' => 'alias',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'textarea',
'label' => $this->l('Other'),
'name' => 'other',
'required' => false,
'cols' => 15,
'rows' => 3,
'hint' => $this->l('Forbidden characters:').' <>;=#{}'
),
),
'submit' => array(
'title' => $this->l('Save'),
)
);
$id_customer = (int)Tools::getValue('id_customer');
if (!$id_customer && Validate::isLoadedObject($this->object))
$id_customer = $this->object->id_customer;
if ($id_customer)
{
$customer = new Customer((int)$id_customer);
$token_customer = Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)$this->context->employee->id);
}
$this->tpl_form_vars = array(
'customer' => isset($customer) ? $customer : null,
'tokenCustomer' => isset ($token_customer) ? $token_customer : null
);
// Order address fields depending on country format
$addresses_fields = $this->processAddressFormat();
// we use delivery address
$addresses_fields = $addresses_fields['dlv_all_fields'];
// get required field
$required_fields = AddressFormat::getFieldsRequired();
// Merge with field required
$addresses_fields = array_unique(array_merge($addresses_fields, $required_fields));
$temp_fields = array();
foreach ($addresses_fields as $addr_field_item)
{
if ($addr_field_item == 'company')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Company'),
'name' => 'company',
'required' => in_array('company', $required_fields),
'col' => '4',
'hint' => $this->l('Invalid characters:').' <>;=#{}'
);
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('VAT number'),
'col' => '2',
'name' => 'vat_number',
'required' => in_array('vat_number', $required_fields)
);
}
elseif ($addr_field_item == 'lastname')
{
if (isset($customer) &&
!Tools::isSubmit('submit'.strtoupper($this->table)) &&
Validate::isLoadedObject($customer) &&
!Validate::isLoadedObject($this->object))
$default_value = $customer->lastname;
else
$default_value = '';
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Last Name'),
'name' => 'lastname',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!&lt;&gt;,;?=+()##"�{}_$%:',
'default_value' => $default_value,
);
}
elseif ($addr_field_item == 'firstname')
{
if (isset($customer) &&
!Tools::isSubmit('submit'.strtoupper($this->table)) &&
Validate::isLoadedObject($customer) &&
!Validate::isLoadedObject($this->object))
$default_value = $customer->firstname;
else
$default_value = '';
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('First Name'),
'name' => 'firstname',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!&lt;&gt;,;?=+()##"�{}_$%:',
'default_value' => $default_value,
);
}
elseif ($addr_field_item == 'address1')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address'),
'name' => 'address1',
'col' => '6',
'required' => true,
);
}
elseif ($addr_field_item == 'address2')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (2)',
'name' => 'address2',
'col' => '6',
'required' => in_array('address2', $required_fields),
);
}
elseif ($addr_field_item == 'address3')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (3)',
'name' => 'address3',
'col' => '6',
'required' => in_array('address3', $required_fields),
);
}
elseif ($addr_field_item == 'address4')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (4)',
'name' => 'address4',
'col' => '6',
'required' => in_array('address4', $required_fields),
);
}
elseif ($addr_field_item == 'postcode')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Zip/Postal Code'),
'name' => 'postcode',
'col' => '2',
'required' => true,
);
}
elseif ($addr_field_item == 'city')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('City'),
'name' => 'city',
'col' => '4',
'required' => true,
);
}
elseif ($addr_field_item == 'country' || $addr_field_item == 'Country:name')
{
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('Country'),
'name' => 'id_country',
'required' => in_array('Country:name', $required_fields) || in_array('country', $required_fields),
'col' => '4',
'default_value' => (int)$this->context->country->id,
'options' => array(
'query' => Country::getCountries($this->context->language->id),
'id' => 'id_country',
'name' => 'name'
)
);
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('State'),
'name' => 'id_state',
'required' => false,
'col' => '4',
'options' => array(
'query' => array(),
'id' => 'id_state',
'name' => 'name'
)
);
}
elseif ($addr_field_item == 'phone')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Home phone'),
'name' => 'phone',
'required' => in_array('phone', $required_fields) || Configuration::get('PS_ONE_PHONE_AT_LEAST'),
'col' => '4',
'hint' => Configuration::get('PS_ONE_PHONE_AT_LEAST') ? sprintf($this->l('You must register at least one phone number.')) : ''
);
}
elseif ($addr_field_item == 'phone_mobile')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Mobile phone'),
'name' => 'phone_mobile',
'required' => in_array('phone_mobile', $required_fields) || Configuration::get('PS_ONE_PHONE_AT_LEAST'),
'col' => '4',
'hint' => Configuration::get('PS_ONE_PHONE_AT_LEAST') ? sprintf($this->l('You must register at least one phone number.')) : ''
);
}
}
// merge address format with the rest of the form
array_splice($this->fields_form['input'], 3, 0, $temp_fields);
return parent::renderForm();
}
public function processSave()
{
if (Tools::getValue('submitFormAjax'))
$this->redirect_after = false;
// Transform e-mail in id_customer for parent processing
if (Validate::isEmail(Tools::getValue('email')))
{
$customer = new Customer();
$customer->getByEmail(Tools::getValue('email'), null, false);
if (Validate::isLoadedObject($customer))
$_POST['id_customer'] = $customer->id;
else
$this->errors[] = Tools::displayError('This email address is not registered.');
}
elseif ($id_customer = Tools::getValue('id_customer'))
{
$customer = new Customer((int)$id_customer);
if (Validate::isLoadedObject($customer))
$_POST['id_customer'] = $customer->id;
else
$this->errors[] = Tools::displayError('This customer ID is not recognized.');
}
else
$this->errors[] = Tools::displayError('This email address is not valid. Please use an address like bob#example.com.');
if (Country::isNeedDniByCountryId(Tools::getValue('id_country')) && !Tools::getValue('dni'))
$this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
/* If the selected country does not contain states */
$id_state = (int)Tools::getValue('id_state');
$id_country = (int)Tools::getValue('id_country');
$country = new Country((int)$id_country);
if ($country && !(int)$country->contains_states && $id_state)
$this->errors[] = Tools::displayError('You have selected a state for a country that does not contain states.');
/* If the selected country contains states, then a state have to be selected */
if ((int)$country->contains_states && !$id_state)
$this->errors[] = Tools::displayError('An address located in a country containing states must have a state selected.');
$postcode = Tools::getValue('postcode');
/* Check zip code format */
if ($country->zip_code_format && !$country->checkZipCode($postcode))
$this->errors[] = Tools::displayError('Your Zip/postal code is incorrect.').'<br />'.Tools::displayError('It must be entered as follows:').' '.str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)));
elseif(empty($postcode) && $country->need_zip_code)
$this->errors[] = Tools::displayError('A Zip/postal code is required.');
elseif ($postcode && !Validate::isPostCode($postcode))
$this->errors[] = Tools::displayError('The Zip/postal code is invalid.');
if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
$this->errors[] = Tools::displayError('You must register at least one phone number.');
/* If this address come from order's edition and is the same as the other one (invoice or delivery one)
** we delete its id_address to force the creation of a new one */
if ((int)Tools::getValue('id_order'))
{
$this->_redirect = false;
if (isset($_POST['address_type']))
$_POST['id_address'] = '';
}
// Check the requires fields which are settings in the BO
$address = new Address();
$this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
if (empty($this->errors))
return parent::processSave();
else
// if we have errors, we stay on the form instead of going back to the list
$this->display = 'edit';
/* Reassignation of the order's new (invoice or delivery) address */
$address_type = ((int)Tools::getValue('address_type') == 2 ? 'invoice' : ((int)Tools::getValue('address_type') == 1 ? 'delivery' : ''));
if ($this->action == 'save' && ($id_order = (int)Tools::getValue('id_order')) && !count($this->errors) && !empty($address_type))
{
if (!Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'orders SET `id_address_'.$address_type.'` = '.Db::getInstance()->Insert_ID().' WHERE `id_order` = '.$id_order))
$this->errors[] = Tools::displayError('An error occurred while linking this address to its order.');
else
Tools::redirectAdmin(Tools::getValue('back').'&conf=4');
}
}
public function processAdd()
{
if (Tools::getValue('submitFormAjax'))
$this->redirect_after = false;
return parent::processAdd();
}
/**
* Get Address formats used by the country where the address id retrieved from POST/GET is.
*
* #return array address formats
*/
protected function processAddressFormat()
{
$tmp_addr = new Address((int)Tools::getValue('id_address'));
$selected_country = ($tmp_addr && $tmp_addr->id_country) ? $tmp_addr->id_country : (int)Configuration::get('PS_COUNTRY_DEFAULT');
$inv_adr_fields = AddressFormat::getOrderedAddressFields($selected_country, false, true);
$dlv_adr_fields = AddressFormat::getOrderedAddressFields($selected_country, false, true);
$inv_all_fields = array();
$dlv_all_fields = array();
$out = array();
foreach (array('inv','dlv') as $adr_type)
{
foreach (${$adr_type.'_adr_fields'} as $fields_line)
foreach (explode(' ', $fields_line) as $field_item)
${$adr_type.'_all_fields'}[] = trim($field_item);
$out[$adr_type.'_adr_fields'] = ${$adr_type.'_adr_fields'};
$out[$adr_type.'_all_fields'] = ${$adr_type.'_all_fields'};
}
return $out;
}
/**
* Method called when an ajax request is made
* #see AdminController::postProcess()
*/
public function ajaxProcess()
{
if (Tools::isSubmit('email'))
{
$email = pSQL(Tools::getValue('email'));
$customer = Customer::searchByName($email);
if (!empty($customer))
{
$customer = $customer['0'];
echo Tools::jsonEncode(array('infos' => pSQL($customer['firstname']).'_'.pSQL($customer['lastname']).'_'.pSQL($customer['company'])));
}
}
die;
}
/**
* Object Delete
*/
public function processDelete()
{
if (Validate::isLoadedObject($object = $this->loadObject()))
if (!$object->isUsed())
$this->deleted = false;
return parent::processDelete();
}
/**
* Delete multiple items
*
* #return boolean true if succcess
*/
protected function processBulkDelete()
{
if (is_array($this->boxes) && !empty($this->boxes))
{
$deleted = false;
foreach ($this->boxes as $id)
{
$to_delete = new Address((int)$id);
if ($to_delete->isUsed())
{
$deleted = true;
break;
}
}
$this->deleted = $deleted;
}
return parent::processBulkDelete();
}
}
I also tried clearing cache using the Advanced Parameters > Performance and also did a manual cache clearance as well.
What might the problem be as to not showing the new address fields in backend or the frontend?
Try also delete (no worries it will be rebuid) class_index.php file at cache folder of Your store

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.