Customizing Xmultiselect in Yii - yii-extensions

I am not able to make the left list of multiselect widget in empty mode on load. It shows error when I set null value to the left list. This is my code:
$this->widget('ext.widgets.multiselects.XMultiSelects', array(
'leftTitle' => '',
'leftName' => 'Certificate[selected][]',
'leftList' => SpecificCertification::model()->findCertificate(),// here I need to make the list empty
'rightTitle' => '',
'rightName' => 'Certificate[all][]',
'rightList' => SpecificCertification::model()->findCertificates(),
'size' => 10,
));
How can I make the left list empty ?

You need to open file widget XMultiSelects.php and modify it to fit your need
public function init()
{
/* Comment out the below validation
if(!isset($this->leftList))
{
throw new CHttpException(500,'"leftList" have to be set!');
}
if(!isset($this->rightList))
{
throw new CHttpException(500,'"rightList" have to be set!');
}
*/
}
Add validation for leftList and rightList such as below
if($this->leftList){
foreach($this->leftList as $value=>$label)
{
echo "<option value=\"{$value}\">{$label}</option>\n";
}
}
and
if($this->rightList){
foreach($this->rightList as $value=>$label)
{
echo "<option value=\"{$value}\">{$label}</option>\n";
}
}
After then, you can set null for them like what you did

Related

laravel 8 session doesn't save data

I'm trying to save an array for checkout but when i print session it gives null
namespace App\Http\Livewire;
use App\Orders;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Cart;
use Carbon\Carbon;
public function setAmountForCheckout()
{
if(session()->has('coupon'))
{
session()->put('checkout',[
'discount'=>$this->discount,
'subtotal'=>$this->subtotalAfterDiscount,
'total'=>$this->totalAfterDiscount,
]);
}
else
{
session()->put('checkout',[
'discount'=>0,
'tax'=>Cart::instance('cart')->tax(),
'subtotal'=>Cart::instance('cart')->subtotal(),
'total'=>Cart::instance('cart')->total(),
]);
session()->save();
}
}
public function placeOrder(Request $request)
{
dd(session()->get('checkout'));
$this->validate([
'first_name' => 'required|min:4|string',
'Phone_number' => 'required|digits:11'
]);
$order=new Orders();
$order->user_id=Auth::id();
$order->cust_name=$this->first_name;
$order->phone=$this->Phone_number;
$order->subtotal=session()->get('checkout')['subtotal'];
$order->discount=session()->get('checkout')['discount'];
$order->total=session()->get('checkout')['total'];
$order->status='ordered';
$order->is_shipping=$this->haveShipping ? 1:0;
foreach(Cart::instance('cart')->content() as $items)
{
$orderItem= new OrderItems();
$orderItem->product_id=$items->id;
$orderItem->price=$item->price;
$orderItem->order_id=$order->id;
$orderItem->quantity=$item->qty;
$orderItem->save();
}
if($this->haveShipping)
{
$this->validate([
'Address'=>'required|min:4',
'shipping_fee'=>'required|numeric'
]);
$order->address=$this->Address;
$order->delivery=$this->shipping_fee;
}
$order->save();
Cart::instance('cart')->destroy();
session()->forget('checkout');
}
when i remove dd it gives me the error "Trying to access array offset on value of type null"
I'm trying to find what's wrong with the session.
also i have checked the cart if it works or not but i found that it works well and delivers data.
Remove
session()->save();
This is not needed as per https://laravel.com/docs/8.x/session#storing-data

Yii1 - sanitize GET parameter in the before action

I am trying to find if it possible to use the beforeAction in the controller to access the injected parameter.
For example, every action in the controller accepts type parameter, which I need to sanitize:
public function actionGetCustomPaymentsChunk($type) {
$type = TextUtil::sanitizeString($type);
// Get filter data
$filter = FilterHelper::getFilterData();
// Initialize components
$totalCostPayableComponent = new TotalCostPayableComponent($filter);
// Get chunk data
$data = $totalCostPayableComponent->getCustomPaymentChunk($type);
// Return content to client side
$this->renderPartial('/partials/_payable_cost_chunk', array(
'data' => $data,
'route' => 'totalCostPayable/getCustomPaymentsGrid',
'type' => $type,
'paymentType' => 'Custom',
));
}
}
Is this possible to do (I am trying to avoid repetition)?
You should be able to, what did you try?
Assuming the $type is passed via GET, you can modify it in a beforeAction and the modified value will be applied to the target action with a request like
http://myhost.com/route/test?type=something
using the below, $type = "foo" in any action in this controller.
protected function beforeAction($action)
{
if (isset($_GET['type'])) {
$_GET['type'] = 'foo';
}
...
return parent::beforeAction($action);
}
public function actionTest($type)
{
# $type === 'foo'
...
}
Change the manipulation in beforeAction to satisfy whatever your requirements are.

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

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();
}

Yii2 iterate dataprovider with relations

I need to know how to iterate through a Yii2 dataprovider with relations.
I have a model Asset that has a relationship to another model Make.
class Equipment extends \yii\db\ActiveRecord
{
// ...
public function getMake() {
return $this->hasOne(Make::className(), ['make_id' => 'make_id']);
}
}
In my controller, I have 2 functions, one to render a grid, and another to export the data to a CSV file.
public function actionEquipment()
{
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// Store the search model in session
Yii::$app->session->set('exportEquipmentModel', $searchModel);;
// Render grid
return $this->render('equipment', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionExportequipment()
{
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="equipment_report-' . date('YmdHi') .'.csv"');
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// Use the search model from session, or get all
if(\Yii::$app->session->get('exportEquipmentModel')) {
$searchModel = Yii::$app->session->get('exportEquipmentModel');
$dataProvider = $searchModel->search(false);
$dataProvider->setPagination(false);
}
// csv header
$columns =[
'serial_number',
'Make',
'Model',
];
echo implode(",", $columns) . " \r\n";
// csv data
foreach ($dataProvider->getModels() as $data) {
$row =[
$data['serial_number'],
// TODO: I need to resolve the relation here
$data['make_id'] // Works
// $data->make_id // Works
// $data->make->description // Does not work
// $data['make_id']['description'], // Does not work
$data['model_id']
];
echo implode(",", $row) . " \r\n";
}
}
As can be see from the comments in the code, various forms of getting the make->description field is not yielding results.
Lesson learned : Always check for errors.
My code was correct. However, the data was not what I expected. The dba deleted some of the makes and models after setting off foreign key checks. Therefore, $data->make.
I therefore changed the line
$data->make->description
to
!empty($data->make)?$data->make->description:'Not Set',

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