Saturday, February 27, 2010

IPv6 for online customers

Problem : how to make Magento show the ipv6 ip address on online customers.
See full text here http://www.magentocommerce.com/boards/viewthread/79160/

Possible (untested) solution. If someone tests it please tell me the results also:

In theory you cannot do this, because in the database the fields for ip address are 'bigint' (see tables that start with log_visitor_)
All the ip addresses stored in this table 'suffer' a modification with ip2long() method. Unfortunately php does not support IPv6 (at least that's what I know. If I'm wrong someone please correct me).
Enough with the problems.
Here is what you can try.
Change the type of the columns for ip addresses from bigint to varchar.
In app/code/core/Mage/Log/Model/Visitor.php look for these lines:
$this->addData(array(
'server_addr'           => $helper->getServerAddr(true),
'remote_addr'           => $helper->getRemoteAddr(true), 
....
and remove the 'true' parameters from the functions.
$this->addData(array(
'server_addr'           => $helper->getServerAddr(),
'remote_addr'           => $helper->getRemoteAddr(), 
This should save the ip addresses as strings.

We are half way there. Now all you have to do is make sure that the ip addresses are rendered in the back-end grid you need to change the \app\code\core\Mage\Adminhtml\Block\Customer\Online\Grid\Renderer\Ip.php file.
Change this
public function render(Varien_Object $row)
{
return long2ip($row->getData($this->getColumn()->getIndex()));
}

to
public function render(Varien_Object $row)
{
return $row->getData($this->getColumn()->getIndex());
}

or to this, for backwards compatibility (to see the previous saved ip addresses)
public function render(Varien_Object $row)
{
$val = $this->getColumn()->getIndex();
if (is_int($val)){
return long2ip($val);
}
return $val;
}

Clear the cache and test it.
I have no way of testing this but it seams to me that this is the way to go.

(Of course you don't need to modify the core files if you plan to upgrade, you can overwrite them the proper magento way ).

Monday, February 1, 2010

Save an object into the database with a specific id. (insert - not update)

Problem can be found here:

Possible solution:

The presence of an id means update and if the id is null it means is insert.
So when you try to insert and add an id Magento is actually trying to update the entity but the id you specify does not exist.
It's something similar to this:
UPDATE some_table SET some_field = some_value WHERE id = some_id; 
The sql goes through but nothing gets updated.
If you want to modify something (but I don't advice you to do this) you can change the Mage_Core_Model_Mysql4_Abstract and Mage_Core_Model_Abstract models (the save() method for both of them.)

If you look inside the save method of Mage_Core_Model_Mysql4_Abstract you will see that there's an 'if' statement
if (!is_null($object->getId())) {...}
This means exactly what I explained above.

Here is an idea on how you can make magento do an insert with a specified id.
Overwrite the Mage_Core_Model_Abstract::save() method to accept and other parameter.
Let's call it $alwaysInsert and set it's default value to false (so you will not interfere with the other objects that use save()).
Then pass the $alwaysInsert parameter to the save method from the resource.
Your new method could look like this:
public function save($alwaysInsert = false)
{
$this->_getResource()->beginTransaction();
try {
$this->_beforeSave();
$this->_getResource()->save($this, $alwaysInsert);
$this->_afterSave();

$this->_getResource()->commit();
}
catch (Exception $e){
$this->_getResource()->rollBack();
throw $e;
}
return $this;
}

In Mage_Core_Model_Mysql4_Abstract, change the method save() to accept 2 parameters.
It could look like this:
public function save(Mage_Core_Model_Abstract $object, bool $alwaysInsert)
{
if ($object->isDeleted()) {
return $this->delete($object);
}

$this->_beforeSave($object);
$this->_checkUnique($object);

if (!is_null($object->getId()) && !$alwaysInsert) {
$condition = $this->_getWriteAdapter()->quoteInto($this->getIdFieldName().'=?', $object->getId());
$this->_getWriteAdapter()->update($this->getMainTable(), $this->_prepareDataForSave($object), $condition);
} else {
$this->_getWriteAdapter()->insert($this->getMainTable(), $this->_prepareDataForSave($object));
$object->setId($this->_getWriteAdapter()->lastInsertId($this->getMainTable()));
}

$this->_afterSave($object);

return $this;
} 

WARNING:
There are 2 issues (at least that is all I can think about now)
1. I didn't test this. You can test it and tell everyone the results
2. I'm not sure how Magento behaves when extending an abstract class. Normally it shouldn't cause any problems, but make sure the class(es) you are working with extend the new class(es) that you just created (extensions of Mage_Core_Model_Abstract and Mage_Core_Model_Mysql4_Abstract not these classes themselves).

If instead of overwriting you decide to modify the core this should take care of these issues, but you are not suppose to modify the code.
I hope this works for you. If it doesn't I'm sorry.

Tuesday, January 19, 2010

Display 'template hints' in 'default config'

Problem: Display 'template hints' and 'bloc hints' in 'default config'
Posible solution
If you want this option displayed for 'default config' also, just edit the app\code\core\Mage\Core\etc\system.xml file.
Look for something like this
<template_hints translate="label">
<label<Template Path Hints</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>20</sort_order>
<show_in_default>0</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</template_hints>
replace
<show_in_default>0</show_in_default>
with
<show_in_default>1</show_in_default>
and clear the cache
Do the same for this section

<template_hints_blocks translate="label">
<label>Add Block Names to Hints</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>21</sort_order>
<show_in_default>0</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</template_hints_blocks>
Be careful. When you enable these 2 from 'default config' you will also see template hints and block hints in the admin section.

Monday, January 18, 2010

Avoid empty meta-title for products (for biostall)

Problem: in case the meta-title is not filled in for a product the title should replace it

Possible solution:

Create a new method in the product model (Mage_Catalog_Model_Product) class called getMetaTitle();
function getMetaTitle(){
if (!$this->getData('meta_title')){
$this->setMetaTitle($this->getTitle());
}
return $this->getData('meta_title');
}

A list of all the products in the website (for travelingwilly)

Problem: a list of all the products in the website.

Possible solution:

The easiest (less code) solution is to create a category called 'All' an put all the products in that category(beside the category that they belong to).
The second method implies some code.
Create the Mage_Catalog_Block_Product_All class and put it in a file located here (app/code/code/Mage/Catalog/Block/Product/All.php)
<?php
class Mage_Catalog_Block_Product_All extends Mage_Catalog_Block_Product_List
{
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('status', 1)
->addAttributeToFilter(array(array('attribute'=>'visibility', 'eq'=>"4")));
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
}
?>

After this create a CMS page. and in it's content put the following
{{block type="catalog/product_all" template="catalog/product/list.phtml"}}
In the "Layout" field (from the 'Custom design' tab) select '2columns-left' (or any other design just don't leave it to 'empty')
Save and that's it.
If the page you just created has the identifier ('all-products') and is enabled you will see a paginated list of all your products here:
http://www.yoursite/all-products (or http://www.yoursite/{YOUR STORE CODE}/all-products if you have store codes in the url)

I know that this is not 100% clean because you need to add some code in the core. This is no problem, you can add this also in the local folder.

EDIT: I forgot to close a curly bracket at the end of the class. Thanks To John (see who John is the comments below) I fixed it.

Display CMS Blocks on product description (for Mattse)

Problem: add static block to product description

possible solution

You can add a new method to the product model.
function getDescription(){
$processor = Mage::getModel('core/email_template_filter');
$html = $processor->filter($this->getData('description'));
return $html;
}

In this way you can use the same {{block}} and {{skin}} sections just like the static blocks and pages and e-mail templates.

Wednesday, January 13, 2010

how to display number of items in cart and cart total (for elmuchoprez)

Problem: how to display number of items in cart and cart total?
Possible solution

To display items in cart do this:
$this->helper('checkout/cart')->getSummaryCount();
or
Mage::helper('checkout/cart')->getSummaryCount();
And for the total:
Mage::getSingleton('checkout/session')->getQuote()->getSubtotal();
This will display only the total amount for the products.
If you want the grand total (including shipping & handling) do this:
Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal();

Tuesday, January 5, 2010

Show customer group in order e-mail (for redbeetstudio)

Problem: Show customer group in order e-mail.
http://www.magentocommerce.com/boards/viewthread/71736/

Possible solution
In order for this to work in the e-mail template:
{{var order.getCustomerGroupName()}}
you have to create a method in the Order model (overwrite it or edit the core at your own risk).
function getCustomerGroupName(){
$group = Mage::getModel('customer/customer_group')->load($this->getCustomerGroupId());
if ($group->getId()){
return $group->getName();
}
return '';//or any default value if the customer is not in a group or is a guest
}

Tuesday, December 29, 2009

how to get customer address (for MagentoPycho)

Problem:how to get customer address from session?

Possible solution
Here is how you retrieve the primary billing address object:
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customerAddressId){
$address = Mage::getModel('customer/address')->load($customerAddressId);
}
If you want the address in html format do this:
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customerAddressId){
$address = Mage::getModel('customer/address')->load($customerAddressId);
$htmlAddress = $address->format('html')
}
if you want specific parts of the address just print it out and see how that part is called
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customerAddressId){
$address = Mage::getModel('customer/address')->load($customerAddressId);
echo "
"; print_r($address->getData());echo "
"; }
for example if you want the street do this:
$street = $address->getData('street');
It works the same for the rest of the of the address attributes (firstname, lastname, phone, ...)

Exporting reviews (for rpeters83)

Problem: how to export reviews from Magento.
Possible solution:


Here is how you can retrieve all the comments.
Create a new php file on the same level as index.php of Magento. let's call it reviews.php
the content of this file should look like this:
<?php 
$mageFilename = 'app/Mage.php';

require_once $mageFilename;

Varien_Profiler::enable();

Mage::setIsDeveloperMode(true);

ini_set('display_errors', 1);

umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);

header('Content-Type: text/xml; charset=utf-8');
echo "<?xml version =\"1.0\" encoding =\"UTF-8\"?>\n";
echo "<reviews>\n";
$collection = Mage::getModel('review/review')->getCollection();
foreach ($collection as $item){
$review = Mage::getModel('review/review')->load($item->getId());
echo "\t<review>\n";
echo "\t\t<id>".$review->getId()."</id>\n";
echo "\t\t<created_at>".$review->getCreatedAt()."</created_at>\n";
echo "\t\t<status_id>".$review->getStatusId()."</status_id>\n";
echo "\t\t<store_id>".$review->getStoreId()."</store_id>\n";
echo "\t\t<title>".$review->getTitle()."</title>\n";
echo "\t\t<detail>".$review->getDetail()."</detail>\n";
echo "\t\t<nickname>".$review->getNickname()."</nickname>\n";
echo "\t\t<customer_id>".$review->getCustomerId()."</customer_id>\n";
echo "\t\t<product_id>".$review->getEntityPkValue()."</product_id>\n";
echo "\t\t<stores>".implode(",", $review->getStores())."</stores>\n";
echo "\t</review>\n";
}
echo "</reviews>";
?>
Just call the page in your browser (www.yoursite.com/review.php)
This will export all the reviews in xml format. If you want an other format you can manage from this.
The status id is one of these
APPROVED       = 1;
PENDING        = 2;
NOT_APPROVED   = 3;

I hope this helps.