Get associated products - php

I created a new module to create a section in admin panel. This module section has a sub-section "Associated products" where I can add one or more products to each item in that module.
I am able to get the field values using functions like
$combo->getName()
$combo->getComments()
But I am not able to get the associated products to that item using
$combo->getAssociatedProducts()
What I tried is as follows:
<?php $comboCollection = Mage::getResourceSingleton('combo/combo_collection'); ?>
<?php
foreach ($comboCollection as $combo) {
zend_debug::dump($combo->getAssociatedProducts($combo)); //giving error
}
?>
PS: here $combo is not a product, it is just an item in the created module.
Explanation:

Considering that you have model/collection products for table combo_combo_product. you should get collection for products and then filter it for current combo id of combo collection in this way
foreach ($comboCollection as $combo) {
$associatedCollection = Mage::getResourceSingleton('combo/products_collection');
//$associatedCollection = Mage::getModel('combo/products')->getCollection();
$associatedCollection->addFieldToFilter('combo_id',array('eq' => $combo->getId()));
foreach{$associatedCollection as $item){
print_r($item->getData());
}
}

Related

How to add custom fields to category pages?

I have a website about HTML5 games, built with some PHP script.
One of its plugins you can create custom fields for each category page.
I created different custom fields (description text) for each category page.
But when I want to show these fields on category pages, unfortunately each category page shows all custom fields of all categories.
Here is a code I added to category.php file:
<?php
$categories = get_all_categories();
foreach ($categories as $category){
$category_info = $category->get_field('category_info');
if(is_null($category_info)){
$category_info = 'no info';
}
echo $category_info;
}
?>
I want to show only 1 custom field (which is particular to each category) in every category page.
Here is get_all_categories() default function of the script:
function get_all_categories(){
$data = Category::getList();
return $data['results'];
}
Thanks

Magento - Get the associated product attributes of an item in the wishlist

In app/code/local/Mage/Catalog/Product/Type/Configurable/Price.php, I am trying to get the attribute values of an associated product within the wishlist. I've attempted several approaches but I can only seem to produce data for the parent product.
Latest attempt
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId()) {
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $wlitem) {
$wishitem = Mage::getModel('catalog/product')->setStoreId($wlitem->getStoreId())->load($wlitem->getProductId());
//echo $wishitem->getId() . '<br>';
if($product->getId() == $wishitem->getId()) { //if the current product id equals the wishlist product id
echo $wishitem->getSku()."</br>";
}
}
}
That only gets me the parent product's sku. What I ultimately want to get is the attribute value for 2 attributes that I added for configurable products (not super attributes) but it seems that $product in Price.php only has the parent product collection.
Other Attempts:
$item_s = Mage::getModel('wishlist/item')->loadWithOptions($product->getId(), 'simple_product')->getOptionsByCode();
$simple_product = $item_s['simple_product']->getData();
$simple_product_id = $simple_product['product_id'];
$sim_product = Mage::getModel('catalog/product')->load($simple_product_id);
print_r($sim_product);
This only resulted in an error on the page.
Also:
$_item = Mage::getModel('catalog/product')->load($product->getId());
//echo $_item->getData('ppuom');
//print_r($_item);
$simpleProduct = $_item->getOptionsByCode()['simple_product']->getItem()->getProduct();
print_r($simpleProduct);
Seems as if you were most of the way there. I've tested this on my Magento site and it worked for me. It's pretty simple actually, you just have to grab the right model for that collection. Also, it seems like you're changing the pricing?!?! Be careful that your wishlist items contain the necessary attributes used in your logic.
$_item = Mage::getModel('catalog/product')->load($product->getId());
$attribute1 = $_item->getData('attribute1_code'); //see admin for attribute code
$attribute2 = $_item->getData('attribute2_code'); //see admin for attribute code
OR
Make changes to your template's wishlist files rather than the pricing logic in the code folder. You'll have access to all the data you need and it won't interfere with the price.php file which is relied on heavily in the cart and other critical areas of the website. The price in the wishlist is recalculated when it's moved to the cart anyway.

How to filter product list by category and brand in Magento soap api

I'm using Magento soap API for a mobile app and in my app I need to get products which are under a certain category and are also filtered by brand.
it is possible to get the products assigned to a category by calling catalog_category.assignedProducts but this method doesn't allow filtering by other attributes.
on the other hand we have the catalog_product.list method which can filter products by attributes but I think it can't filter products by category.
is there any way to filter products by both category and brand (an attribute)?
I ended up using foreach method to manually filter the result of catalog_category.assignedProducts method like this:
$products = $client->call($session, 'catalog_category.assignedProducts',$categoryId);
if($brandId!=null && $brandId>0)
{
$result=array();
foreach ($products as $product) {
if($product['brand']==$brandId)
array_push($result,$product);
}
}
else{
$result=$products;
}

Display 3 specific attributes on new products(with startdate)

I have a home page that displays new products, so products that have a startdate. These are in a widget.
Problem is they only display things like name, price, picture...
I would like to show 3 attributes per product, so the user instantly sees some specs of the product and can then click further to see all the details.
For example, desktops should have Processor family, harddisk capacity etc.
Laptops should display screen size etc.
Is this possible? The problem is that they have different categories so just adding the 3 attributes to the template will cause problems.
Thanks.
For each product you could check if it is a member of a certain category and then check for and display attributes based on a list in an associative array. Something like this:
$_productsCollection = $this->getLoadedProductCollection();
$_helper = $this->helper('catalog/output');
$cats = array( // keys are category IDs
1 => array('processor', 'disk', 'ram'), // attribute codes
2 => array('screen', 'weight', 'battery')
);
// loop product collection in widget
foreach ($_productsCollection as $_product) {
// loop array of categories
foreach ($cat as $cat_id => $attributes) {
// loop array of attributes if the product is in this category
if (in_array($cat_id, $_product->getAvailableInCategories())) {
foreach ($attributes as $attribute) {
if ($attr = $_product->getData($attribute)) {
$resource = $_product->getResource();
// markup and $helper to display image here
echo $resource->getAttribute($attribute)->getStoreLabel().': '.$attr;
// markup and getProductUrl() here, etc.
}
}
}
}
}
This is not tested, but might give you an idea. You would need to add in some code to handle cases where the product might be a member of multiple categories in the list.

Copy and Paste Category in Magento

I want to copy my first category to a second category in Magento.
What should I do?
Thanks,
Wesley.
By code:
<?php
$category = Mage::getModel('catalog/category')
->load(123); // The ID of the category you want to copy.
$copy = clone $category;
$copy->setId(null) // Remove the ID.
->save();
If you want to do it in a programmatic way you can use the Magento API.
Use:
catalog_category.info - to read a category
catalog_category.create - to create a new one by copying data from existing.
Here are the docs for category API
I wouldn't clone the category object, but rather do something like this (using the Magento API - http://www.magentocommerce.com/wiki/doc/webservices-api/catalog_category ):
get the category which must be copied
$source_category = Mage::getModel('catalog/category')->load($id);
Create a new category using the API
$CategoryApi = new Mage_Catalog_Model_Category_Api();
$parent_id = /* Location for the new category */
$new_category_id = $CategoryApi->create(
$parent_id,
array(
/* Attributes to fill with source category values. */
)
);
Get the source category products and place them in the new category, again with the API.
$products = $CategoryApi->assignedProducts(source_category->getId());
foreach($products as $product)
{
$CategoryApi->assignProduct($product->getId())
}
Above must be done recursively for each subcategory.
Note: Using the API ensures your code will still work when you upgrade the Magento core.
All the replies here were not complete. I did a script that does the total Creating the new category, subcategories and assigning the products to them.
public function run()
{
$categoryId = 123;
// Change this if you want the copy to be under another category than the default
$baseCategoryId = 2;
$category = Mage::getModel('catalog/category')->load($categoryId);
$defaultCategory = Mage::getModel('catalog/category')->load($baseCategoryId);
$this->duplicate($category, $defaultCategory, 1);
}
private function duplicate($categoryToClone, $parentCategory, $level)
{
// This will clone the clild and assign it to the new parent
$newCategory = clone $categoryToClone;
$newCategory->setPath($parentCategory->getPath())
->setParentId($parentCategory->getId())
->setId(null);
// Optional, Only change the new with suffix with "new" for the first
if ($level == 1) {
$newCategory->setUrlKey($categoryToClone->getUrlKey() . '-new')
->setName($categoryToClone->getName() . '(new)');
}
// Assign all products from the cloned category to the new
$newCategory->setPostedProducts($categoryToClone->getProductsPosition());
$newCategory->save();
// Applies the changes to the subcategories infinite levels
$subcategories = $categoryToClone->getChildrenCategories();
if (count($subcategories) > 0) {
foreach ($subcategories as $subcategory) {
$this->duplicate($subcategory, $newCategory, ++$level);
}
}
}
You can't with the admin interface, you need. to create a script with the category api.
Sorry you cannot copy/paste Category directly in Magento Admin panel through the interface, which Catalog Products can offer with the help of "Duplicate" button.
I suppose you will need to write a script fetching the category details by first loading the Category model with the required Category ID.
This forum post contains instructions and code for importing your categories from a CSV file.
Good luck,
JD
I think you want to export products from a specific cat and import it to another one. if it's so use the steps bellow:
login to magento backend
navigate to System -> Import/Export
Create a new advanced profile for your cat
export it
now import it in the same fashion
Sometime we need to copy same products to another category.(Like we have two stores with same category or within same store need to copy the category products to somewhere else)
Adding product from back-end is very time consuming process you can do it by code.
You can create a file in your root directory copy-products.php with the following code to copy product:
<?php
require_once ( "app/Mage.php" );
umask(0);
// Initialize Magento
Mage::app();
$category = Mage::getModel('catalog/category');
$category->load('24'); // Category id you want to copy
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$product->getId();// Now get category ids and add a specific category to them and save?
$categories = $product->getCategoryIds();
$categories[] = 29; // Category id you want to add
$product->setCategoryIds($categories);
$product->save();
}
?>

Categories