1:24 PM
0

1. Active record

Conlection +
Sau moi activerecode, goi load() de tra ve du lieu

1. getFirstItem() - getLastItem() : lay 1 doi ban ghi trong db - thuoc getCollection
2. getColumnValues('name_column') : lay tat ca gia tri cua mot cot - tra ve mang - thuoc getCollection
3.getItemsByColumnValue('name_column','value'): tra ve mang cac doi tuong ban ghi ma cot co gia tri tuong ung
4. removeAllFieldsFromSelect: remove all column in select
4. (string)getModel()->getSelect(): tra ve string cau lenh mysql
5. getFieldToFilter() : tuong duong where select
- $column,$value : $column = '$value';
- $column,array('$operator'=>'$value'): $column $operator '$value'
$operator: eq= , neq!= , like, nlike, is, in, nin,
notnull(true or false),  null, gt> , lt< ,
gteq>= , lteq , (from=>value, to=>value)
6. addFieldToSelect(string): them cot trong select
7. getSelect()->cac lenh sql co ban, sau cac lenh tren
-columns(string): select?
- where(string)
- join(table, cond) - table = $thismodel->getTable(module/table)
- order(string)
-limit(limit, start)
- group

$select = clone $collection->getSelect();
$select->columns()->where()..;
$result = $collection->getConnect()->fetchAll($select);

Dung core_resource de lay ket qua

8. EAV: sau cau lenh khong can goi load()
addAttributeToSelect(): giong getFieldToSlect()
addAttributeToFilter(): giong addFieldToFilter()

9. run query mysql
$resource = Mage::getModel('core/resource');
$connect = $resource->getConnection('core_read'); (core_write)
$table = $resource->getTableName('module/tagTable');

SELECT:
$query = "";
$result = $connect->fetchOne($query);//fetchRow, fetchCol, fetchAll, fetchPairs
UPDATE:
$connect->update($table, array(column=>value), array(where=>value));
INSERT:
$connect->insert($table, array(colume=>value));
DELETE
$connect->delete($table, array(where=>value))

$writeConnection->query($query);

where: array('id in(?)' => array(1,2,3));

2. Core

1. mage_core_model_design_package:

2. Block:
core/text_list: auto to html
page/html_breadcrumbs

3. -----------upgrade:
Magentoconnect: < 1.4: magento-core/Mage_All_Latest
> 1.4.2: http://connect20.magentocommerce.com/community/Mage_All_Latest
downloader\lib\Mage\Connect\Validator.php:
or  downloader\pearlib\download\Mage_Downloader-1.5.0.0\downloader\lib\Mage\Connect
comment:
if (file_exists($dest)) {
$this->addError("'{$file}' already exists");
return false;
}
Call to undefined method Varien_Db_Adapter_Pdo_Mysql::isTableExists()
reindex web by cmd: php -f ./index.php

-------------------------
Hien error: Mage::setIsDeveloperMode(true);

1. load admin - setstore
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0, website_id=0,group_id=0 WHERE code='admin';

UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';

UPDATE `core_website` SET website_id = 0 WHERE code='admin';

UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';

SET FOREIGN_KEY_CHECKS=1;

2. Grid Admin
    Collection - dung cac cot trong add column
      error filter: prepareCollection:
            'filter_index' => 'main_table.grand_total',
            or 'filter_condition_callback' => array($this,'_filterNames'),
                  protected function _filterNames($collection, $column)
                {
                    $value = $column->getFilter()->getValue();
                    if($value) {
                        $collection->getSelect()->where("`sales/order_item`.`name` LIKE '%$value%'");
                    }
                    return $this;
                }
3. Khai bao admin trong config moi dung duoc menu moi
    adminhtml:
       <config>
            <menu>
                <giangnt translate="title" module="giangnt_exportcsv">
                    <title>GiangNT</title>
                    <sort_order>999</sort_order>
                    <children>
                        <exportcsv translate="title" module="giangnt_exportcsv">
                            <title>Export CSV</title>
                            <sort_order>1</sort_order>
                            <action>adminhtml/exportcsv/index</action>
                        </exportcsv>
                    </children>
                </giangnt>
            </menu>
            <acl>
                <resources>
                    <admin>
                        <children>
                            <giangnt translate="title" module="giangnt_exportcsv">
                                <title>GiangNT</title>
                                <sort_order>999</sort_order>
                                <children>
                                    <exportcsv translate="title" module="giangnt_exportcsv">
                                        <title>Export CSV</title>
                                    </exportcsv>
                                </children>
                            </giangnt>
                        </children>
                    </admin>
                </resources>
            </acl>
        </config>
4. script khong an update value: Mage::app()->setUpdateMode(false);

4. delete log: php -f log.php clean , php -f log.php status
            'dataflow_batch_export',
            'dataflow_batch_import',
            'log_customer',
            'log_quote',
            'log_summary',
            'log_summary_type',
            'log_url',
            'log_url_info',
            'log_visitor',
            'log_visitor_info',
            'log_visitor_online',
            'index_event',
            'report_event',
            'report_viewed_product_index',
            'report_compared_product_index',
            'catalog_compare_item',
            'catalogindex_aggregation',
            'catalogindex_aggregation_tag',
            'catalogindex_aggregation_to_tag'

            TRUNCATE TABLE dataflow_batch_export;
TRUNCATE TABLE dataflow_batch_import;
TRUNCATE TABLE log_customer;
TRUNCATE TABLE log_quote;
TRUNCATE TABLE log_summary;
TRUNCATE TABLE log_summary_type;
TRUNCATE TABLE log_url;
TRUNCATE TABLE log_url_info;
TRUNCATE TABLE log_visitor;
TRUNCATE TABLE log_visitor_info;
TRUNCATE TABLE log_visitor_online;
TRUNCATE TABLE index_event;
TRUNCATE TABLE report_event;
TRUNCATE TABLE report_viewed_product_index;
TRUNCATE TABLE report_compared_product_index;
TRUNCATE TABLE catalog_compare_item;
TRUNCATE TABLE catalogindex_aggregation;
TRUNCATE TABLE catalogindex_aggregation_tag;
TRUNCATE TABLE catalogindex_aggregation_to_tag;


         
5. fix bug
    - view log
    - Change theme default
    - so sanh core, base
    - disable extension
      - Dat log
6. dat log index.php
Mage::log('-----------Url ---------------', null, 'giang_url_info.log');
Mage::log('url: ' . $_SERVER['REQUEST_URI'], null, 'giang_url_info.log');
Mage::log('-----------Post info-----------', null, 'giang_url_info.log');
Mage::log(print_r($_POST, true), null, 'giang_url_info.log');
Mage::log('-----------Get info-----------', null, 'giang_url_info.log');
Mage::log(print_r($_GET, true), null, 'giang_url_info.log');

7. last_increment_id
eav_entity_store, eav_entity_type

8. redirect - cache
      etc/module/local.xml remove cache mem
9. magento 1910: not order sent success
      queue sales/order->checkout/type_onepage
10. formkey: layout/core.xml
11. list product: Catalog_Model_layer, Catalog_Block_Layer_view,
12. duplicate save product UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID:
    max_id_product_status of table cataloginventory_stock_status
    max_id_product_item of cataloginventory_stock_item
    max_id_product_item > max_id_product_status : delete all record of cataloginventory_stock_item have product id > max_id_product_status.
13.
------------------------
4. Mage::getSingleton('core/session')->getMessages()->count() : dem so messages (success, notice, warning, error)

5. customer_form_attribute: tu 1.9, cac form dung bang nay de lay attribute

6. List product
Layout them sau toolbar
               
               
                   
               
                trong Data.php of Helper, viet ham getProductCollection, voi dieu kien custom

7. checkout: js step
 $(document).observe('dom:loaded', function(){
        $("opc-billing").observe('click', function(evt){
            checkout.changeSection('opc-billing');
        });
        }
8. Override controller

       
           
               
                   
                        SM_FPCheckEmail
                   
               
           
       
   

9. Get handler any
    Mage::app()->getLayout()->getUpdate()->getHandles()

10. sent email
$templateTransaction = Mage::getModel('core/email_template')
                    ->getCollection()
                    ->addFieldToSelect('template_id')
                    ->addFieldToFilter('template_code', 'Sell email template')
                    ->getFirstItem(); //get template email
                if ($templateTransaction->getTemplateId()) {
                    $templateId = $templateTransaction->getTemplateId();
                    $mailTo = Mage::getStoreConfig('trans_email/ident_custom1/email');
                    $nameTo = Mage::getStoreConfig('trans_email/ident_custom1/name');
                    $sender = array(
                        'name' => $params['name'],
                        'email' => $mailTo,
                    );
                    $storeId = Mage::app()->getStore()->getId();

                    // Set variables that can be used in email template sell
                    $vars = array(
                        'email_sell' => $params['email'],
                        'name_sell' => $params['name'],
                        'message_sell' => $params['message'],
                    );
                    $translate = Mage::getSingleton('core/translate'); //translate template email
                    $mailTransactional = Mage::getModel('core/email_template');
                    //image attachment
                    if (isset($_FILES['img'])) {
                        //MAX file size
                        if (($_FILES['img']['error'] == 1 || $_FILES['img']['error'] == 2)) {
                            Mage::getSingleton('core/session')->addError($this->__('File size must less than 2MB, please again!'));
                            return Mage::app()->getResponse()->setRedirect(Mage::helper('sm_sell')->getSellUrl());
                        }
                        //error upload file
                        if ($_FILES['img']['name'] && $_FILES['img']['error'] !== 0) {
                            Mage::getSingleton('core/session')->addError($this->__('Error upload file, please again!'));
                            return Mage::app()->getResponse()->setRedirect(Mage::helper('sm_sell')->getSellUrl());
                        }
                        //upload img success
                        if (file_exists($_FILES['img']['tmp_name'])) {
                            $fileInfo = $_FILES['img'];
                            $allowFile = array('image/jpeg', 'image/png', 'image/gif');
                            if (($fileInfo['size'] / 1e6) > 2) {
                                Mage::getSingleton('core/session')->addNotice($this->__('File size must less than 2MB, please again!'));
                                return Mage::app()->getResponse()->setRedirect(Mage::helper('sm_sell')->getSellUrl());
                            } else if (!in_array($fileInfo['type'], $allowFile)) {
                                Mage::getSingleton('core/session')->addNotice($this->__('Only allow image type: png, jpeg, gif, please again!'));
                                return Mage::app()->getResponse()->setRedirect(Mage::helper('sm_sell')->getSellUrl());
                            }

                            $at = $mailTransactional->getMail()
                                ->createAttachment(file_get_contents($fileInfo['tmp_name']));
                            $at->type = $fileInfo['type'];
                            $at->disposition = Zend_Mime::DISPOSITION_INLINE;
                            $at->encoding = Zend_Mime::ENCODING_BASE64;
                            $at->filename = $fileInfo['name'];
                        }
                    }
                    try {
                        $mailTransactional  //send email to admin sell
                            ->sendTransactional($templateId, $sender, $mailTo, $nameTo, $vars, $storeId);
                        $translate->setTranslateInline(true);
                        Mage::getSingleton('core/session')->addSuccess($this->__("Send message success!"));
                    } catch (Exception $e) {
                        Mage::getSingleton('core/session')->addError($e->getMessage());
                        return Mage::app()->getResponse()->setRedirect(Mage::helper('sm_sell')->getSellUrl());
                    }
                }
    ----------- config core
            $config = array(
                'ssl' => 'tls',
                'port' => 587,
                'auth' => 'login',
                'username' => '',
                'password' => ''
            );
            $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
            $mail = new Zend_Mail();
            $mail->send($transport);

11. order incremnt id

$idsEntity = Mage::getModel('eav/entity_type')->getCollection()
        ->addFieldToSelect('entity_type_id')
        ->addFieldToFilter('entity_type_code',array(in=>array('order','invoice','shipment','creditmemo')))
        ->getColumnValues('entity_type_id');
    if(count($idsEntity)>0){
        $resource = Mage::getModel('core/resource');
        $readConnection = $resource->getConnection('core_read');

        $tableEntityStore =$resource->getTableName('eav/entity_store');
        $query = "select max(increment_last_id) as idMax from $tableEntityStore where store_id='$storeId'";
        $results = $readConnection->fetchOne($query);

        //id_increment assign order, invoice, shipment, creditmemo
        $idMax = $results ? ($results+10) : $orderIncrementIdMax;

        foreach($idsEntity as $idEntity) {
            $query = "select entity_store_id from $tableEntityStore where store_id='$storeId'
                        and entity_type_id='$idEntity'";
            $results = $readConnection->fetchOne($query);

            if(!$results) { //if code not exist then insert
                $readConnection->insert(
                    $tableEntityStore,
                    array(
                        'entity_type_id' => $idEntity,
                        'store_id' => $storeId,
                        'increment_prefix' => $storeId,
                        'increment_last_id' => $idMax,
                    )
                );
            }
            else { //if code exist then update
                $readConnection->update(
                    $tableEntityStore,
                    array('increment_last_id' => $idMax),
                    array(
                        'entity_store_id = ?' => $results,
                    )
                );
            }
        }
    }

12. add website, store and category
$website = Mage::getModel('core/website')->getCollection()->addFieldToFilter("code", "proteinedieet_web")->getFirstItem();
if(!$website->getWebsiteId()){
    $website = Mage::getModel('core/website');
    $website->setCode('proteinedieet_web')
        ->setName('Proteinedieet.net')
        ->save();
}

//Add root category for store
$nameCategoryRoot = 'Proteinedieet.net Root Category';
$categoryRoot = Mage::getModel('catalog/category');
$categoryRoot->setData('name',$nameCategoryRoot);
$categoryRoot->setData('is_active',1);
$categoryRoot->setData('include_in_menu',1);
$categoryRoot->setPath('1');
$categoryRoot->save();

//#addStoreGroup
/** @var $storeGroup Mage_Core_Model_Store_Group */
$storeGroup = Mage::getModel('core/store_group');
$storeGroup->setWebsiteId($website->getId())
    ->setName('Proteinedieet.net')
    ->setRootCategoryId($categoryRoot->getId())
    ->save();
//#addStore
/** @var $store Mage_Core_Model_Store */

$store = Mage::getModel('core/store')->getCollection()->addFieldToFilter("code", "proteinedieet")->getFirstItem();
if(!$store->getStoreId()){
    $store = Mage::getModel('core/store');
    $store->setCode('proteinedieet')
        ->setWebsiteId($storeGroup->getWebsiteId())
        ->setGroupId($storeGroup->getId())
        ->setName('Proteinedieet.net')
        ->setIsActive(1)
        ->save();
}

13. add attribute set
$entityTypeId = $installer->getEntityTypeId('catalog_product');
$attributeSetIds = Mage::getModel('eav/entity_type')->load($entityTypeId)->getAttributeSetCollection()
    ->getColumnValues('attribute_set_id'); // this is the attribute sets associated with this entity
$attributeCode = 'fasens';
$attributeId = $installer->getAttribute($entityTypeId, 'fasens', 'attribute_id');
if(count($attributeSetIds) > 0) {
    foreach ($attributeSetIds as $attributeSetId) {
        $attributeSet = Mage::getModel('eav/entity_attribute_set')->load($attributeSetId);
        $groupId = Mage::getModel('eav/entity_attribute_group')->getCollection()
            ->addFieldToFilter('attribute_set_id',$attributeSetId)
            ->addFieldToFilter('attribute_group_name','General')
            //->setOrder('attribute_group_id',ASC)
            ->getFirstItem()
            ->getId();
        $newItem = Mage::getModel('eav/entity_attribute');
        $newItem->setEntityTypeId($entityTypeId) // catalog_product eav_entity_type id
            ->setAttributeSetId($attributeSetId) // Attribute Set ID
            ->setAttributeGroupId($groupId) // Attribute Group ID
            ->setAttributeId($attributeId) // Attribute ID that need to be added manually
            ->setSortOrder(10) // Sort Order for the attribute in the tab form edit
            ->save();
    }
}

//change label Fasens in store proteinedieet
$store = Mage::getModel('core/store')->load("proteinedieet");
if($store->getStoreId()) {
    $storeId = $store->getStoreId();
    $resource = Mage::getModel('core/resource');
    $readConnection = $resource->getConnection('core_read');
    $tableEntityStore = $resource->getTableName('eav/attribute_label');

    $querySelect = "select attribute_label_id from {$tableEntityStore} where store_id = '{$storeId}' AND attribute_id = '{$attributeId}'";
    $result = $readConnection->fetchOne($querySelect);
    if(!$result) { //if exists then insert
        $readConnection->insert(
            $tableEntityStore,
            array(
                'attribute_id' => "$attributeId",
                'store_id' => "$storeId",
                'value' => 'Vanaf',
            )
        );
    }
    else { //else uipdate
        $readConnection->update(
            $tableEntityStore,
            array('value' => 'Vanaf'),
            array(
                'attribute_label_id = ?' => $result,
            )
        );
    }
}

14.  norouter: $this->norouteAction(); in controller

15. script
Mage::register('isSecureArea', 1);
Mage::app()->setUpdateMode(false);
$baseUrl = Mage::app()->getStore(Mage::app()->getStore()->getStoreId())->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

16: catalog
    Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($productCollection);
        filter product can show;
    $this->helper('catalog/image')->init($_product, 'image')->resize(500, 1030): get image size

    public function getUrlPath($category=null) : get path product
    public function getUrlInStore($params = array()) : get url product store, have url category, param: array('_ignore_category' => true) => not have url category
    public function getProductUrl($useSid = null) : get url product
17: form
    date input
        $fieldset->addField('date', 'date', array(
    'name'               => 'date'
    'label'              => Mage::helper('your_module_name')->__('Date'),
    'after_element_html' => 'Comments',
    'tabindex'           => 1,
    'image'              => $this->getSkinUrl('images/grid-cal.gif'),
    'format'             => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT) ,
    'value'              => date( Mage::app()->getLocale()->getDateStrFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
                                  strtotime('next weekday') )

Chi tiết update ở đây: https://github.com/mage-websd/bug/

0 comments:

Post a Comment