I need to sort region drop down in one page checkout page. I found data coming from 'Mage_Directory_Helper_Data' I need to sort this data. I tried by adding below code:
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->addOrder('default_name', 'DESC')
->load();
But it did not work. Can anyone please help me. Thank You.
Try
if (empty($json)) {
$countryIds = array();
foreach ($this->getCountryCollection() as $country) {
$countryIds[] = $country->getCountryId();
}
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->setOrder('default_name','DESC')
->load();
$regions = array(
'config' => array(
'show_all_regions' => $this->getShowNonRequiredState(),
'regions_required' => $this->getCountriesWithStatesRequired()
)
);
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
'name' => $this->__($region->getName())
);
}
krsort($regions); // or ksort($regions)
$json = Mage::helper('core')->jsonEncode($regions);
}
Related
I have for each of value from color of my product. Any product can gives to many color
this color save it in interface table with for each .
my store for each
foreach ($request->addcolor as $colorss) {
foreach ($colorss as $item){
if(!empty($item['color_id'])){
$color = ColorProduct::create([
'product_id' => $product->id,
'color_id' => $item['color_id'],
'color_body'=>$request->input('color_body'),
'color_handle' => $request->input('color_handle'),
'color_handle_head' => $request->input('color_handle_head'),
'productable' => Product::class
]);
}
}
}
I wrote update this for each
if($request->addcolor ){
$color_product = ColorProduct::where('product_id' , $product->id)->get();
foreach ($request->addcolor as $keys => $colorsis) {
$color = $color_product->where('color_id' , $keys)->first();
if ($color) {
foreach ($request->addcolor as $colorss) {
foreach ($colorss as $item){
if(!empty($item['color_id'])){
$item['color_id'] = $request->input ('color_id');
$item['color_body']= $request->input('color_body');
$item['color_handle'] = $request->input('color_handle');
$item['color_handle_head'] = $request->input('color_handle_head');
}
}
}
} else {
foreach ($colorss as $procol){
if(!empty($procol['color_id'])){
$color = ColorProduct::create([
'product_id' => $product->id,
'color_id' => $procol['color_id'],
'productable' => Product::class
]);
}
}
}
}
$duplicateArgs= DB::table('color_products')
->select('product_id' , 'color_id' , DB::raw('count(*) as total'))
->groupBy('product_id' , 'color_id')
->get();
foreach ($duplicateArgs as $item){
if($item->total>1){
for ($i = 1; $i < $item->total; $i++){
$duplicate = ColorProduct::where('product_id' , $item->product_id)
->where('color_id' , $item->color_id)->orderBy('id' , 'Desc')->first();
$duplicate->delete();
}
}
}
how can update color body, color handle, color handle head ?I can only update color id
thanks for your help
I am a little unclear of the data structure here, but maybe you need to do something like this in your first foreach?
$color->update([
'color_id' = $request->input ('color_id'),
'color_body' = $request->input('color_body'),
'color_handle' = $request->input('color_handle'),
'color_handle_head' = $request->input('color_handle_head')
]);
I am trying to Add Products to Cart with respect to customer (programmatically) but getting error "Invalid request for adding product to quote". I have both Simple products (with custom options) and configurable products. Below is my code. Please help. Many thanks in advance.
public function addtocartAction(){
try {
$cusId = $this->getRequest()->getParam('cusId');
$customer = Mage::getModel('customer/customer')->load($cusId);
$quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
$quoteId = $quote->getId();
//$products = $this->getRequest()->getParam('products');
$products = json_decode('[{"proId": "906","proQty": "1", "options":{"17":"wq","16":"18"}}]');
foreach($products as $product) {
/*if (!$product->getId()) {
throw new Exception();
}*/
foreach ($product->options as $optKey => $optValue) {
$optAll[$optKey] = $optValue;
}
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
'product' => $product->proId,
'qty' => $product->proQty,
'options' => $optAll
);
echo "<pre />"; print_r($params);
$quote->addProduct($mainProduct, $params);
$quote->setIsActive(1);
$quote->collectTotals()->save();
}
$rslt['success'] = '1';
$rslt['message'] = 'Product has been succefully added to cart';
}
catch(Exception $e){
$rslt['success'] = '0';
$rslt['message'] = $e->getMessage();
}
print_r(json_encode($rslt));
}
Try using cart instead of quote.
This works for me:
$cart = Mage::getModel('checkout/cart');
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
'product' => $product->proId,
'qty' => $product->proQty,
'options' => $optAll
);
$cart->init();
$cart->addProduct($mainProduct, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
I am creating simple products and then configurable product followed by associating simple products with configurable product. When I run the code for the first time, it works smoothly creating all simple products, configurable product and also an association. But, when I run that code again it says constraint violation. The ID that shows duplicated is the same product ID that was created the last time, when all process were ok.
My code is the following one.
$product_collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$toinsertId = $product_collection->getLastItem()->getId() + 1;
$configurable_attribute = "art_print_sizes";
$attr_id = 133;
$simpleProducts = array();
$lowestPrice = 999999;
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray = array();
foreach ($attributes as $a) {
if ($a->getAttributeCode() == 'art_print_sizes') {
$count = 0;
foreach ($a->getSource()->getAllOptions(false) as $option) {
$option_id = $this->getOptionId("art_print_sizes", $option['label']);
$sku = 'SK_' . '500' . '_' . strval($count);
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setWebsiteIds(array(1))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setTaxClassId(5)
->setAttributeSetId(9)
->setSku($sku)
// $main_product_data is an array created as part of a wider foreach loop, which this code is inside of
->setName($wholedata['name'] . " - " . $option['label'])
->setShortDescription($wholedata['short_description'])
->setDescription($wholedata['description'])
->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count]))
->setData($configurable_attribute, $option_id);
$sProduct->save();
array_push(
$simpleProducts,
array(
"id" => $sProduct->getId(),
"price" => $sProduct->getPrice(),
"attr_code" => 'art_print_sizes',
"attr_id" => $attr_id,
"value" => $option_id,
"label" => $option['label']
)
);
$count++;
}
}
}
$cProduct = Mage::getModel('catalog/product');
$productData = array(
'name' => 'Main configurable Tshirt',
'sku' => 'tshirt_sku',
'description' => 'Clear description about your Tshirt that explains its features',
'short_description' => 'One liner',
'weight' => 1,
'status' => '1',
'visibility' => '4',
'attribute_set_id' => 9,
'type_id' => 'configurable',
'price' => 1200,
'tax_class_id' => 0
);
foreach ($productData as $key => $value) {
$cProduct->setData($key, $value);
}
$cProduct->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 0,
'use_config_manage_stock' => 0
)
);
$cProductTypeInstance = $cProduct->getTypeInstance();
$attribute_ids = array(133);
$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach ($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 1;
$attributes_array[$key]['position'] = 0;
if (isset($attribute_array['frontend_label'])) {
$attributes_array[$key]['label'] = $attribute_array['frontend_label'];
} else {
$attributes_array[$key]['label'] = $attribute_array['attribute_code'];
}
}
$cProduct->setConfigurableAttributesData($attributes_array);
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array();
foreach ($attributes_array as $key => $attrArray) {
array_push(
$dataArray[$simpleArray['id']],
array(
"attribute_id" => $simpleArray['attr_id'][$key],
"label" => $simpleArray['label'][$key],
"is_percent" => 0,
"pricing_value" => $simpleArray['pricing_value'][$key]
)
);
}
}
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
The Error is like this
Product ID 126 is already added in database in previous session. And previous session went well adding all necessary products.
Magento will not allow you to update configurable products. So for resolve it just add below code
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
before
$cProduct->setConfigurableAttributesData($attributes_array);
So your final code will be
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
$cProduct->setConfigurableAttributesData($attributes_array);
Note: Change $productId variable according to your code. You have to pass product id here.
I am trying to get all product thumbs for a category product collection like that
$category = Mage::getModel('catalog/category')->load($cat_id);
$products = Mage::getResourceModel('catalog/product_collection')
->setStoreId(1)
->setPageSize(10)
->addAttributeToFilter(
'status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
)
->addAttributeToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->addCategoryFilter($category);
$productThumbs = array();
try {
foreach ($products as $product) {
$thumbUrl = $product->getThumbnailUrl(200, 60);
$productThumbs[] = array(
'entity_id' => $product->getId(),
'thumb_url' => $thumbUrl
);
}
} catch (Exception $e) {
error_log($e->getMessage());
}
It always return placeholder image urls like that...
http://magentohost/magento/media/catalog/product/cache/0/thumbnail/200x60/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/thumbnail.jpg
Don't know what I am doing wrong... Please guide.
I found that we need to load the $product before getting its thumb, like this
$product= Mage::getModel('catalog/product')->load($prod_id);
and then we can retrieve its thumb using
$thumbUrl = $product->getThumbnailUrl(200, 60);
I am trying to show the products in shopping cart in a panel which is accessible in all pages(in menu). I have accomplished it by using below
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
but i am struggling with showing the Custom option selected for each product.
I tried using
$item->getOptionList()
but its not working for me..
Please give me a hand on this.
Thanks,
Balan
I found the answer, below code would print the custom option selected
$options = array();
if ($optionIds = $item->getOptionByCode('option_ids')) {
$options = array();
foreach (explode(',', $optionIds->getValue()) as $optionId) {
if ($option = $item->getProduct()->getOptionById($optionId)) {
$quoteItemOption = $item->getOptionByCode('option_' . $option->getId());
$group = $option->groupFactory($option->getType())
->setOption($option)
->setQuoteItemOption($quoteItemOption);
$options[] = array(
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($quoteItemOption->getValue()),
'print_value' => $group->getPrintableOptionValue($quoteItemOption->getValue()),
'option_id' => $option->getId(),
'option_type' => $option->getType(),
'custom_view' => $group->isCustomizedView()
);
}
}
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options = array_merge($options, unserialize($addOptions->getValue()));
}
thanks goes to http://www.e-commercewebdesign.co.uk see
this link for reference.
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllVisibleItems() as $item) {
$options = Mage::helper('catalog/product_configuration')->getCustomOptions($item);
}