product variant array issue - multidimensional-array

Trying create a variable product variants
I am getting this array from product upload form but I want to convert it like :
{color: ["red", "blue"], size: ["M", "L"]}
how I want to convert it like this ....
[{"color":"red","size":"M"},{"color":"red","size":"L"},{"color":"blue","size":"M"},{"color":"blue","size":"L"}]
I try with this but not working
`foreach($att as $key=>$value)
{
$array[$key] = $value;
foreach($value as $key1=>$value1){
$array[][$key] = $value1;
}
$array[][$key] = $value;
}`

Related

How to format hreflang from "en-ae" to "en-AE" (WordPress+Rank Math+WPMLl)?

I need to set it by the technical task.
I've found only
function hrefs_to_uppercase($hrefs) {
$hrefs = array_change_key_case($hrefs,CASE_UPPER);
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
But it makes all characters uppercase - "EN-AE".
Tried manually in wpml settings- didn't help
You can simply replace the array key with the following code:
function hrefs_to_uppercase($hrefs) {
$hrefs['en-AE'] = $hrefs['en-ae'];
unset($hrefs['en-ae']);
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
if you want to make every array key have an uppercase second part (e.g. from en-us to en-US), you can use the codes below (assumed all your keys have a similar structure like en-us):
function hrefs_to_uppercase($hrefs) {
foreach ($hrefs as $key => $val) {
$key_tokens = explode('-', $key);
$new_key = $key_tokens[0] . '-' . strtoupper($key_tokens[1]);
$hrefs[$new_key] = $hrefs[$key];
unset($hrefs[$key]);
}
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
I solved like that for now, maybe right-maybe not
jQuery('[hreflang*="en-ae"]').each(function(){
// Update the 'rules[0]' part of the name attribute to contain the latest count
jQuery(this).attr("hreflang",'en-AE');
});

Get Magento 2 collection based on final_price

I have the following code to get a Magento 2 product collection:
<?php namespace Qxs\Related\Block;
class Related extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
$this->_registry = $registry;
parent::__construct($context, $data);
}
public function getProductCollection()
{
try {
$product = $this->_registry->registry('current_product');
$range_percentage = 35;
$price_temp = round($product->getFinalPrice() / 100 * $range_percentage);
$price_from = $product->getFinalPrice() - $price_temp;
$price_to = $product->getFinalPrice() + $price_temp;
$categories = $product->getCategoryIds();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $categories])
->addPriceDataFieldFilter('%s >= %s', ['min_price', $price_from])
->addPriceDataFieldFilter('%s <= %s', ['min_price', $price_to])
->addMinimalPrice()
->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
return $collection;
} catch (\Exception $e) {
var_dump($e->getMessage());
}
}
}
Code above is updated with a working example
It will return a result with addtofieldfilter 'price' but it does not work with final_price attribute. I need to sort based on final_price because configurable products don't have a price. The code returns: invalid attribute name.
How can I filter on price range in final_price attribute?
Thanks,
The final_price is part of the price index tables, so you can't work with it the same way as you would do with fields and attributes. You need to join in the price index to be able to filter and sort based on final_price. Luckily, Magento has added a few nifty functions for us to use on the product collection; addPriceDataFieldFilter() and addFinalPrice().
Solution
To be able to achieve the logic you describe above, you would want to change your code to something like this:
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoriesFilter(['in' => $categories])
->addPriceDataFieldFilter('%s >= %s', ['final_price', $price_from])
->addPriceDataFieldFilter('%s <= %s', ['final_price', $price_to])
->addFinalPrice()
->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
Note the order of the functions. You must always call addFinalPrice() after all of the addPriceDataFieldFilter() or else the filter won't be applied.
Bonus
If you want to sort by final_price, you can add following code after addFinalPrice():
$collection->getSelect()->order('price_index.final_price ASC');
References
https://github.com/magento/magento2/blob/2.2.9/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L1465
https://github.com/magento/magento2/blob/2.2.9/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L2265

PHPExcel setWidth();

Hi i'm using PhpExcel and Symfony2 , displaying excel files in HTML table.
My controller :
$filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
$objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
$objReader->setReadFilter($filterSubset);
$objPHPExcel = $objReader->load($excel[0]);
$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
$writer->generateStyles();
$writer->generateSheetData();
return $this->render('MonextPerfclientBundle:Default:testexcel.html.twig', array(
'excelHtml'=>$writer,
'stylesExcel'=>$writer,
My ReadFilter class :
class PHPExcel_Reader_DefaultReadFilter implements PHPExcel_Reader_IReadFilter
{
public function __construct($fromColumn, $toColumn) {
$this->columns = array();
$toColumn++;
while ($fromColumn !== $toColumn) {
$this->columns[] = $fromColumn++;
}
}
public function readCell($column, $row, $worksheetName = '') {
// Read columns from 'A' to 'N'
if (in_array($column, $this->columns)) {
return true;
}
return false;
}
}
How can i set width of the 'E' column ?
Blanks columns still displaying..dont know why..
Why the width of columns are always different ?
Thanks #MarkBaker
To manage the width of columns cell you should setting the width in the controller.
.
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
Blanks columns still displaying: You should manage the empty columns from the writer
The width of the olumns is depending on the length of data contained in first line.

Drupal commerce save personnal field

I'm new to Drupal Commerce ...
I added two fields in the order table :
field_date_de_livraison (text) and field_info_comp_cmde (long text).
In a personalized pane , I try to save the entered values ​​with this code :
function pane_date_livraison_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
if (!empty($form_state['values'][$checkout_pane['pane_id']])) {
$Date_saisie = $form_state['values'][$checkout_pane['pane_id']];
if (!empty($Date_saisie['date_livraison'])) {
$Date_sauvegarde = new DateTime($Date_saisie['date_livraison']);
$Date_sauvegarde = $Date_sauvegarde->format('d/m/Y');
$order->field_date_de_livraison = $Date_sauvegarde;
}
if (!empty($Date_saisie['info_comp'])) {
$order->field_info_comp_cmde = $Date_saisie['info_comp'];
}
}
dpm($order, "RETURN_SUBMIT", $type = 'status');
}
With dpm , I see the values ​​assigned to variables , but then they are not saved to the table?
Thank's for your answers !

PHPexcel - getOldCalculatedValue and rangeToArray

Searched for quite a while now, but I'm stuck at the following problem.
I am using PHPexcel 1.8.0
The spreadsheet is read using the following code:
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, TRUE);
So far ok and it works well.
But some spreadsheets contain external referenced data.
And for that I want to use "getOldCalculatedValue".
How do I combine "getOldCalculatedValue" with "rangeToArray" ?
Or is "rangeToArray" inappropriate for this ?
Thanks for any help or hints !
Simple answer, you can't combine the two
rangeToArray() is a simple method for a simple purpose, it doesn't try to do anything clever, simply to return the data from the worksheet as efficiently and quickly as possible
getOldCalculatedValue() is used for a very specific circumstance, and isn't guaranteed to be correct even then, because it retrieves the last value calculated for the cell in MS EXcel itself, which ,ay not be correct if the external workbook wasn't available to MS Excel in that circumstance, or MS Excel formula evaluation was disable.
When calculating cells values from a formula, the PHPExcel calculation engine should use the getOldCalculatedValue() as a fallback if it finds an external reference, and rangeToArray() will try to use this method, but it isn't perfect, especially when that reference in nested deep inside other formulae referenced in other cells.
If you know that a formula in a cell contains an external reference, you should use getOldCalculatedValue() directly for that cell
I came up with the following solution.
Maybe not perfect, but it currently does the job. Thanks for any improvements!
With PHPExcel included and the excel file uploaded and ready, I continue with:
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
Create a new array to store the cell values of a row
$arr_row = array();
Loop through the rows
for ($rownumber = 2; $rownumber <= $highestRow; $rownumber++){
$row = $sheet->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
Then loop through the cells of the current row
foreach ($cellIterator as $cell) {
Find cells with a formula
$cellcheck = substr($cell->getValue(),0,1);
if($cellcheck == '='){
$cell_content = $cell->getOldCalculatedValue();
}
else{
$cell_content = $cell->getValue();
}
Add the cell values to the array
array_push($arr_row,$cell_content);
Close cell loop
}
At this point I use the $arr_row to do further calculations and string formatting, before finally inserting it into a mysql table.
Close row loop
}
I made some changes in the function rangeToArray() inside Worksheet.php.
Worked fine!
public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Returnvalue
$returnValue = array();
// Identify the range that we need to extract from the worksheet
list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange);
$minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1);
$minRow = $rangeStart[1];
$maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1);
$maxRow = $rangeEnd[1];
$maxCol++;
// Loop through rows
$r = -1;
for ($row = $minRow; $row <= $maxRow; ++$row) {
$rRef = ($returnCellRef) ? $row : ++$r;
$c = -1;
// Loop through columns in the current row
for ($col = $minCol; $col != $maxCol; ++$col) {
$cRef = ($returnCellRef) ? $col : ++$c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
// so we test and retrieve directly against _cellCollection
if ($this->_cellCollection->isDataSet($col.$row)) {
// Cell exists
$cell = $this->_cellCollection->getCacheData($col.$row);
if ($cell->getValue() !== null) {
if ($cell->getValue() instanceof PHPExcel_RichText) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
} else {
if ($calculateFormulas)
{ ##################################### CHANGED LINES
if(!preg_match('/^[=].*/', $cell->getValue()))
{
$returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); # THE ORIGINAL CODE ONLY HAD THIS LINE
}
else
{
$returnValue[$rRef][$cRef] = $cell->getOldCalculatedValue();
}
} ##################################### CHANGED LINES
else
{
$returnValue[$rRef][$cRef] = $cell->getValue();
}
}
if ($formatData) {
$style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString(
$returnValue[$rRef][$cRef],
($style && $style->getNumberFormat()) ?
$style->getNumberFormat()->getFormatCode() :
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
}
} else {
// Cell holds a NULL
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
// Cell doesn't exist
$returnValue[$rRef][$cRef] = $nullValue;
}
}
}
// Return
return $returnValue;
}

Resources