How to customize product URL? - magento

How to customize the product URL to add certain attribute such as EAN on URL part? For example I want make url like `[domain]/cars/[sku]/tata-suv.html
Thanks

So, I am gonna be short and quick here.
1) You have to customize Mage_Catalog_Model_Url::getProductRequestPath. You have add following statements.
$sku = $product->getSku();
$requestPath = 'cars/' . $sku . "/" . $requestPath;
May be Add this just before following line:
if (strlen($requestPath) > self::MAX_REQUEST_PATH_LENGTH + self::ALLOWED_REQUEST_PATH_OVERFLOW) {
$requestPath = substr($requestPath, 0, self::MAX_REQUEST_PATH_LENGTH);
}
2) Customize the collection Mage_Catalog_Model_Resource_Url::_getProducts add sku in select field list:
$select = $adapter->select()
->useStraightJoin(true)
->from(array('e' => $this->getTable('catalog/product')), array('entity_id', 'sku'))
->join(
array('w' => $this->getTable('catalog/product_website')),
'e.entity_id = w.product_id AND w.website_id = :website_id',
array()
)
->where('e.entity_id > :entity_id')
->order('e.entity_id')
->limit($this->_productLimit);
Notice, sku in array('entity_id', 'sku')

Related

How to add same name product in magento 2?

I am uploading product programmatically in Magento2 I have same name product with different SKU but when I run script Magento 2 gives an error because of Url Key :
Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'reine-de-naples-jour-nuit-8998.html-1' for key 'URL_REWRITE_REQUEST_PATH_STORE_ID
my script is those we use to save a product programmatically
<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList');
$path = $directoryList->getPath('media');
//var_dump($path); die;
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$myarray = glob("Book2.csv");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
if(count($myarray)){
/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
array_walk($csv_map, function(&$a) use ($csv_map) {
$a = array_combine($csv_map[0], $a);
});
array_shift($csv_map); # remove column header
/*End*/
$message = '';
$count = 1;
foreach($csv_map as $data){
//echo '<pre>';print_r($data);exit;
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product->setName(trim($data['Name']));
$product->setTypeId('simple');
$product->setAttributeSetId(4);
$product->setSku(trim($data['model_no']));
$product->setURL(trim($data['Name']).trim($data['model_no']));
$product->setWebsiteIds(array(1));
$product->setVisibility(4);
$product->setCreatedAt(strtotime('now'));
$product->setPrice(trim($data['price']));
//$_product->setShortDescription(trim($data['Short Description'])); // add text attribute
//$_product->setDescription(trim($data['Long Description'])); // add text attribute
$img_url = trim($data['img_big']);
//$lastWord = substr($img_url, strrpos($img_url, '/') + 1);
//copy($img_url, 'pub/media/product/');
$dir = $directoryList->getPath('media').'/big/';
$imgpath = $dir.$img_url;
//echo $imgpath; die;
/*$_product->addImageToMediaGallery($imgpath, array('image','thumbnail','small_image'), false, false); */
$product->addImageToMediaGallery($imgpath, array('image', 'small_image', 'thumbnail'), false, false);
//$_product->setImage($imgpath);
//$_product->setSmallImage($imgpath);
//$_product->setThumbnail($imgpath);
$product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
$product->save();
}
echo'success';
}
?>
please suggest how to add Url key to script my script is working fine without the same name
Have you tried omitting that field, so Magento generates the url_key itself?
If you want model_no to be in the url (due to SEO requirements, I suppose) you'd better add it to name, which could be even better for SEO
$product->setName(trim($data['Name']) . trim($data['model_no']));
Feel free to join https://magento.stackexchange.com/questions & post more details about what you want
You are using set on wrong attribute i.e setUrl() instead you should use setUrlKey() and because you are not setting different url keys so magento is trying to use name for generating url keys and as you have same names for multiple products so it ends up trying to save same keys for multiple products which is giving you this error.

How to add product with custom option type file to cart programmatically

I am creating a functionality to add product to cart programmatically with Custom Option type File.
I am using the below code to add product :
$cart = Mage::helper ( 'checkout/cart' )->getCart ();
$product = Mage::getModel ( 'catalog/product' )->load(949);
$params['product'] = 949;
$options['options_32_file_action'] = 'save_new';
$params['options_32_file_action'] = 'save_new';
$params['options'] = $options;
$params['qty'] = 1;
$cart->addProduct ( $product, $params);
Uploaded file :
$_FILES['options_25_file'] = array
(
"name" => "1.png",
"type" => "application/octet-stream",
"tmp_name" => Mage::getBaseDir()."/1.png",
);
I am getting this below error :
The product has required options
I tried most of the solution provided on this site but can't fix this.
Kindly let me know is this the right approach or if there any other way to do this please refer me.

Reverse Name search using Kanavan Autosearch in Magento 1.7

I am using karavan autosearch extention for magento1.7. and I want to modify the searching technique. In that search technique if we provide a full or partial name, the search engine works perfectly. but I want it works for reverse name. I mean If the exact name is 'test product', then if I use 'product test', that result will show same product in dropdown product list, what is now became empty. I have debug it and found that this search engine also using magento default search technique.
Any kind of Idea is acceptable.Please help me..
Thanks in advance..
Karavan extension uses default Magento search Model as backbone
app\code\local\Mage\CatalogSearch\Model\Resource\Search\collection.php
Find method _getSearchEntityIdsSql() and change there as u required.
$words = array();
if(str_word_count($this->_searchQuery)>1){
$words = explode(" ",$this->_searchQuery);
}
$ifValueId = $this->getConnection()->getCheckSql('t2.value_id > 0', 't2.value', 't1.value');
foreach ($tables as $table => $attributeIds) {
foreach($words as $word){
$selects[] = $this->getConnection()->select()
->from(array('t1' => $table), 'entity_id')
->joinLeft(
array('t2' => $table),
$this->getConnection()->quoteInto(
't1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id = ?',
$this->getStoreId()),
array()
)
->where('t1.attribute_id IN (?)', $attributeIds)
->where('t1.store_id = ?', 0)
->where($resHelper->getCILike($ifValueId, $word, $likeOptions));
}
if ($selects) {
$likeCond = '(' . join(' and ', $selects) . ')';
}
}
Some what like this.
Note: DOnt overwrite BAse Class

How to get views / clicks of a specific product

As the title suggests, how do I get the number of views / clicks / impressions of a specific product in Magento. Any help is welcome.
This simple example will give you a list of products that have been viewed between the dates you specify + their view counts:
$fromDate = '2010-01-01';
$toDate = now();
$viewedProducts = Mage::getResourceModel('reports/product_collection')
->addViewsCount($fromDate, $toDate);
foreach($viewedProducts as $product) {
echo "ID: " . $product->getData('entity_id') . " - View Count: " . $product->getData('views') . "<br/>";
}
It helped me, get views just for one product.
$resource = Mage::getResourceModel('reports/event');
$select = $resource->getReadConnection()->select()
->from(array('ev' => $resource->getMainTable()), array(
'product_id' => 'object_id',
'view_count' => new Zend_Db_Expr('COUNT(*)')
))
->join(
array('et' => $resource->getTable('reports/event_type')),
"ev.event_type_id=et.event_type_id AND et.event_name='catalog_product_view'",'')
->group('ev.object_id')
->where('ev.object_id IN(?)', [$entity_id])
->where('ev.logged_at >= ?', $from)
->where('ev.logged_at <= ?', $to);
$views = $resource->getReadConnection()->fetchPairs($select);
$views = !empty($views[$entity_id]) ? $views[$entity_id] : 0;

set image to category programmatically in Magento

I try to add a category in magento by this code:
$_cat = new Mage_Catalog_Model_Category();
$_cat->setName($nom);
$_cat->setUrlKey($nom);
$_cat->setIsActive(1);
$parentCategory = Mage::getModel('catalog/category')->load(2);
$_cat->setPath($parentCategory->getPath());
$mediaAttribute = array ('thumbnail');
$_cat->addImageToMediaGallery($other_file, $mediaAttribute, true, false);
$_cat->save();
its works, but the image is not inserted, I need to know what is the correct code to insert the category image programmatically,
Thanks u.
ok I solved it , to add additionnel datas write :
$data['display_mode'] = 'PRODUCTS_AND_PAGE';
$data['page_layout'] = 'one_column';
$data['thumbnail'] = $path; // path to your image
$_cat->addData($data);
then put your image in YOUR_MAGENTO/media/catalog/category/NAME_OF_IMAGE.jpg
Cheers.
Here is a working example:
$newCategory = Mage::getModel('catalog/category');
$newCategory->setName('Category name');
$newCategory->setUrlKey('category-name');
$newCategory->setIsActive(1);
$parentCategory = Mage::getModel('catalog/category')->load(2);
$newCategory->setPath($parentCategory->getPath());
$newCategory->setImage('file_name.jpg');
$newCategory->save();
Make sure your category image 'file_name.jpg' is uploaded to media/catalog/category/file_name.jpg
BTW, any answer mentioning "addImageToMediaGallery" is wrong. This method only exist for product, not for category.
Also the correct attribute name for category is "image" not "thumbnail".
You could have also done to make it look cleaner and more readable:
$parentCategory = Mage::getModel('catalog/category')->load(2);
$newCategory = Mage::getModel('catalog/category');
$newCategory->setName($nom);
$newCategory->setUrlKey($nom);
$newCategory->setIsActive(1);
$newCategory->setPath($parentCategory->getPath());
$newCategory->addImageToMediaGallery($other_file, array ('thumbnail'), true, false);
$newCategory->setDisplayMode('PRODUCTS_AND_PAGE');
$newCategory->setPageLayout('one_column');
$newCategory->setThumbnail($path); // path to your image
$newCategory->save();
What do you think?
ElGabbu, in your code i get this error :
PHP Fatal error: Uncaught exception 'Varien_Exception' with message 'Invalid method Mage_Catalog_Model_Category::addImageToMedia Gallery(Array
(
[0] => image.jpg
[1] => Array
(
[0] => thumbnail
)
[2] => 1
[3] =>
)
)' in /home/www/magento/lib/Varien/Object.php:569
that my code who worked for me :
$_cat = new Mage_Catalog_Model_Category();
$_cat->setName($nom);
$_cat->setUrlKey($nom);
$_cat->setIsActive(1);
$parentCategory = Mage::getModel('catalog/category')->load(2);
$_cat->setPath($parentCategory->getPath());
$_cat->setIsAnchor(1);
$data['display_mode'] = 'PRODUCTS_AND_PAGE';
$data['page_layout'] = 'one_column';
$data['thumbnail'] = $path;
$_cat->addData($data);
$_cat->save();
I use the following snipped based on Mage_Catalog_Model_Product_Attribute_Backend_Media and Mage_Catalog_Model_Category_Attribute_Backend_Image to copy the image from external path to the thumbnail property including a _1 suffix if needed.
$attr = 'thumbnail';
$new_file = ...; // absolute path to your file
$category = ...; // your category model
$path = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS;
if (md5_file($new_file) != md5_file($path.$category->getData($attr)) {
$ioObject = new Varien_Io_File();
try {
$ioObject->open(array('path'=>$path));
} catch (Exception $e) {
$ioObject->mkdir($path, 0777, true);
$ioObject->open(array('path'=>$path));
}
$destFile = $path . Mage_Core_Model_File_Uploader::getNewFileName($path . basename($new_file));
$ioObject->cp($new_file, $destFile);
$category->setData($attr, basename($destFile));
}

Resources