issue Importing csv file into magento - magento

So, I am trying to add some products to Imports in the admin page, however, the prices that have a float ending on "0" get truncated by excel. For example, if I have a price of $4.10 it will be truncated into $4.1, and prices on webpage will be displayed as so.
I thought about creating a vba automation in a macro but there are many different files and it will take too much effort. So, I know I cannot do anything excel-wise.
Now, magento-wise, I could use $_coreHelper(currency($price); to convert this into the right format, but those anybody knows where can I find these code? Any other ideas?
Thanks in advance!!

Here's an option for you. I have an import.php script that I use to import or update large numbers of products and their attributes. It will let you either update or create a product based on SKU. You would have to check the constants to see if they match your Magento.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
$product = GetProduct('SKU01'); $product->setData('upc', '013051388461'); SaveProduct($product); unset($product);
$product = GetProduct('SKU02'); $product->setData('special_price', null); $product->setData('special_from_date', null); SaveProduct($product); unset($product);
$product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product);
?>
I often get Excel to create the lines like $product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product); and then just copy and paste into the script. I can edit before running.
This is much faster than importing a CSV and it calls all of the correct observers.
Just run this from a SSH shell.

I suggest you to use Open Office Calc.
Before entering the values in the price column right click on top of column > Click format cell > Select numbers tab > Select text as shown in the attached image then click ok.
Now when you enter value like 12.30 it will be as it is in the column.
Also save the file as UTF-8 csv format before importing.
You can verify the created file by opening in notepad++.

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!";
?>

Change the maximum amount of characters in the Meta Description

I have a problem to change the limit of characters in the meta description. I\\’ve modified as shown here:
http://www.magentocommerce.com/boards/v/viewthread/278911/#t392935
But it only detects if you create or modify the product from magento admin and I upload products from .csv file and I have to go one by one to each product in the meta description and then go down from 255 to 155: (
Is there any way to change it without changing it from Magento, I think the problem comes because the code says:
setOnkeyup
Thanks in advance and greetings!
I understand, that you have too long data in your meta_description for each of products.
You can short the value before loading it by layout XML config, or directly by the PHTML template for each page type.
Better way to have result you need is NOT ti import longest data than you need.
Importing unnecessary data solving import and after that you need to correct it again.
Maybe will be better to make script to cut-out meta description in CSV file before you start import to magento.
I solved simmilar issue and make something like this:
(script take your csv file and make new with only 2 columns, SKU and updated text named DECSRIPTION, than you can import to magento after your firs import of csv (first import everything without meta description, after that ONLY your meta description cuted out by 250 chars for example))
//////// get csv and take variable you need in my case is it SKU
$csv = file_get_contents ('myimportfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list of variables to array
$vystup = parse_csv($csv);
enter code here
After that you can loop each variable to row, modify by PHP what you want:
$seznamsku = array();
foreach ($vystup as $row){
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
foreach ($seznamskufin as $row) {
$__OUT .= ' "ROW_YOURSKU","'.htmlspecialchars(substr(ROW_YOURMETADESCRIPTION, 0, 155)).'"'."\n"; // TODO exactly dont know how to call variables, maybye $row['something'] or $row[0]['something']
};
$feed = fopen($newfile, 'w');
fwrite($feed, $__OUT);
fclose($feed);
//remember to unset variables
you can get another csv file with description long 250 chars and import it to magento
(You must update code it only returns list of SKU, get your descriptions from file);

Deleting Products with Magmi Datapump

I can successfully delete products with MAGMI's web frontend.
But when using the datapump API, it just seems to ignore the magmi:delete column...
$this->magmi = Magmi_DataPumpFactory::getDataPumpInstance("productimport");
$this->magmi->beginImportSession("Default","create", new MagmiLogger($this));
$prods = Mage::getResourceModel('catalog/product_collection');
$count = $prods->getSize();
$i = 0;
foreach ($prods as $_p) {
$this->magmi->ingest(array(
'sku' => $_p->getSku(),
'magmi:delete' => '1'
));
}
$this->magmi->endImportSession();
With this code I try to delete my whole catalog. When executing, the foreach loop runs through without any exception or error by MAGMI. The Product Deleter plugin is activated in my selected Default profile.
What am I missing here?
Nevermind, I selected the wrong profile...
It works with the posted code, when you really select a profile with activated "Product Deleter" plugin.
Click Here to add MAGMI into your module -> https://magento.stackexchange.com/a/351175
Enable Product Deleter plugin.
Using CSV
"sku","magmi:delete"
"sku1","1"
"sku2","1"
Using Code
$importData = [];
$configProduct = new \Magmi_ProductImport_DataPump('productimport');
$importData['sku'] = "your Product SKU";
$importData['magmi:delete'] = "1";
$configProduct->beginImportSession("default", "update");
$run = $configProduct->ingest($importData);
$configProduct->endImportSession();
Check catalog_eav_attribute table in your db . If is_configurable column not present then update below code from getConfigurableOptsFromAsId() function in this file .../magmi/plugins/base/itemprocessors/configurables/magmi_configurableprocessor.php
//$sql .= " JOIN $cea as cea ON cea.attribute_id=ea.attribute_id AND cea.is_global=1 AND cea.is_configurable=1";
$sql .= " JOIN $cea as cea ON cea.attribute_id=ea.attribute_id AND cea.is_global=1";
} else {
//$cond .= " AND ea.is_global=1 AND ea.is_configurable=1";
$cond .= " AND ea.is_global=1";
Note:- magmi:delete : 1 is to delete the product 0 is to not delete the product

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

Auto refresh content in Mediawiki

I added a new tag (<news />) to my mediawiki to list the last modified pages.
Unfortunately the list is not updated unless I modify the page where the tag is.
I'm looking for a way to do it, and I think of AJAX. But I didn't manage to make AJAX refreshing my list.
Does anyone know a simple way to add an auto refresh feature on my Mediawiki ?
Here is my extension code :
$wgHooks['ParserFirstCallInit'][] = 'replaceTags';
function replaceTags( Parser $parser ) {
$parser->setHook( 'news', 'newsRender' );
return true;
}
function newsRender( $input, array $args, Parser $parser, PPFrame $frame ) {
// Titre =News=
$output = $parser->parse( "=News=", $parser->mTitle, $parser->mOptions, false, false )->getText();
$nb = 5;
$querySQL = "SELECT page_namespace, page_title, page_id, page_latest, rev_timestamp
FROM page, revision
WHERE page.page_latest = revision.rev_id
AND page_namespace = 0
ORDER BY rev_timestamp
DESC LIMIT 0,$nb";
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->query( $querySQL );
$count = $dbr->numRows( $res );
if( $count > 0 ) {
$output .= "<ul>";
while( $row = $dbr->fetchObject( $res ) )
{
$pageTitle = $row->page_title;
$nicerPageTitle = str_replace("_", " ", $pageTitle);
$pageNamespace = $row->page_namespace;
$title = Title::makeTitleSafe( $pageNamespace, $pageTitle );
$url = $title->getFullURL();
$date = $row->rev_timestamp;
$date = wfTimestamp( TS_RFC2822, $date );
$output .= "<li>$nicerPageTitle $date</li>";
}
$output .= "</ul>";
} else {
$output .= "A l'ouest rien de nouveau !!!";
}
return $output;
}
Thanks to nischayn22, I go into the cache problem in depth.
And I found that it's possible to deactivate it :
$parser->disableCache();
I tried it, and it works !!!
http://www.mediawiki.org/wiki/Extensions_FAQ#How_do_I_disable_caching_for_pages_using_my_extension.3F
This probably happens because MediaWiki uses Cache for pages. What you could rather do is make a SpecialPage for the feature needed. AFAIK Special Pages are not cached (confirm this on irc #mediawiki).
Also you might already find a similar implementation done by someone if you search the extensions that exist on Mediawiki.org .(Otherwise I would be happy to build one for you :)
Update: Extensions you could use Dynamic List(used in wikinews) and news . There could be more if you search mediawiki.org.

Resources