magento的一些小技巧(20120321更新)

2023-05-16

1.加载某个attribute:


    $attributeCode=Mage::getModel('catalog/resource_eav_attribute')
                        ->load($attrbuteId)
                        ->getData("attribute_code");




2.获取某个attribute的所有option:


$attributeObject=Mage::getModel('eav/config')->getAttribute('catalog_product')->load($attributeId);
        $options = $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
$table       = $attributeObject->getBackend()->getTable();



    public function getAttributeOptionsByAttributeCode($entityType, $attributeCode){
   
    $entityType = Mage::getSingleton('eav/config')->getEntityType($entityType);
         $attributeObject = Mage::getModel('customer/attribute')->loadByCode($entityType, $attributeCode);
         return $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
   
    }


或者:

$optionCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
                ->setAttributeFilter($attr_model->getId())
                ->setStoreFilter($storeId, false)
                ->load();

3.获取某个attribute的所有多语言label:


        $attributeLabelsArray= Mage::getResourceModel('eav/entity_attribute')
                        ->getStoreLabelsByAttributeId($attrbuteId);    


4.获取所有的产品属性的attribute:


$attributes = Mage::getResourceModel ( 'catalog/product_attribute_collection' )
             ->addFieldToFilter ( "frontend_input", "select" )
             ->load ();




5.获取某个product的所有attribute:






注:如果是在collection中获取自定义的attribute,必须加addAttributeToSelect(), 如下:


product=Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("dropdownlistone");


6.利用静态block
<?php echo $this->getLayout()->createBlock('clientnumber/widget_name')
                    ->setObject($this->getAddress())
                    ->toHtml() ?>


7.获取某个种类的所有attribute:
$entityTypeId = Mage::getSingleton('eav/config')
                ->getEntityType('catalog_product')
                ->getEntityTypeId();
            $items = Mage::getResourceSingleton('catalog/product_attribute_collection')
                ->setEntityTypeFilter($entityTypeId)
                ->getItems();


8.获取某个attribute_set的所有attribute:


$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
   ->setAttributeSetFilter($attribute_set_id)
   ->load();


 $attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')
            ->load();


9.获取attribute 对象 by attribute code


$muarqspFrom = Mage::getSingleton('eav/config')->getAttribute('catalog_product', '
muarqsp_from');


$attrCollection = Mage::getResourceModel('eav/entity_attribute_collection')
               ->setCodeFilter($attributeCode)
               ->load();
  
10。get store id


$store_id=Mage::getModel('core/store')
    ->getCollection()
    ->addFieldToFilter ( "code", "france_fr" )
    ->getFirstItem()->getData('store_id');
 
or
Mage::getModel('core/store')->load('france_fr')->getId();
 


11.product collection


        $collection = Mage::getResourceModel('catalog/product_collection')
            ->addStoreFilter()
            ->addAttributeToSelect("*")
            ->addAttributeToFilter('entity_id', array('in' => $products))
            ->setPageSize(10)
            ->setCurPage(1);


12.数据库操作


    $dbr = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_read' );
$sql = "select instructor_id,position from product_instructor_link where product_id = $productId";
$result = $dbr->fetchAll($sql);
//$result = $dbr->fetchOne($sql);
$instructors = array();
foreach($result as $item){
$instructors[$item['instructor_id']] = array('position' => $item['position']);
}


            $dbw = Mage::getSingleton('core/resource')->getConnection('core_write');


                  $sql="update catalog_product_entity_datetime set value=NULL where attribute_id=$special_from_date_attribute_id and store_id=$storeId and entity_id=$productId";
                  $dbw->query( $sql );




13. 获取quote中的所有的item




$quote=Mage::getSingleton('checkout/session')->getQuote();
        foreach ($quote->getAllItems() as $item) {
            $proId[]=$item->getProduct()->getId();
        }

14. 获取这个网站所代表的国家的代号(如:FR)

Mage::getModel('directory/country')
              ->load(Mage::getStoreConfig('general/country/default'))->getIso2Code(),


15. 获取后台的配置


Mage::getStoreConfig("clientnumber/total_config/service_ip",0); //get admin config


16. 获取当前的时间


$date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null);
$date = $date->toString('yyyy-MM-dd hh:m:s');


17. generate skin url


Mage::getDesign()->getSkinUrl('images/our_shops/shop_logo_default.jpg');


18. generate select html


$html = $this->getLayout()->createBlock('core/html_select')
            ->setName($name)
            ->setId($id)
            ->setTitle(Mage::helper('directory')->__($title))
            ->setClass('validate-select')
            ->setValue($defValue)
            ->setOptions($options)
            ->getHtml();


19. 删除一个product的所有的images


//Get products gallery attribute
        $attributes = $product->getTypeInstance()->getSetAttributes();


        if (isset($attributes['media_gallery'])) {
            $gallery = $attributes['media_gallery'];
            //Get the images
            $galleryData = $product->getMediaGallery();


            foreach($galleryData['images'] as $image){
                //If image exists
                if ($gallery->getBackend()->getImage($product, $image['file'])) {
                    $gallery->getBackend()->removeImage($product, $image['file']);
                    $filename = Mage::getBaseDir('media') . DS . 'catalog'. DS .'product' . $image['file'];
                    debug('<span style="color: green;">&lt;&lt; unlinked previous image '.$image['file'].' from product '.$product->getSku().'</span>');
                    if (file_exists($filename) && is_file($filename) && is_writeable($filename)){
                        @unlink($filename);
                        debug('<span style="color: green;">(and deleted file '.$filename.')</span>');
                    }else
                        debug('<span style="color: red;">(but couldn\'t delete file '.$filename.')</span>');
                }
            }


        }


20. 获取指定level目录


$parent = Mage::app()->getStore()->getRootCategoryId();
        $categoryModel = Mage::getModel('catalog/category');
        $storeCategories = $categoryModel->getCategories($parent, 2); //获取level 2


21. 发送邮件


 $mailTransport = new Zend_Mail_Transport_Smtp(    '192.168.0.1'   );
 $mail = new Zend_Mail();
            $mail->setBodyText($content);
            $mail->setFrom("hello@example.com", 'Webmaster');
            $mail->addTo("bysoftgz@gmail.com", '');
            $mail->setSubject('Import attribute logs');
            $mail->send($mailTransport);


22.get website config
        
//$website can be string or id
        $import_type = Mage::getModel('core/website')->load($website)->getConfig('maps/stock_import/stock_limit');
        if( $import_type===false ){
   //get admin config
        $import_type=Mage::getStoreConfig('maps/stock_import/import_type',0);
        }


23. 用block创建一个template


<?php echo Mage::getBlockSingleton('inseecode/form')->getInseeFormHtml($this->getAddress(), 'customer');?>


public function getInseeFormHtml($address, $type) {
$this->setTemplate('inseecode/form.phtml');
return $this->toHtml();
}


24.


获取对象的方法:get_class_methods($object)
返回对象的类名:get_class($object)


25. controller 中 添加block


            $this->getLayout()
                ->createBlock('clientnumber/inputform', 'checkout.cart.inputclientnumber')
                ->setTemplate('clientnumber/input.phtml')
                ->toHtml()

26. 在Configuation中添加validate


<validate>validate-number</validate>


27. 获取当前的controller


$moduleName=Mage::app()->getRequest()->getModuleName();
    $controllerName=Mage::app()->getRequest()->getControllerName();
    $actionName=Mage::app()->getRequest()->getActionName();
   
        $fullActionName=$moduleName."_".$controllerName."_".$actionName;


28. can't see load.gif in firefox6


so just remove or comment the id  "#loading-mas" about <!-- opacity: 0.8;-->,it will solve it


29. get attributeSetId by attributeName


Mage::getResourceModel('eav/entity_attribute_set_collection')
            ->addFieldToFilter('attribute_set_name',$attributSetName)
            ->getFirstItem()->getId();


30. get attributeSetName by attributeSetId


Mage::getModel('eav/entity_attribute_set')
            ->load($id)->getData("attribute_set_name");
           
31.修改数据库结构


$installer->getConnection()->addColumn(
    $installer->getTable('enterprise_giftcardaccount/giftcardaccount'),
    'gift_card_type',
    "VARCHAR(200) DEFAULT ''");


$installer->getConnection()->addColumn(
    $installer->getTable('enterprise_giftcardaccount/giftcardaccount'),
    'gift_card_type',
    "TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT  '0'");    


$installer->getConnection()->dropColumn($installer->getTable('eav_attribute'), 'use_in_super_product');
$installer->run("ALTER TABLE `sales_flat_order` CHANGE `is_synced` `is_synced` INT( 4 ) NOT NULL ");


32. 获取登录的用户信息


Mage::getSingleton('customer/session')->getCustomer()


33. 格式化时间


Mage::app()->getLocale()->date($creditMemo->getCreatedAt())->toString('YYYY-MM-dd');


或:


$this->_filterDates($data, array('date_expires'));


    protected function _filterDates($array, $dateFields)
    {
        if (empty($dateFields)) {
            return $array;
        }
        $filterInput = new Zend_Filter_LocalizedToNormalized(array(
            'date_format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)
        ));
        $filterInternal = new Zend_Filter_NormalizedToLocalized(array(
            'date_format' => Varien_Date::DATE_INTERNAL_FORMAT
        ));


        foreach ($dateFields as $dateField) {
            if (array_key_exists($dateField, $array) && !empty($dateField)) {
                $array[$dateField] = $filterInput->filter($array[$dateField]);
                $array[$dateField] = $filterInternal->filter($array[$dateField]);
            }
        }
        return $array;
    }


34. 加减日期


Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss');


35. 打印php调试信息的代码


    $array = debug_backtrace();
   //print_r($array);//信息很齐全
    unset($array[0]);
    foreach($array as $row)
    {
        $html .= $row['file'].':'.$row['line'].'行,调用方法:'.$row['function']."<p>";
    }
    echo $html;
    exit();


36.添加面包翘




在 controller中:


        $this->loadLayout();
        $breadCrumb = $this->getLayout()->getBlock('breadcrumbs'); //这是
        $breadCrumb->addCrumb('home', array(
            'label' => Mage::helper('catalog')->__('Home'),
            'title' => Mage::helper('catalog')->__('Go to Home Page'),
            'link'  => Mage::getBaseUrl(),
        ))->addCrumb('youhui', array(
            'label' => Mage::helper('catalog')->__('youhuihuodong'),
            'title' => Mage::helper('catalog')->__('youhuihuodong'),
            'link'  => $category->getId() ? Mage::getUrl('*/*') : NULL,
        ))
        ;


37. filter in collection


$collection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', array('eq'=>'pending'))
->addFieldToFilter('created_at', array('datetime' => true, 'from'=>"2011-10-10 00:00:00",'to' => Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss')));


38. 日期过滤


        $todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
        $this->_getProductCollection()
            ->addAttributeToFilter('news_from_date', array('or'=> array(
                0 => array('date' => true, 'to' => $todayDate),
                1 => array('is' => new Zend_Db_Expr('null')))
            ), 'left')
            ->addAttributeToFilter('news_to_date', array('or'=> array(
                0 => array('date' => true, 'from' => $todayDate),
                1 => array('is' => new Zend_Db_Expr('null')))
            ), 'left')
            ->addAttributeToFilter(
                array(
                    array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
                    array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
                )
            )
            ->addAttributeToFilter('visibility', array('in' => array(2, 4)))
            ->addAttributeToSort('news_from_date', 'desc')
            ->setPage(1, 4)
        ;


39. 判断日期是否有效


Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $special_from_date, $special_to_date)


40.test code for quote


$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllVisibleItems() as $item) {
           echo $item->getProductId();


}

$quote->collectTotals()->save();


40.日期的比较


//get orders 15 days ago
$collection = Mage::getModel('sales/order')->getCollection()
    ->addFieldToFilter('status', array('eq' => 'pending'))
    ->addFieldToFilter('created_at', array('datetime' => true, 'from' => "2011-10-10 00:00:00", 'to' => Mage::app()->getLocale()
        ->date()
        ->sub("15", Zend_Date::DAY)
        ->toString('YYYY-MM-dd HH:mm:ss'))
    )
;


41. delete confirm js


function confirmSetLocation(message, url){
   if( confirm(message) ) {
       setLocation(url);
   }
   return false;
}


function setLocation(url){
   window.location.href = url;
}


42.在controller中返回blocl html

$this->getResponse()->setBody($this->getLayout()->createBlock('invoicebill/account_content')
            ->setTemplate("bysoft/invoicebill/account/content.phtml")
            ->toHtml());  


43. 获取某个action的url

Mage::getUrl('checkout/process/directOver', array('_secure'=>true));


44. 添加customer attribute


$installer = $this;
$installer->startSetup();

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');


$entityTypeId     = $setup->getEntityTypeId('customer_address');
$attributeSetId   = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);


/*
  add customer address attribute "mobile"
 */
$installer->addAttribute('customer_address', 'mobile1',array(
'label'             => 'Mobile',
'type' => 'varchar',
'input'             => 'text',
'used_in_forms'=> array('customer_register_address','customer_address_edit'),
'source'            => '',
'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible'           => true,
'required'          => true,
'user_defined'      => true,
'searchable'        => false,
'filterable'        => false,
'comparable'        => false,
'visible_on_front'  => true,
'visible_in_advanced_search' => false,
'unique'            => false
));
$setup->addAttributeToGroup(
 $entityTypeId,
 $attributeSetId,
 $attributeGroupId,
 'mobile1',
 '200'  //sort_order
);

$installer->endSetup();


45. 获取product某个 option的label


    public function getProductOptionLable( $optionid=0 )
    {
        $tableName  = Mage::getSingleton('core/resource')->getTableName('eav_attribute_option_value');
$read =Mage::getSingleton('core/resource')->getConnection('core_read');
$storeid=Mage::app()->getStore()->getId();
if($optionid)
{
$sql=" select value from $tableName where option_id=$optionid and store_id=$storeid ";
$query=$read->query($sql);
$row = $query->fetch();

//if can't get value from default store view, then get data from admin store view
if( trim($row['value'])=="" ){
$sql=" select value from $tableName where option_id=$optionid and store_id=0 ";
$query=$read->query($sql);
$row = $query->fetch();
}
}
else
{
$row=array('value'=>'');
}

    return  $row['value'];  
    }


46. 格式化某个日期

Mage::app()->getLocale()->date($_obj->getCreatedAt(), null, null)->toString('yyyy.MM.dd');


47.magento中只单独保存某个attribute的方法

        $order->setData('customer_email',$address->getData("email"));
        $order->getResource()->saveAttribute($order, 'customer_email');

48.  常用的load

Mage::getModel('sales/order')->load();
Mage::getModel('customer/customer')->load();
Mage::getModel('catalog/product')->load();



【文章标题】magento的一些小技巧(20120222更新)
【文章作者】曾健生
【作者邮箱】zengjiansheng1@126.com
【作者QQ】190678908
【作者博客】blog.csdn.net/newjueqi

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

magento的一些小技巧(20120321更新) 的相关文章

  • 如何在 Magento 中更改订单起始编号

    有没有办法在 Magento 中更改订单起始编号而不更改已有的订单号 我只想为所有新订单设置 170000xxxx Thanks Look in eav entity store并找到increment last id 更新此号码 确保en
  • Magento 1.9 注册后重定向客户

    我想在 Magento 1 9 中成功注册后将所有客户重定向到自定义页面 我已经尝试了很多事情 首先 我成功地覆盖了核心客户帐户控制器 我尝试自定义以下操作 创建后动作 successProcessRegistration welcome客
  • Magento 购物车未更新阿拉伯语商店视图中的数量

    我在 Magento 1 8 1 安装中遇到以下问题 我有两种商店视图 英语 默认 和阿拉伯语 在英文商店视图中 如果我将产品添加到购物车 我可以通过在数量框中输入新数量并单击更新购物车来修改数量 这会更改数量和总数 但是 当我切换到阿拉伯
  • 如何更改客户 ID 和订单 ID?

    当前 CustomerID 从 1 开始 而生成的第一个订单已OrderID 100000001 有什么方法可以改变这些字段 所以创建的第一个客户已经 顾客号码900000001并且创建的第一个订单有OrderID 900000001 通过
  • 如何解决PHP扩展“0”必须加载的问题?

    我正在尝试在我的服务器上安装 Magento 我做了一切 正如文档中所写的 我有以下错误 必须加载 PHP 扩展 0 当我尝试在浏览器中的第二页上配置 Magento 时 会发生这种情况 你知道如何解决这个问题吗 如果您安装的是 Magen
  • 在不破坏寻呼机的情况下获取第一个集合项

    我之前发布了一个关于此问题的问题 但我现在有了更多信息 我认为最好发布一个新问题而不是修改 抱歉 如果这不是正确的协议 你可以找到我原来的问题here https stackoverflow com questions 6311646 ma
  • magento - 无法与 PayPal 网关通信

    有什么解决办法吗 我已经在配置 gt gt 系统 gt gt 支付方式 gt gt PayPal支付解决方案中禁用了SSL验证 但还是不行 您需要禁用 SSL 验证 进入后台 系统 gt 配置 gt 付款方式 找到PayPal Expres
  • magento从产品sku获取产品类型

    我如何使用产品 sku 或 id 获取产品类型 简单 可配置 分组 我已加载产品集合并从中尝试通过 product gt getTypeId 但它不打印产品类型 请帮我 Thanks I think product gt getTypeId
  • 安装新的 Magento 扩展需要注销/登录,否则您会在管理页面中收到 404

    两个不同的人告诉我 以下是 Magento 的一个已知问题 安装新扩展时 管理员尝试访问 配置扩展程序 并获取 404 页面 去的方法 解决此问题的方法是注销然后登录到他的管理面板 在设计扩展时有没有办法解决这个问题 这方面有一个悬而未决的
  • Magento Connect 登录后尝试更改为什么路径?

    我每次都会收到错误消息 部署 FTP 错误 登录后无法 chdir 我通过 chmod ing 我的 complete path to magento installation dir 成功完成了第一次连接和设置下载器 至 0777 在 d
  • 在 Magento 中获取过去 24 小时内的订单商品

    我正在尝试获取过去 24 小时内的所有订单商品 我已锁定查询 因此它返回了我需要的内容 order id 和created on 值 order items Mage getResourceModel sales order item co
  • Magento,翻译验证错误消息

    我已经成功创建了原型验证的新规则 现在我需要翻译错误消息 位置 Javascript 中的字符串 但是 我只能翻译所有消息 我的新自定义消息似乎无法翻译 我该如何改变这个 也许你需要一个jstranslator xml里面的文件etc fo
  • reindex 目录 URL 在 magento 中重写永无止境

    我已使用自定义导入配置文件将 6K 类别和 16K 产品导入到 magento 当我尝试重新索引时 除了 目录 URL 重写 之外的所有内容都正常工作 该 目录 URL 重写 一直显示 正在处理 但从未完成 日志和异常文件不显示任何内容 我
  • 在 Magento 控制器中使用 move_uploaded_file

    我是 magento 的新手 我正在 magento 管理中创建用于文件上传的自定义模块 现在我已将上传文件发布到我的模块控制器中 这里我用过move uploaded file将文件上传到与控制器文件夹相同的目录中 下面的代码我用于控制器
  • 无法从配置文件设置基本 URL

    我尝试使用这里描述的方法Magento 将基本网址存储在配置文件中 https stackoverflow com questions 17618236 magento storing base url in a config file从
  • Magento --“SQLSTATE[23000]:违反完整性约束..”客户更新

    迁移服务器后 每次尝试更新客户信息时都会出现错误 我正在使用一个客户激活插件 http www magentocommerce com magento connect vinai extension 489 customer activat
  • Magento 从 Observer 重定向始终有效

    我无法从观察者在 Magento 中创建工作重定向 据我所知 有很多事件都获得了响应对象 在 observer目的 另一种方法是使用类似的东西 Mage app gt getResponse gt setRedirect Mage getU
  • 如何在购物车中显示自定义属性(Magento)

    我尝试了很多东西 但没有一个起作用 我想我可以在产品页面上获取自定义属性 但我想知道 如何在购物车页面中获取它们 属性只是简单的文字 item gt getProduct gt load 将从数据库重新加载所有产品数据 虽然这可行 但请记住
  • 在产品页面上显示最近浏览过的产品

    magento 当前的默认功能是在类别页面的右侧显示最近查看的产品 现在我想在产品页面底部显示相同的内容 使用的 phtml 文件在位置命名为 frontend base default template reports product v
  • Magento 路由器 URL - 需要连字符的路径名称

    假设我使用自定义控制器 其 url 路径 前端名称为 customcategory 好吧 显然如果我有一个名为 TestController php 和indexAction的控制器文件 url 路径将是 customcategory te

随机推荐