Prestashop product update hook is not updating product attributes in the hook function - prestashop

I am using hookActionProductUpdate. I am getting all data updated but not attributes.
This is the code inside hook function:
public function hookActionProductUpdate($params) {
$prestaObject = new ProductCore($params['id_product'], false, Context::getContext()->language->id);
$arrrs = $prestaObject->getFrontFeatures(1);
}
Everything else is updated but the front features I am getting are the older one. Any IDEA?
EDIT: I tried this too, here is my new function:
public function hookActionProductUpdate($params) {
$product = $params['product'];
$arrrs = $product->getFrontFeatures(1);
pr($arrrs);die("No updating :(");
}

You don't need to instantiate a new Object. The product Object should already be contained in $params['product'].
Here is the update() method of Product Class where this Hook is called:
public function update($null_values = false)
{
$return = parent::update($null_values);
$this->setGroupReduction();
// Sync stock Reference, EAN13 and UPC
if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && StockAvailable::dependsOnStock($this->id, Context::getContext()->shop->id)) {
Db::getInstance()->update('stock', array(
'reference' => pSQL($this->reference),
'ean13' => pSQL($this->ean13),
'upc' => pSQL($this->upc),
), 'id_product = '.(int)$this->id.' AND id_product_attribute = 0');
}
Hook::exec('actionProductSave', array('id_product' => (int)$this->id, 'product' => $this));
Hook::exec('actionProductUpdate', array('id_product' => (int)$this->id, 'product' => $this));
if ($this->getType() == Product::PTYPE_VIRTUAL && $this->active && !Configuration::get('PS_VIRTUAL_PROD_FEATURE_ACTIVE')) {
Configuration::updateGlobalValue('PS_VIRTUAL_PROD_FEATURE_ACTIVE', '1');
}
return $return;
}
You should then use this code instead:
public function hookActionProductUpdate($params) {
$product = $params['product'];
$arrrs = $product->getFrontFeatures(1);
}

Yeah I got it why, Its a bug in prestashop, It calls the hook AdminProductsController
Hook::exec('actionProductSave', array('id_product' => (int)$this->id, 'product' => $this));
Hook::exec('actionProductUpdate', array('id_product' => (int)$this->id, 'product' => $this));
from an update method which is called first then it executes the feature update code.
INSIDE processupdate function
I found this code
//this update method calls the HOOK and when this hook get executed it updates features in the database.
if ($object->update()) {
// If the product doesn't exist in the current shop but exists in another shop
if (Shop::getContext() == Shop::CONTEXT_SHOP && !$existing_product->isAssociatedToShop($this->context->shop->id)) {
$out_of_stock = StockAvailable::outOfStock($existing_product->id, $existing_product->id_shop_default);
$depends_on_stock = StockAvailable::dependsOnStock($existing_product->id, $existing_product->id_shop_default);
StockAvailable::setProductOutOfStock((int)$this->object->id, $out_of_stock, $this->context->shop->id);
StockAvailable::setProductDependsOnStock((int)$this->object->id, $depends_on_stock, $this->context->shop->id);
}
PrestaShopLogger::addLog(sprintf($this->l('%s modification', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$this->object->id, true, (int)$this->context->employee->id);
if (in_array($this->context->shop->getContext(), array(Shop::CONTEXT_SHOP, Shop::CONTEXT_ALL))) {
if ($this->isTabSubmitted('Shipping')) {
$this->addCarriers();
}
if ($this->isTabSubmitted('Associations')) {
$this->updateAccessories($object);
}
if ($this->isTabSubmitted('Suppliers')) {
$this->processSuppliers();
}
if ($this->isTabSubmitted('Features')) {
$this->processFeatures();
}

Related

issue refer to scope of variable

how to get variable from outer layer method
trying to use a variable in outer layer in my React-Native App
updateCheckBox() {
Constants.TABS.map((item) => {//Constants.TABS is an array
AsyncStorage.getItem(item)//using item as key to fetch from AsyncStorage
.then((res) => {
if(res == 1) {
//debugged here, item was undeined. but i need setState here with item as key. How should i get item here.
this.setState({item: true}) // I need to get the item here, but it show undefined
} else {
this.setState({item:false}) // I need to get the item here, but it show undefined
}
})
})
}
// I need to get the item here, but it show undefined
You need to wrap the item in [] to use it as a key for a property. Like this:
updateCheckBox() {
Constants.TABS.map(item => {
AsyncStorage.getItem(key) //
.then((res) => {
//item is accessible here, to use item as the key to a property wrap it in []
if(res == 1) {
this.setState({[item]: true});
} else {
this.setState({[item]: false});
}
})
})
}
finally, I found there is no issue in this code, the thing is
updateCheckBox() {
Constants.TABS.map((item) => {
let key = item
AsyncStorage.getItem(key)
.then((res) => {
console.log(item, "item is here", res); //item is visible here
console.log(key) //key is all always undefined
if(res == 1) {
this.setState({item: true})
} else {
this.setState({item:false})
}
})
})
}
key is not visible in method then, which I can not explain, but all in all, my code works.

How to get array of specific attributes values in cypress

I have a few elements in DOM and each of them has its own attribute 'id'. I need to create a function which iterates throw all of these elements and pushes values into the array. And the happy end of this story will be when this function will give me this array with all 'id' values.
I have tried this:
function getModelIds() {
let idList = [];
let modelId;
cy.get(someSelector).each(($el) => {
cy.wrap($el).invoke('attr', 'id').then(lid => {
modelId = lid;
idList.push(modelId);
});
});
return idList;
}
Will be very appreciated if you help me with rewriting this code into a function which will return an array with all 'id' values.
You can have a custom command:
Cypress.Commands.add(
'getAttributes',
{
prevSubject: true,
},
(subject, attr) => {
const attrList = [];
cy.wrap(subject).each($el => {
cy.wrap($el)
.invoke('attr', attr)
.then(lid => {
attrList.push(lid);
});
});
return cy.wrap(attrList);
}
);
You can use it later like this:
cy.get(someSelector)
.getAttributes('id')
.then(ids => {
cy.log(ids); // logs an array of strings that represent ids
});

Yii2 - activeform ajax validation with normal form submit

Using the beforeSubmit function of yii.activeForm.js, how can I make it perform a normal form submit when validation passes?
I have tried the following:
$('.ajax-form').on('beforeSubmit', function (event) {
var form = $(this);
var url = form.attr('action');
var type = form.attr('method');
var data = form.serialize();
$.ajax({
url: url,
type: type,
data: data,
success: function (result) {
if (result.errors.length != 0) {
form.yiiActiveForm('updateMessages', result.errors, true);
}
else if (result.confirmed == true) {
$('.confirm-panel').show();
}
else {
return true;
}
},
error: function() {
alert('Error');
}
});
// prevent default form submission
return false;
});
Controller:
public function actionProcess()
{
$model = $this->findModel($id);
if (Yii::$app->request->isAjax) {
$return_array = [
'errors' => [],
'confirmed' => false,
];
Yii::$app->response->format = Response::FORMAT_JSON;
$return_array['errors'] = ActiveForm::validate($model);
if ($model->confirm == 1) {
$return_array['confirmed'] = true;
}
return $this->asJson($return_array);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['success']);
}
return $this->render('process', [
'model' => $model,
]);
}
As you can see I am also trying to return additional data in my AJAX response. The problem I am having is the return true in the ajax success isn't working. I can't seem to break out of the function. I have also tried form.submit() here but this just does a submit loop via AJAX.
By the way I am not using enableAjaxValidation because I have some additional custom validation that happens in my controller. So this is why I have created my own custom handler for this.
First of all, you can't return true from within an ajax success function to continue form submission as it is javascript and the last line return true is already executed before the response is received so the form ain't going to submit by returning true inside the success function.
You need to use the event afterValidate if you want to submit your page manually after successful ajax validation rather than using beforeSubmit as it will go into an infinite loop if you try to submit the form using $("form").submit() inside the ajax success function. so change your line
$('.ajax-form').on('beforeSubmit', function (event) {
to
$('.ajax-form').on('afterValidate', function (event) {
and then change your success function to
success: function (result) {
if (result.errors.length != 0) {
form.yiiActiveForm('updateMessages', result.errors, true);
}
else if (result.confirmed == true) {
$('.confirm-panel').show();
}
else {
form.submit();
}
},
Hope it helps you out.
Input validation should be made in models no matter if it's built in or custom. Then you can easily use the default ajax validation.
For creating custom validators check http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators
you need not to write any such code for this propose. Yii can handle ajax validations it-self. only thing that you need to do is enable it in active form like.
php $form = ActiveForm::begin([
'id' => 'contact-form',
'enableAjaxValidation' => true,
]); ?>
and placing this code in controller after initialize $model.
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return = ActiveForm::validate($model);
}

Is my order complete return approach correct?

When a customer is returned to the following URL (example);
http://prestashop.dev/index.php?action=completed&controller=callback&fc=module&hmac={valid-hmac}&merchant_order_id=14&module=chippin
After a successful payment, It will call on this FrontController sub-class;
class ChippinCallbackModuleFrontController extends ModuleFrontController
{
public function postProcess()
{
$chippin = new Chippin();
$payment_response = new PaymentResponse();
$payment_response->getPostData();
// if a valid response from gateway
if(ChippinValidator::isValidHmac($payment_response)) {
// "action" is passed as a param in the URL. don't worry, the Hmac can tell if it's valid or not.
if ($payment_response->getAction() === "completed") {
// payment_response->getMerchantOrderId() will just return the id_order from the orders table
$order_id = Order::getOrderByCartId((int) ($payment_response->getMerchantOrderId()));
$order = new Order($order_id);
// this will update the order status for the benefit of the merchant.
$order->setCurrentState(Configuration::get('CP_OS_PAYMENT_COMPLETED'));
// assign variables to smarty (copied this from another gateway, don't really understand smarty)
$this->context->smarty->assign(
array(
'order' => $order->reference,
)
);
// display this template
$this->setTemplate('confirmation.tpl');
I'm quite new to Prestashop. I'm just not sure if this is technically done or not. The confirmation.tlp view does display with the order->reference and the order status is updated to "Completed" but is this all I need?
Are there any other considerations? I have the opportunity to call a hookDisplayPaymentReturn at this point but why should I?
I seem to have a pretty standard return page. Is this enough;
Update - Do I just call a hook something like;
public function displayPaymentReturn()
{
$params = $this->displayHook();
if ($params && is_array($params)) {
return Hook::exec('displayPaymentReturn', $params, (int) $this->module->id);
}
return false;
}
As far as I can see everything seems okay for me.
You should consider adding hookDisplayPaymentReturn it allows other modules to add code to your confirmation page. For example a Google module could add javascript code that sends order informations to analytics on confirmation page.
EDIT
class ChippinCallbackModuleFrontController extends ModuleFrontController
{
public function postProcess()
{
$chippin = new Chippin();
$payment_response = new PaymentResponse();
$payment_response->getPostData();
// if a valid response from gateway
if(ChippinValidator::isValidHmac($payment_response)) {
// "action" is passed as a param in the URL. don't worry, the Hmac can tell if it's valid or not.
if ($payment_response->getAction() === "completed") {
// payment_response->getMerchantOrderId() will just return the id_order from the orders table
$order_id = Order::getOrderByCartId((int) ($payment_response->getMerchantOrderId()));
$order = new Order($order_id);
// this will update the order status for the benefit of the merchant.
$order->setCurrentState(Configuration::get('CP_OS_PAYMENT_COMPLETED'));
// assign variables to smarty (copied this from another gateway, don't really understand smarty)
$this->context->smarty->assign(
array(
'order' => $order->reference,
'hookDisplayPaymentReturn' => Hook::exec('displayPaymentReturn', $params, (int) $this->module->id);
)
);
$cart = $this->context->cart;
$customer = new Customer($cart->id_customer);
Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.$order->id.'&key='.$customer->secure_key);
And in your module :
class myPaymentModule extends PaymentModule
{
public function install()
{
if (!parent::install() || !$this->registerHook('paymentReturn'))
return false;
return true;
}
// Example taken from bankwire module
public function hookPaymentReturn($params)
{
$state = $params['objOrder']->getCurrentState();
$this->smarty->assign(array(
'total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false),
'bankwireDetails' => Tools::nl2br($this->details),
'bankwireAddress' => Tools::nl2br($this->address),
'bankwireOwner' => $this->owner,
'status' => 'ok',
'id_order' => $params['objOrder']->id
));
if (isset($params['objOrder']->reference) && !empty($params['objOrder']->reference))
$this->smarty->assign('reference', $params['objOrder']->reference);
return $this->display(__FILE__, 'confirmation.tpl');
}
}

Doctrine 2 issue inside Zf2 Navigation - strange issue

I can use doctrine from all my controller without any problem
$em = $this->getServiceLocator()->get("doctrine.entitymanager.orm_default");
$newsItems = $em->getRepository('Website\Entity\News')->findAll();
foreach($newsItems as $item)
// do stuff here
Preamble: if I use Zend\Db\Adapter instead of Doctrine the following work as aspected !
I'm inside a MyNavigationObject that was instanciated by MyNavigationFactory.
I have a mysql table called mainmenu with 4 records: home,news,company,contact
I would like to do my own navigation with Doctrine-Orm.
Also I have an entity called Mainmenu.
I can call the entityManager and the results is composed with 4 records but 4 times the records number 1. Incredible !
this is the code:
protected function getPages(ServiceLocatorInterface $serviceLocator)
{
if (null === $this->pages) {
$em = $serviceLocator->get("doctrine.entitymanager.orm_default");
$menuItems = $em->getRepository('Website\Entity\Mainmenu')->findAll();
//return default key
$configuration['navigation'][$this->getName()] = array();
foreach ($menuItems as $menuItem)
{
$configuration['navigation'][$this->getName()][$menuItem->getName()] = array(
'label' => $menuItem->getLabel(),
'route' => $menuItem->getRoute(),
'controller' => $menuItem->getController(),
);
}
if (!isset($configuration['navigation'])) {
throw new \Exception\InvalidArgumentException('Could not find navigation configuration key');
}
if (!isset($configuration['navigation'][$this->getName()])) {
throw new Exception\InvalidArgumentException(sprintf(
'Failed to find a navigation container by the name "%s"',
$this->getName()
));
}
// refer to Mvc::Application object not to modulename
$application = $serviceLocator->get('Application');
$routeMatch = $application->getMvcEvent()->getRouteMatch();
$router = $application->getMvcEvent()->getRouter();
$pages = $this->getPagesFromConfig($configuration['navigation'][$this->getName()]);
$this->pages = $this->injectComponents($pages, $routeMatch, $router);
}
return $this->pages;
Can anyone provide suggestions or reproduce the issue ?
bye