How to create in Magento with custom code? - magento

I am using this code to create categories and subcategories. This code works fine but the problem is I can't create my own category codes. And I need it to use it for the requeriments.
$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // 0 = default/all store view. If you want to save data for a specific store view, replace 0 by Mage::app()->getStore()->getId().
//if update
if ($id) {
$category->load($id);
}
$general['name'] = "My Category";
$general['path'] = "1/3/"; // catalog path here you can add your own ID
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['landing_page'] = ""; //has to be created in advance, here comes id
$general['display_mode'] = "PRODUCTS"; //static block and the products are shown on the page
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['page_layout'] = 'two_columns_left';
//$general['url_key'] = "cars";//url to be used for this category's page by magento.
//$general['image'] = "cars.jpg";
$category->addData($general);
try {
$category->setId(255); // Here you cant set your own entity id
$category->save();
echo "Success! Id: ".$category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
I tried to do something like that:
$general['id'] = $myCustomId;
But it's not working.

The key needs to map the column header, which is entity_id. So, change $general['id'] to
$general['entity_id'] = $myCustomId;

Related

Import Profile Product Review import/export

I'm using Magento extension https://www.magentocommerce.com/magento-connect/product-review-import-export.html for importing prodcuts review.
I've exported review from one Magento site and I'm trying to import on another website.
While importing products it's show message "Processed 0% 0/1 records" and keep it showing, No process in importing products.
Importing Preview
I've changed my table prefix in "app/code/local/MK/Reviewexport/Model/Convert/Adapter/Reviewimport.php" but still nothing happening.
Waited too long but it keep showing me "Processed 0% 0/1 records" I've too many reviews and so it was not working I've removed all reviews from CSV and kept only one review.
This extension is created by : https://magento.stackexchange.com/users/599/mufaddal
Anyways I've resolved the issue by making custom script for importing reviews which is exported by that mentioned extension.
Here is a code
<?php
ini_set('memory_limit', '128M');
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'app/Mage.php';
Mage::app();
$fileLocation = "var/import/import_review.csv";
$fp = fopen($fileLocation, 'r');
$count = 1;
while($data = fgetcsv($fp)){
if($count > 1){
//intiate requirement varibles
$_createdAt = $data[0];
$_sku = $data[1];
$_catalog = Mage::getModel('catalog/product');
$_productId = $_catalog->getIdBySku($_sku);
$_statusId = $data[2];
$_title = $data[3];
$_detail = $data[4];
$_customerId = NULL;
$_nickname = $data[5];
//load magento review model and assign values
$review = Mage::getModel('review/review');
$review->setCreatedAt($_createdAt); //created date and time
$review->setEntityPkValue($_productId);//product id
$review->setStatusId($_statusId); // status id
$review->setTitle($_title); // review title
$review->setDetail($_detail); // review detail
$review->setEntityId(1); // leave it 1
$review->setStoreId(Mage::app()->getStore()->getId()); // store id
$review->setCustomerId($_customerId); //null is for administrator
$review->setNickname($_nickname); //customer nickname
$review->setReviewId($review->getId());//set current review id
$review->setStores(array(Mage::app()->getStore()->getId()));//store id's
$review->save();
$review->aggregate();
//set review ratings
if($data[7]){
$arr_data = explode("#",$data[7]);
if(!empty($arr_data)) {
foreach($arr_data as $each_data) {
$arr_rating = explode(":",$each_data);
if($arr_rating[1] != 0) {
Mage::getModel('rating/rating')
->setRatingId($arr_rating[0])
->setReviewId($review->getId())
->setCustomerId($_customerId)
->addOptionVote($arr_rating[1], $_productId);
}
}
}
$review->aggregate();
}
}
// if($count == 5){
// die("total $count reviews are imported!");
// }
$count++;
}
echo "total $count reviews are imported!";
?>

Magento re-generate url-keys for categories

I must re-generate all url-keys for all categories.
When I added some main categories i copied them using one of way from forum.
Everything was going ok, but when i’m copied about 20k categories i saw: when the name has polish letter the rest was cutted:
Example:
name of category: Części karoseryjne
should be: czesci-karoseryjne
after copy: cz
name of category: Próg zwalniajacy
should be: prog-zwalniajacy
after copy: pr
I’m found on polish forum the way to fix it (with polish letters), but it works only with new added categories.
Now, when i select any category, clear the url-key and click save - the naming is ok, but ....... there is 20k categories…
Can somebody write how to fix it ?
http://www.errorin.com/open-source/how-to-add-category-programmatically-in-magento-1-7-0-with-custom-field/
require_once 'app/Mage.php';
Mage::app('default'); // Default or your store view name.
//get a new category object
$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // 0 = default/all store view. If you want to save data for a specific store view, replace 0 by Mage::app()->getStore()->getId().
//if update
if ($id) {
$category->load($id);
}
$general['name'] = "My Category";
$general['path'] = "1/2/23"; // catalog path
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['landing_page'] = ""; //has to be created in advance, here comes id
$general['display_mode'] = "PRODUCTS_AND_PAGE"; //static block and the products are shown on the page
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['page_layout'] = 'two_columns_left';
//$general['url_key'] = "cars";//url to be used for this category's page by magento.
//$general['image'] = "cars.jpg";
$category->addData($general);
try {
$category->save();
echo "Success! Id: ".$category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}

Magento: get max and min price for bundle product

I tried several ideas I could find at google, but no one did work for me for few days. Finally I found a way to display in a custom extension the "minimal possible price" and the "maximal possible price" for a bundle product in magento:
$_product_id = YOUR_BUNDLE_PRODUCT_ID;
// highest possible price for this bundle product
$return_type = 'max'; // because I used this in a helper method
// lowest possible price for this bundle product
// $return_type = 'min';
$model_catalog_product = Mage::getModel('catalog/product'); // getting product model
$_product = $model_catalog_product->load( $_product_id );
$TypeInstance = $_product->getTypeInstance(true);
$Selections = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions = $Options->appendSelections($Selections, true);
$minmax_pricevalue = 0; // to sum them up from 0
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
$pricevalues_array = array();
foreach ($bundleSelections as $bundleSelection) {
$pricevalues_array[] = $bundleSelection->getPrice();
}
if ( $return_type == 'max' ) {
rsort($pricevalues_array); // high to low
} else {
sort($pricevalues_array); // low to high
}
// sum up the highest possible or lowest possible price
$minmax_pricevalue += $pricevalues_array[0];
}
}
// echo $minmax_pricevalue;
echo ''.Mage::helper('core')->currency($minmax_pricevalue, true, false).'';
If you have better and shorter ways feel free to post here. Thanks to all involved!
Background of all was that, I have made a custom extension and wanted also to show there the "minimal possible price" and the "maximal possible price" for such a configuration. Magento-Setup was: Native "bundle product" several "Bundle Items Options" connected my "bundle product". Each "bundle option" has multiple simple products with different prices in it. I think that was the point here.
Hope that all helps someone - love to share such stuff :-)
Magento has build in function for that purpose:
Mage::getModel('bundle/product_price')->getTotalPrices($_product,'min',1);
Here once again the final working code:
$_product_id = YOUR_BUNDLE_PRODUCT_ID;
// highest possible price for this bundle product
$return_type = 'max'; // because I used this in a helper method
// lowest possible price for this bundle product
// $return_type = 'min';
$model_catalog_product = Mage::getModel('catalog/product'); // getting product model
$_product = $model_catalog_product->load( $_product_id );
$TypeInstance = $_product->getTypeInstance(true);
$Selections = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions = $Options->appendSelections($Selections, true);
$minmax_pricevalue = 0; // to sum them up from 0
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
$pricevalues_array = array();
foreach ($bundleSelections as $bundleSelection) {
$pricevalues_array[] = $bundleSelection->getPrice();
}
if ( $return_type == 'max' ) {
rsort($pricevalues_array); // high to low
} else {
sort($pricevalues_array); // low to high
}
// sum up the highest possible or lowest possible price
$minmax_pricevalue += $pricevalues_array[0];
}
}
// echo $minmax_pricevalue;
echo ''.Mage::helper('core')->currency($minmax_pricevalue, true, false).'';
I had a similar problem a while back and came up with this (with some help from Inchoo's blog for getting the bundled product collection). It loads all of the bundled products associated with the main product_id into an array. By sorting the array you get the min on the bottom and max at the end which I retrieved with $bundled_prices[0] and array_slice($bundled_prices, -1, 1, false).
$product_id = YOUR_PRODUCT_ID;
$bundled_product = new Mage_Catalog_Model_Product();
$bundled_product->load($product_id);
$selectionCollection = $bundled_product->getTypeInstance(true)->getSelectionsCollection(
$bundled_product->getTypeInstance(true)->getOptionsIds($bundled_product), $bundled_product
);
$bundled_items = array();
foreach($selectionCollection as $option) {
if ($option->getPrice()!="0.0000"){
$bundled_prices[]=$option->getPrice();
}
}
sort($bundled_prices);
$min_price=$bundled_prices[0];
$max_price_tmp=array_slice($bundled_prices, -1, 1, false);
$max_price=$max_price_tmp[0];
echo "Min: " . $min_price . '<br>';
echo "Max: " . $max_price;

Magento : Display html element based on product attribute set?

I wish to display a static block on the product page if the product belongs to a certain Attribute Set
For example if I was a fashion store, and I have an attribute set of "Footwear" I only want the static block to show on product pages when the attribute set matches "Footwear"
I have found a little bit of code that outputs the ID of the Attribute set but I want to turn it into an else if statement.
<?php
$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = 'Footwear';
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();
echo $attributeSetId;
?>
Anyone have any ideas?
G
Add this method to the Product View Block
(not to core file app/code/core/Mage/Catalog/Block/Product/View.php of course):
public function checkAttributeSet($product = null, $attributeSetName = null)
{
if(is_null($product) || is_null($attributeSetName))
return false;
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
if($attributeSetModel->getAttributeSetName() == $attributeSetName) {
return true;
} else {
return false;
}
}
Then in app/design/frontend/package/theme/template/catalog/product/view.phtml:
if($this->checkAttributeSet($_product, 'Monitors')):
echo $this->getLayout()->createBlock('cms/block')->setBlockId('monitor')->toHtml();
elseif($this->checkAttributeSet($_product, 'Footwear')):
echo $this->getLayout()->createBlock('cms/block')->setBlockId('footwear')->toHtml();
endif;
FOR THE ADMINS WHO DELETE USEFUL INFORMATION FOR POINTS ON STACKOVERFLOW >>>> 3rd time replying to this post with updated material ya know just incase someone stumbles on this thread.
This is the updated magento 2.3 way of completing this task.
Add code to
module-catalog/view/frontend/templates/product/view
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeSet = $objectManager->create('Magento\Eav\Api\AttributeSetRepositoryInterface');
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId());
$attributeSetRepository = $attributeSet->get($product->getAttributeSetId());
$attribute_set_name = $attributeSetRepository->getAttributeSetName();
//$attribute_set_name_arr[] = $attribute_set_name;
//echo '<pre>'; print_r($attribute_set_name);
if( !empty($attribute_set_name) && $attribute_set_name == 'Rc' ) {
// echo $this->getLayout()
->createBlock('Magento\Cms\Block\Block')
->setBlockId('rcitems')
->toHtml();
}
?>
setBlockId = The Identifier of the block in admin.
Rc = is the attribute set
no need to add to default.xml

TYPO3 Extbase: How to render the pagetree from my model?

I want to create some kind of sitemap in extbase/fluid (based on the pagetree). I have loaded the pages table into a model:
config.tx_extbase.persistence.classes.Tx_MyExt_Domain_Model_Page.mapping.tableName = pages
I have created a controller and repository, but get stuck on the part wich can load the subpages as relation into my model.
For example:
$page = $this->pageRepository->findByPid($rootPid);
Returns my rootpage. But how can I extend my model that I can use $page->getSubpages() or $page->getNestedPages()?
Do I have to create some kind of query inside my model? Or do I have to resolve this with existing functions (like the object storage) and how?
I tried a lot of things but can simply figure out how this should work.
you have to overwrite your findByPid repository-method and add
public function findByPid($pid) {
$querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->setDefaultQuerySettings($querySettings);
$query = $this->createQuery();
$query->matching($query->equals('pid', $pid));
$pages = $query->execute();
return $pages;
}
to get all pages. Than you can write your own getSubpages-method like
function getSubpages($currentPid) {
$subpages = $this->pagesRepository->findByPid($currentPid);
if (count($subpages) > 0) {
$i = 0;
foreach($subpages as $subpage) {
$subpageUid = $subpage->getUid();
$subpageArray[$i]['page'] = $subpage;
$subpageArray[$i]['subpages'] = $this->getSubpages($subpageUid);
$i++;
}
} else {
$subpageArray = Array();
}
return $subpageArray;
}
i didn't test this method, but it looks like this to get alle subpages.
i wonder that i could´t find a typo3 method that return the complete Page-Tree :( So i write a little function (you can use in an extbase extension), for sure not the best or fastes way, but easy to extend or customize ;)
first you need an instance of the PageRepository
$this->t3pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
this->t3pageRepository->init();
make the init, to set some basic confs, like "WHERE deletet = 0 AND hidden = 0..."
then with this function you get an array with the page data and subpages in. I implement yust up to three levels:
function getPageTree($pid,$deep=2){
$fields = '*';
$sortField = 'sorting';
$pages = $this->t3pageRepository->getMenu($pid,$fields,$sortField);
if($deep>=1){
foreach($pages as &$page) {
$subPages1 = $this->t3pageRepository->getMenu($page['uid'],$fields,$sortField);
if(count($subPages1)>0){
if($deep>=2){
foreach($subPages1 as &$subPage1){
$subPages2 = $this->t3pageRepository->getMenu($subPage1['uid'],$fields,$sortField);
if(count($subPages2>0)){
$subPage1['subpages'] = $subPages2;
}
}
}
$page['subpages'] = $subPages1;
}
}
}
return $pages;
}

Resources