Cannot reverse output, tried with array_reverse and usort.
I'm trying to import products from an XML to Magento with magmi datapump, works fine but I need the output in reverse order for Magento to link simple products with configurable products,
Any ideas?
$xml = simplexml_load_file("23.xml") or die("Error: Cannot create object");
foreach($xml->wapiitems->record as $book) {
$item = $book->fields->itemno;
if (strlen($item) <= 6) {
$type = "configurable";
$ca = "color,size";}
else {
$type = "simple";
$ca = "";}
$newProductData = array(
'sku' => (string)$book->fields->itemno, // name
'type' => (string)$type, // sku
'color' => (string)$book->subtables->descriptions->record->fields->variant1name, // special price
'size' => (string)$book->subtables->descriptions->record->fields->variant3name, // price
'attribute_set' => 'Default', // attribute_set
'store' => 'admin',
'name' => (string)$book->subtables->descriptions->record->fields->description, // full description
'configurable_attributes' => (string)$ca // short description
);
//$dp->ingest($newProductData);
echo "</br>";
print_r ($newProductData);
$newProductData=null; //clear memory
unset($newProductData); //clear memory
}
unset($xml);
$dp->endImportSession(); // end import
My output is:
Array ( [sku] => 90349 [type] => configurable [color] => [size] => [attribute_set] => Default [store] => admin [name] => [configurable_attributes] => color,size )
Array ( [sku] => 903490101004 [type] => simple [color] => Red [size] => 4 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101005 [type] => simple [color] => Black [size] => 5 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101006 [type] => simple [color] => Black [size] => 6 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
But I need this:
Array ( [sku] => 903490101006 [type] => simple [color] => Black [size] => 6 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101005 [type] => simple [color] => Black [size] => 5 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 903490101004 [type] => simple [color] => Red [size] => 4 [attribute_set] => Default [store] => admin [name] => Q-Irine Cover [configurable_attributes] => )
Array ( [sku] => 90349 [type] => configurable [color] => [size] => [attribute_set] => Default [store] => admin [name] => [configurable_attributes] => color,size )
Not sure how Magmi Datapump is linking the simple and configurable products based on your example, but assuming that all that is required for your problem is that configurable products get imported after the simple products, you could do something like this:
Create an intermediate array of product records after pulling them out of XML by changing $newProductData = array(...) to $newProductData[] = array(...)
Now use something like this to sort your intermediate array by product type:
usort($newProductData, function($a, $b)
{
if ($a['type'] == 'configurable' && $b['type'] == 'simple') {
return 1;
} else if ($a['type'] == 'simple' && $b['type'] == 'configurable') {
return -1;
} else {
return strnatcmp($a['sku'], $b['sku']);
}
});
Finally, iterate over the sorted array and complete the import:
foreach ($newProductData as $data) {
$dp->ingest($data);
}
Related
this is taking more than i anticipated,
On my shopping cart app i'm able to add product to app cart session with no problem, But now i need to add product variations like (color, size, ... etc) for every product added to the cart, These variation can change to product price according to users selection on product details page.
The code that i have currently is working for me except that i can't add a list of variation for a single product i can only create one variation then the code is replacing it with new variation value.
This is my cart object when running {{print_r($cart)}}
App\Cart Object
(
[items] => Array
(
[27] => Array
(
[id] => 27
[name] => product with variation and colors
[slug] => iphone-pro13
[price] => 100
[prefix] => QAR
[qty] => 1
[poster] => /image/md/9964677a-c957-4510-9eb4-f41578c069b3
[subtotal] => 730
[quotable] => 0
[variations] => Array // these are the list of product variations
(
[16] => Array
(
[id] => 16
[var_name] => This is the variation
[var_price] => 365.00
[var_qty] => 1
[var_subtotal] => 365
[color_code] => #e6bf00
)
)
)
[12] => Array
(
[id] => 12
[name] => Dolore quis sunt reiciendis.
[slug] => iste-autem-beatae-eaque-natus-distinctio
[price] => 96.08
[prefix] => QAR
[qty] => 1
[poster] => /media/default/product-placeholder.jpg
[subtotal] => 350.692
[quotable] => 0
[variations] => Array // these are the list of product variations
(
[0] => Array
(
[var_name] => This is the variation 2
[var_price] => 335.00
[var_qty] => 1
[var_subtotal] => 365
[color_code] => #e6bf00
)
)
)
)
the is my cart.php class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart extends Model
{
public $items = null;
public $itemsCount = 0;
public $grandTotal = 0;
public $variations = null;
public function __Construct($oldCart = null) {
if($oldCart) {
$this->items = $oldCart->items;
$this->itemsCount = $oldCart->itemsCount;
$this->grandTotal = $oldCart->grandTotal;
$this->variations = $oldCart->variations;
}
}
public function add($product) {
if (isset($this->items)) {
if( array_key_exists($product->id, $this->items) ) {
$qty = $this->items[$product->id]['qty'] += $product->qty;
$subtotal = $qty * $product->price;
}else{
$qty = $product->qty;
$subtotal = $product->subtotal;
}
}else{
$qty = $product->qty;
$subtotal = $product->subtotal;
}
$item = [
'id' => $product->id,
'name' => $product->name,
'slug' => $product->slug,
'price' => $product->price,
'prefix' => $product->prefix,
'qty' => $qty,
'poster' => $product->poster,
'subtotal' => $subtotal,
'quotable' => $product->quotable,
];
$variations = [
'id' => $product->variation_id,
'var_name' => $product->variation,
'var_price' => $product->variation_price,
'var_qty' => $qty,
'var_subtotal' => $qty * $product->variation_price,
'color_code' => $product->color,
];
$this->items[$product->id] = $item; // <-- this adds new product
$this->items[$product->id]['variations'][$product->variation_id] = $variations; // <-- this adds new product variation
$this->itemsCount +=1;
$this->grandTotal += $product->price * $product->qty;
}
}
Not sure where my code went wrong but i need to be able to add list of product variations instead of replacing current ones.
any ideas?
In laravel 8 app I use spatie/laravel-medialibrary 9
and how can I check that file returned by getUrl really exists under storage in code :
foreach (Auth::user()->getMedia('avatar') as $mediaImage) {
\Log::info( varDump($mediaImage, ' -1 $mediaImage::') );
return $mediaImage->getUrl();
}
?
$mediaImage var has data like:
Array
(
[id] => 11
[model_type] => App\Models\User
[model_id] => 1
[uuid] => 2fb4fa16-cbdc-4902-bdf5-d7e6d738d91f
[collection_name] => avatar
[name] => b22de6791bca17184093c285e1c4b4b5
[file_name] => avatar_111.jpg
[mime_type] => image/jpg
[disk] => public
[conversions_disk] => public
[size] => 14305
[manipulations] => Array
(
)
[custom_properties] => Array
(
)
[generated_conversions] => Array
(
)
[responsive_images] => Array
(
)
[order_column] => 1
[created_at] => 2021-12-30T14:08:11.000000Z
[updated_at] => 2021-12-30T14:08:11.000000Z
[original_url] => http://127.0.0.1:8000/storage/Photos/11/avatar_111.jpg
[preview_url] =>
)
Looks like nothing about file under storage...
Thanks!
Method :
File::exists($mediaImage->getPath());
helped me!
I have a small problem programming with the use of UploadField . I have created pages to make a light CMS on the FrontEnd. But I don't know how retrieve this image to the page «Update».
There is the code from the page «Create» :
$uploadField = new UploadField( 'ImageEvenement', 'Image' );
There is the code I tried to get working for the page «Update»
$evenID = Session::get('evenementID');
$evenement = Versioned::get_by_stage('PageCalendrierEvenement', 'Stage')->byID($evenID);
..
$SavedImage = File::get()->byID($evenement->ImageEvenementID)
$uploadField = new UploadField( 'ImageEvenement', 'Image', $SavedImage );
How can I retrieve the submitted image to $SavedImage ? My idea to get the ID from File don't work.
Another method :
$SavedImage = $evenement->ImageEvenement();
If I dump data from $SavedImage I'm viewing :
Image Object
(
[destroyed] =>
[model:protected] => DataModel Object
(
[customDataLists:protected] => Array
(
)
)
[record:protected] => Array
(
[ClassName] => Image
[Created] => 2015-07-15 14:41:24
[LastEdited] => 2015-07-16 15:03:25
[Name] => images.jpg
[Title] => images
[Filename] => assets/Membres/9/calendrier/images.jpg
[ShowInSearch] => 1
[ParentID] => 15
[OwnerID] => 9
[ID] => 22
[RecordClassName] => Image
)
[changed:DataObject:private] => Array
(
)
[original:protected] => Array
(
[ClassName] => Image
[Created] => 2015-07-15 14:41:24
[LastEdited] => 2015-07-16 15:03:25
[Name] => images.jpg
[Title] => images
[Filename] => assets/Membres/9/calendrier/images.jpg
[ShowInSearch] => 1
[ParentID] => 15
[OwnerID] => 9
[ID] => 22
[RecordClassName] => Image
)
[brokenOnDelete:protected] =>
[brokenOnWrite:protected] =>
[components:protected] =>
[unsavedRelations:protected] =>
[sourceQueryParams:protected] =>
[failover:protected] =>
[customisedObject:protected] =>
[objCache:ViewableData:private] => Array
(
)
[class] => Image
[extension_instances:protected] => Array
(
[BetterButtonDataObject] => BetterButtonDataObject Object
(
[owner:protected] =>
[ownerBaseClass:protected] => DataObject
[ownerRefs:Extension:private] => 0
[class] => BetterButtonDataObject
)
[SiteTreeFileExtension] => SiteTreeFileExtension Object
(
[owner:protected] =>
[ownerBaseClass:protected] => File
[ownerRefs:Extension:private] => 0
[class] => SiteTreeFileExtension
)
[Hierarchy] => Hierarchy Object
(
[markedNodes:protected] =>
[markingFilter:protected] =>
[_cache_numChildren:protected] =>
[owner:protected] =>
[ownerBaseClass:protected] => File
[ownerRefs:Extension:private] => 0
[class] => Hierarchy
)
)
[beforeExtendCallbacks:protected] => Array
(
)
[afterExtendCallbacks:protected] => Array
(
)
)
Any idea?
class PageCalendrierEvenement extends Page {
private static $db = array(
"Titre" => "Varchar(50)",
"DateDepart" => "Date",
"DateFin" => "Date",
);
private static $has_one = array(
'Creator' => 'Member',
'ImageEvenement' => 'Image',
);
..
}
Thank you!
has one relations need the "ID" suffix in the name of the relation (as it's saved to db...), e.g.
$uploadField = new UploadField( 'ImageEvenementID', 'Image', $SavedImage );
then it should save automatically.
OR, what i do for a single relation:
$imageField = UploadField::create('ImageEvenement', 'Image');
$imageField->setAllowedFileCategories('image');
$imageField->setAllowedMaxFileNumber(1);
hope that helps.
My code works fine but are not clean and not using SilverStripe function classes. The reason for non working saving images to dataobject, is because that I have not use :
$form->saveInto($evenement)
I would like to thank you Wmk for give me the get method to fill form with values on another post :
$form->loadDataForm($evenement)
Finaly, all works fine now!
Finaly after long time brain searching, I have found the trick! The command to use with UploadField is setValue($value) with fileIDs include with it. My final code is :
$evenement = Versioned::get_by_stage('PageCalendrierEvenement', 'Stage')->byID($evenID);
...
$uploadField = new UploadField( 'ImageEvenement', 'Image' );
$data['ImageID'] = $evenement->ImageEvenement()->ID;
$fileIDs[]=$data['ImageID'];
$uploadField->setValue(array('Files' => $fileIDs));
Thats it!
I am trying to implement an admin module in magento which has a grid in the first page and grids in the tabs while editing the grid entities.
The main grid works fine, but the grids in the tabs are not working fine.
The problem I found while I debugged the code is that, I am loading the collection in the grid with field filtering, ie I am filtering the collection with filter that is the user id. I did this because I need only data of a single user from the table. This made the entire problem, the data in the grid is coming correctly, but the filtering,sorting and searching feature inside grid is not working and returning a 404 not found error page. I tried removing the field filter I added while getting the collection, then it works fine but all the data in the table is coming which is the opposite to my requirement.
Is there any possible solution to this. Here is the way I am trying to do:
protected function _prepareCollection() {
$collection = Mage::getModel('merchant/subscriptions')->getCollection()->addFieldToFilter('user_id', Mage::registry('merchant_data')->getId());
$this->setCollection($collection); //Set the collection
return parent::_prepareCollection();
}
Thanks in advance.
ok My problem is solved there is a mistake in my code. In the grid file the function below was wrong.
public function getGridUrl() {
return $this->getUrl('*/*/transactiongrid', array('user_id',Mage::registry('merchant_data')->getId(), '_current' => true));
}
The correct method was
public function getGridUrl() {
return $this->getUrl('*/*/transactiongrid', array('user_id'=> Mage::registry('merchant_data')->getId(), '_current' => true));
}
Filter action is dependent on your below method:
public function getGridUrl() {
return $this->getUrl('*/*/grid', array('user_id' => Mage::registry('merchant_data')->getId(),'_current'=>true));
}
now this is how you will prepare collection:
protected function _prepareCollection()
{
$regData = Mage::registry('merchant_data');
if(isset($regData))
$regData = $regData->getId();
else
$regData = $this->getRequest()->getParam('user_id');
$collection = Mage::getModel('merchant/subscriptions')->getCollection()->addFieldToFilter('user_id',$regData);
...
When I dumped $regData I got this:
Cubet_Merchant_Model_Merchant Object
(
[_eventPrefix:protected] => core_abstract
[_eventObject:protected] => object
[_resourceName:protected] => merchant/merchant
[_resource:protected] =>
[_resourceCollectionName:protected] => merchant/merchant_collection
[_cacheTag:protected] =>
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[user_id] => 3
[firstname] => Robin
[lastname] => Cubet
[email] => robin#cubettech.com
[username] => robincubet
[password] => 51a7f45eb11fc49b5967a0039193c3ad:HSX8JkSO5lr3uaRHrzd86i7gb0RATeDb
[created] => 2013-12-12 08:34:28
[modified] => 2013-12-16 09:03:56
[logdate] =>
[lognum] => 0
[reload_acl_flag] => 1
[is_active] => 1
[extra] => N;
[rp_token] =>
[rp_token_created_at] =>
)
[_hasDataChanges:protected] =>
[_origData:protected] => Array
(
[user_id] => 3
[firstname] => Robin
[lastname] => Cubet
[email] => robin#cubettech.com
[username] => robincubet
[password] => 51a7f45eb11fc49b5967a0039193c3ad:HSX8JkSO5lr3uaRHrzd86i7gb0RATeDb
[created] => 2013-12-12 08:34:28
[modified] => 2013-12-16 09:03:56
[logdate] =>
[lognum] => 0
[reload_acl_flag] => 1
[is_active] => 1
[extra] => N;
[rp_token] =>
[rp_token_created_at] =>
)
[_idFieldName:protected] => user_id
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)
I want to delete empty categories, using the following code:
`<?php
require "app/Mage.php";
umask(0);
Mage::app();
$categoryCollection = Mage::getModel('catalog/category')->getCollection()->addFieldToFilter('level', array('gteq' => 2));
foreach($categoryCollection as $category) {
if ($category->getProductCount() === 0) {
print_r ($category);
echo "<br><hr><br>";
$category->delete();
}
}
echo 'End!';
?>`
Upon executing this code, it crashes at delete.
print_r gives the following result:
Mage_Catalog_Model_Category Object (
[_eventPrefix:protected] => catalog_category
[_eventObject:protected] => category
[_cacheTag:protected] => catalog_category
[_useFlatResource:protected] => 1
[_designAttributes:Mage_Catalog_Model_Category:private] => Array (
[0] => custom_design
[1] => custom_design_from
[2] => custom_design_to
[3] => page_layout
[4] => custom_layout_update
[5] => custom_apply_to_products
)
[_treeModel:protected] =>
[_defaultValues:protected] => Array (
)
[_storeValuesFlags:protected] => Array (
)
[_lockedAttributes:protected] => Array (
)
[_isDeleteable:protected] => 1
[_isReadonly:protected] =>
[_resourceName:protected] => catalog/category_flat
[_resource:protected] =>
[_resourceCollectionName:protected] => catalog/category_flat_collection
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array (
[entity_id] => 53
[level] => 4
[path] => 1/2/27/39/53
[position] => 3
[is_active] => 1
[is_anchor] => 1
[product_count] => 0
)
[_hasDataChanges:protected] => 1
[_origData:protected] => Array (
[entity_id] => 53
[level] => 4
[path] => 1/2/27/39/53
[position] => 3
[is_active] => 1
[is_anchor] => 1
)
[_idFieldName:protected] => entity_id
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array (
)
[_syncFieldsMap:protected] => Array (
)
)
What am I doing wrong, and how should I do it?
Any help would be greatly appreciated.
<?php
require "app/Mage.php";
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$categoryCollection = Mage::getModel('catalog/category')->getCollection()->addFieldToFilter('level', array('gteq' => 2));
foreach($categoryCollection as $category) {
if ($category->getProductCount() === 0) {
print_r ($category->entity_id);
echo "<br><hr><br>";
$category->delete();
}
}
echo 'End!';
?>
You have to add this line
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
you write this code print_r ($category); so its reruns the array. That is not error.