顯示包含「Magento」標籤的文章。顯示所有文章
顯示包含「Magento」標籤的文章。顯示所有文章

2014/04/26

Support multi site for the magneto facebook login

A very common magento facebook login extension:

Belvg_FacebookFree
http://www.magentocommerce.com/magento-connect/facebook-connect-and-like-free.html?

 However it is not supporting multi site, so i did some changes to extension its function. The check existing fb id function only check the fb id if it is unique, without the current store id "where" clause


(1) Add a store_id column to database table 'belvg_facebook_customer' 

(2) Add the check existence function in 
/app/code/community/Belvg/FacebookFree/controllers/CustomerController.php in around line 52

$sql = 'SELECT `customer_id` FROM `' . $tablePrefix .
 'belvg_facebook_customer` WHERE `fb_id` = ' . $me['id'] .
 ' AND `store_id` = '.$store_id.' LIMIT 1';

Add AND `store_id` = '.$store_id.' 


(3) Insert the customer id/fb id pair with store id At around line 71, 
 $store_id = Mage::app()->getStore()->getStoreId(); // a new variable to save the current store_id

$sql = 'INSERT INTO `' . $tablePrefix . 'belvg_facebook_customer` VALUES (' . $r['entity_id'] . ', ' . $me['id'] .', '.$store_id. ')';

 Add one more column, the store id should be included in the insert clause. 


(4) Finished!
then the same fb_id can related to differrent magneto customer Id in different store

2014/04/09

CSV multi line import for multi site is missing some value in some scope

Magento's importer uses bunches to import values in all the different tables. It processes 100 rows each bunch. The split in bunches some does not make sense, for example The following file sucks when 100rows stops before the next scope(shopnz), then this product will be in missing of shopnz scope!!
There are two options:
1) The complete Mage_ImportExport_Model_Import_Entity_Product::_saveProducts methods has to be rewritten for all to work properly.
2) The data should only be cut when it can be cut, so the Mage_ImportExport_Model_Import_Entity_Abstract::_saveValidatedBunches method should be rewritten.

 At last i found a patch for 2) https://gist.github.com/paales/7934644 THe problem is described in here https://github.com/avstudnitz/AvS_FastSimpleImport/issues/69
 

Mage_ImportExport_Model_Import_Entity_Abstract

protected function _saveValidatedBunches()

2014/04/04

Pop out file download message in admin grid massaction

Inside the massaction controller, e.g. Mage_Adminhtml_Sales_OrderController By default, those print invoice options do this:
 
return $this->_prepareDownloadResponse( //edit by leo - change file name $filename.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(), 'application/pdf' );
But you can not just output pdf/file, csv is also ok
 
$data = 'your csv data'; $this->_prepareDownloadResponse('file.csv', $data, 'text/csv');
In my situation, I generate shipping label in HTML format. As massaction action does not allow opening the action in the blank page, so i assign those html content into a html file.
 
$html = $block->toHtml(); $filename = 'form_'. Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.html'; return $this->_prepareDownloadResponse($filename, $html, 'text/html');

2014/02/19

Cannot update qty after clearing magento db

f you failed to create a new product from admin and you’ll get an error message something like this SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`cataloginventory_stock_item`, CONSTRAINT `FK_CATALOGINVENTORY_STOCK_ITEM_STOCK` FOREIGN KEY (`stock_id`) REFERENCES `cataloginventory_stock` (`stock_id`) ON DELETE CASCADE ON UPDATE) You have to check whether you deleted entry from cataloginventory_stock table. If yes then please use below query to add new product. INSERT INTO cataloginventory_stock SET stock_name = ‘Default’; for product link insert into `catalog_product_link_type`(`link_type_id`,`code`) values (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell'); insert into `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) values (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal'); insert into `cataloginventory_stock`(`stock_id`,`stock_name`) values (1,'Default');

2014/01/06

magento sql 常用用法

  $resource = Mage::getSingleton('core/resource');  
  $tableName_votes = $resource->getTableName('jselfless/votes');  
  $tableName_image = $resource->getTableName('jselfless/image');  
  $collection = Mage::getModel('jselfless/woman')->getCollection();  
  $collection->getSelect()->reset(Zend_Db_Select::COLUMNS);  
  $collection->getSelect()->columns(array('items_count'=>'count(main_table.id)'));  
  $collection->addFieldToFilter('main_table.year',date('Y'));  
  $collection->addFieldToFilter('image.type','main');  
  $collection->addFieldToFilter('award',array('eq'=>''));  
  $collection->getSelect()->join(array('votes' => $tableName_votes), 'main_table.id = votes.selfless_woman_id', '');  
  $collection->getSelect()->join(array('image' => $tableName_image), 'main_table.id = image.selfless_woman_id', array('image.*'));  
  $collection->getSelect()->group('main_table.id');  
  $collection->getSelect()->Order('items_count desc');  
  $collection->getSelect()->Order('votes.created_at desc');  
  $collection->getSelect()->Order('main_table.updated_at desc');  
  $collection->getSelect()->limit(10,$postData['offset']);  

2013/11/04

Cannot find the ACL permission in the permission list

In my custom module, i have created the adminhtml.xml for it.
However  in the system > permission , i cannot find the checkbox that allows me to assign permission to the user.

After exploring the xml, i found that i was missing <title> tag between the section node and the <children> node.

For the build-in section, e.g. <report>, we can skip the <title> tag because it will load the default value that magento assign to it.( anyway you can still add it to override the default one)

However in my case, <suepreport> is a custom new tag, so i must specify the <title> tag for it!

After adding the title tag,  i finally see it in the admin permission tree! Great!

adminhtml.xml
<acl>
<resources>
<admin>
<children>

                    <report>
                        <children>
                            <suepreport>
                                <title>Suep Report</title>
                                <children>
                                    <pickuplocationbyshopbrand translate="title" module="suep">
                                        <title>Pickup Location Report-  By Shop Brand</title>
                                    </pickuplocationbyshopbrand>
                                    <pickuplocationbyshop translate="title" module="suep">
                                        <title>Pickup Location Report - By Shop</title>
                                    </pickuplocationbyshop>
                                   <monthlyaffiliate translate="title" module="suep">
                                        <title>Monthly Affiliate Report</title>
                                    </monthlyaffiliate>
                                </children>
                            </suepreport>
                        </children>
                    </report>




</children>
</admin>
</resources>
</acl>


2013/10/07

SQLSTATE[23000] Duplicate entry 'xxx' for key 'PRIMARY'

Problem:
When saving related product, it shows an error :
magento  SQLSTATE[23000]  Duplicate entry '959' for key 'PRIMARY'

Reason:
yes it right, the key is really duplicate in the table
after checking the related product table --- catalog_entity_product_link, the auto increment of 'link_id' is 950 but the latest record is '959', and it doesnt make sense

Solution: 
(1) increase the auto increment to 959  , SET AUTO_INCREMENT = 959
or
(2) delete the record after 950, and then save these related product again

 

2013/07/30

Magento rule based production relation

今日試用了rule based related product , 在一堆product 加上一個attribute " related product code"

再在rule base product 裏面"product to display" 設定上該attribute

但在frontend 一直call不到product...

磨了良久, 最後發覺condition 設定條件時不能選"is"  , 要選"contains" ....

估計是有space  / trim 空白的問題.......

這不科學啊!

2012/08/10

改變地址次序等格式 Customer Address Format

因香港地區問題, 客人需要印出的PDF SLIP 中的姓名欄位根據特定格式展現:

E.G.   prefix LAST NAME , firstname

即是本來內置看成Mr Chris Wong 的, 要改成 Mr WONG , Chris

其實要分成兩部份去做

(1) 修改Address template
原來magento 已在backend提供了template 的XML

System->Configuration->Customer->Customers->Customer Configuration->Address Templates

改改排序就可以了 

{{depend prefix}}{{var prefix}} {{/depend}}{{var lastname}} {{depend middlename}}{{var middlename}}{{/depend}}, {{var firstname}}

這樣姓氏和名字的次序便倒轉了, 還可在中間加上逗號

(2)override observer "customer_address_format" 把姓氏轉為大寫

簡單先講做法:
config.xml 


<adminhtml>
<events>
            <customer_address_format>
                <observers>
                    <cleargo_custom>
                        <class>Cleargo_Custom_Model_Countryformat</class>
                        <method>countryFormat</method>
                    </cleargo_custom>
                </observers>
            </customer_address_format>
        </events>
    </adminhtml>

Cleargo/Custom/Model/Countryformat.php


class Cleargo_Custom_Model_Countryformat {
    public function countryFormat($observer) {
        $event = $observer->getEvent();
        $address = $event->getAddress();
        $type = $event->getType();
        //if($address->getData('country_id') == 'FR'){
            $lastname = strtoupper($address->getData('lastname'));
            $address->setData('lastname', $lastname);
        //}
    }
}
 



順便講講發現既過程

事源我要在PDF 裏更改格式, 於是在order/pdf/shipment.php 發現
$shippingAddress = $this->_formatAddress($order->getShippingAddress()->format('pdf'));

再追尋format這function 是源自Mage_Customer_Model_Address_Abstract

在入面可發現在render address前, dispatch了一個event
Mage::dispatchEvent('customer_address_format', array('type' => $formatType, 'address' => $this));

於是根據magento的dispatchEvent 機制, 我們可輕鬆override observer 以改變程式run到呢行時既data





2012/07/30

magento print invoice PDF 繁體中文字型


因為PRINT 中文INVOICE PDF 會出現亂碼...

所以到了WINDOWS內的字型檔案, COPY出標楷體TTF 檔案

其他內置繁體字型可能容量太大而超出MEMORY LIMIT........

app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php

protected function _setFontRegular($object, $size = 7)
    {
     
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/KAIU.TTF',(Zend_Pdf_Font::EMBED_SUPPRESS_EMBED_EXCEPTION |
                                                             Zend_Pdf_Font::EMBED_DONT_COMPRESS));
        $object->setFont($font, $size);
        return $font;
    }


2012/07/10

Mage_Checkout.cvs Click here to print a copy of your order confirmation


Meet the double quotes

Notice that in the example above, both strings are surrounded by double quotes. Both what happens when the string itself has quotes in it. This is for instance the case when the Magento shopping cart is visited, while it contains no items.
The solution is simple: Just use 2 double quotes instead of 1. The translation-line would look like the following:
"Click <a href="/"%s"">here</a> to continue shopping.", "Click <a href="/"%s"">here</a> to go back."

2012/06/14

PHP利用EOT代替ECHO輸出


有時要在PHP加入JS/HTML, 會因為括號問題而需要很多改動....

間中會在OPEN SOURCE CODE 中見到以下方法

---------------------------------------------------------------------

使用eot的時候,好處就是可以直接把網頁的html當成一般的php程式一樣放在程式中,不用特別的去寫
<?php
     echo <<< EOT
     <div>新增 Div 標籤的內容放在這裡</div>
EOT;
?>
用法大概就是上面那樣,但要注意的地方是
1:<<<EOT  使用的時候,後面要是空的,不能夠有任何的資料在,空格也不行
2:EOT;這個一定要放在最前面,前面不能夠有任何的資料,空格也不行

2012/06/08

Sitemap.xml cannot change name - Path “/ sitemap_es.xml” is not available and can not be used


I also ran into that, and there’s a simple reason, and a simple and clean solution, which doesn’t tap any code.
They simply limit the file naming to this pattern: “/*/sitemap.xml”. So you can choose any directory, but you’ve to name the file “sitemap.xml”.
That implies, that you create an own directory for every sitemap you generate!
But regardless how simple the solution might be, the question arrises, WHY it is like that at all?! I can’t think of any reason, and it’s not even mentioned anywhere in the admin interface, so of course, you’re confused and start checking path permissions, etc.,
This is even the case with the latest 1.6!
Sourcinggate’s modification is not a very good idea, as it makes a maybe also otherwise used verification function to always return true, so you might mess up paths somewhere else, and Magento can’t tell you anymore.
So, here’s the fix:
In

/app/code/core/Mage/Adminhtml/etc/config.xml

Replace (at around line 190)

<any_path>/*/sitemap.xml</any_path>

with

<!-- zLabs Black BEGIN -->
<!-- 
No wonderthat we couldn't save any other filename than sitemap.xml ;)
        Is this a bug, or a "protection" feature? It doesn'
t tell this anywhere
        in the admin 
interface ... -->
<!-- <
any_path>/*/sitemap.xml</any_path> -->
<!-- zLabs | Black | END -->

2012/05/22

Nominal recurring products show zero in shipping fee

For recurring products, even you have set table rates/ shipping fee,

in the checkout section or cart section you will only just see Zero value, with another nominal item total / nominal shipping fee

It is confusing so that i want to set the normal shipping the same to the nominal shipping fee

The problem is here:
core/Mage/Shipping/Model/Carrier/Tablerate.php

public function collectRates


 if ($request->getFreeShipping() === true || ($request->getPackageQty() == $freeQty)) {
                //var_dump($rate['price']);
                $shippingPrice = 0;
            } else {
                $shippingPrice = $this->getFinalPriceWithHandlingFee($rate['price']);
            }

the shipping price is set to 0 .... but i don;t know why nominal product will enter this check case, maybe due to the ($request->getPackageQty() == $freeQty


Anyway , the shipping fee is now return to normal , lets see the  subtotal....



2012/05/21

Check the current page is a cms page or not


<?php
//for checking it is a CMS page, if true => show the order now button
$urlkey =  Mage::getSingleton('cms/page')->getIdentifier();

//remove any symbol
$cleanUrlKey = trim(preg_replace("/[^a-zA-Z0-9]+/", " ", $urlkey));

    if (!empty($urlkey)){

    // write down your code!!!!!!

}

?>
 

2012/05/01

Can't create table: eav_prefix_text , Integrity constraint violation: 1452 Cannot add or update a child row

http://www.magentocommerce.com/bug-tracking/issue/?issue=12126
http://www.magentocommerce.com/bug-tracking/issue/?issue=12336


Error :
(For magento 1.6 bug)
I encountered the same problem. In my situation I realized that the error occurring when trying to create the database table was: BLOB/TEXT column 'value' used in key specification without a key length
To force Magento to render SQL statements that my database could accept, I had to modify the app/code/core/Mage/Eav/Model/Entity/Setup.php file at approximately line 1337 (inside the createEntityTables method). Replacing the following lines:

        ->addIndex($this->getIdxName($eavTableName, array('attribute_id', 'value')),
            array('attribute_id', 'value'))
        ->addIndex($this->getIdxName($eavTableName, array('entity_type_id', 'value')),
            array('entity_type_id', 'value'))
 
With this:
 

 ->addIndex($this->getIdxName($eavTableName, array('entity_id')),  
                array('entity_id'));  

                if ($eavTableName[1] != 'text')  
                {  

                $eavTable->addIndex($this->getIdxName($eavTableName, array('attribute_id', 'value')),  
                array('attribute_id', 'value'))  
                ->addIndex($this->getIdxName($eavTableName, array('entity_type_id', 'value')),  
                array('entity_type_id', 'value'));  
                }  
 
 
 On the other hand, there is also an error for magento1.6:
Was also getting an error
-- Integrity constraint violation: 1452 Cannot add or update a child row magento
 

 
Had to remove the entity_id FK constraint (removing the ->addForeignKey... entity_id)

The createEntityTables() method Mage_Eav_Model_Entity_Setup creates FK's
 in the type sub-tables pointing at $this->getTable('eav/entity') 
instead of $baseTableName.


replace 
//                ->addForeignKey($this->getFkName($eavTableName, 'entity_id', 'eav/entity', 'entity_id'),
//                    'entity_id', $this->getTable('eav/entity'), 'entity_id',
//                    Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
//                

with this:

 $eavTable->addForeignKey($this->getFkName($eavTableName, 'entity_id', 'eav/entity', 'entity_id'),  
'entity_id', $baseTableName, 'entity_id',  
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)


 



  

2012/04/24

frontend cannot see pending payment orders


要加番 <visible_on_front/> 先會俾CUSTOMER見到...

app/code/core/Mage/Sales/etc/config.xml 

<new translate="label">
  <
label>New</label>
    <
statuses>
      <
pending/>
      <
processing/>
      <
holded/>
      <
complete/>
      <
closed/>
      <
canceled/>
    </
statuses>
    <
visible_on_front/>
  </new>
  <
pending translate="label">
    <
label>Pending</label>
    <
statuses>
      <
pending/>
      <
processing/>
      <
holded/>
      <
complete/>
      <
closed/>
      <
canceled/>
    </
statuses>
    <
visible_on_front/>
  </
pending>

漏左就會FRONTEND睇唔到某D STATUS既ORDER...

2012/04/03

[MAGENTO] DASHBOARD 中的圖表消失了


DASHBOARD 中LAST 24 HOURS的圖表不見了

由官方論壇看到

                            
This is related to the minimal allowed GET variable length settings. Check your settings for suhosin:

suhosin.get.max_value_length 1024


SOLUTION: 
Putting “suhosin.get.max_value_length = 1024” into /etc/php5/conf.d/suhosinn.ini” reload apache

2012/03/21

Adding/Removing Items from header top links



To edit top links content, we need to access the xml files

1. app/design/frontend/default/default/layout/checkout.xml
2. app/design/frontend/default/default/layout/customer.xml

[code]

<!--
Default layout, loads most of the pages
-->

    <default>

        <!-- Mage_Customer -->
        <reference name="top.links">
            <action method="addLink" translate="label title" module="customer"><label>My Account</label><url helper="customer/getAccountUrl"/><title>My Account</title><prepare/><urlParams/><position>10</position></action>
<action method="addLink" translate="label title" module="customer"><label>Contact
Us</label><url>contacts</url><title>Contact
Us</title><prepare/><urlParams/><position>999</position></action>
</reference>
    </default>
[/code]

2012/01/11

Cannot create `tag` table in Magento installation with sample data

彈出的ERROR
Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘USING BTREE,
KEY `FK_TAG_FIRST_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID` (`first’ at line 7

原來是MYSQL 5.0 和5.1 的SYNTAX問題, 升級到5.1可以解決問題, 或是用以下方法

solved this problem by changing:

PRIMARY KEY (`tag_id`) USING BTREE,
changed into
PRIMARY KEY USING BTREE (`tag_id`),

PRIMARY KEY (`tag_relation_id`) USING BTREE ,
changed into
PRIMARY KEY USING BTREE (`tag_relation_id`),