我是靠谱客的博主 大力犀牛,这篇文章主要介绍Magento 开发过程中常用的使用技巧与方法,现在分享给大家,希望可以做个参考。

资料来自网络,大部分没有经过验证,仅供参考:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1.属性Attribute 产品属性操作: $product = Mage::getModel('catalog/product')->getCollection()->getFirstItem(); foreach($product->getAttributes() as $att) { $group_id = $att->getData('attribute_group_id'); $group = Mage::getModel('eav/entity_attribute_group')->load($group_id); var_dump($group); } $attrSetName = 'my_custom_attribute'; $attributeSetId = Mage::getModel('eav/entity_attribute_set') ->load($attrSetName, 'attribute_set_name') ->getAttributeSetId(); 1.1 得到Product的属性id,即catalog_product_entity表的entity_type_id字段 $productAttributeSets = $this->getProductAttributeSets(); 1.2 前台页面获取商品属性 $_product->getResource()->getAttribute('cost')->getFrontend()->getValue($_product); Magento的产品属性,在catalog.xml中已经写进去了。你可以在product view中找到 <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml"> <action method="addToParentGroup"><group>detailed_info</group></action> </block> 现在只要在产品详细页(view.phtml)中想要的位置插入 <?php echo $this->getChildHtml('additional') ?> 1.3获取产品属性集 $sets = Mage::getResourceModel('eav/entity_attribute_set_collection') ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId()) ->load() ->toOptionHash(); 1.4 加载某个attribute: $attributeCode=Mage::getModel('catalog/resource_eav_attribute') ->load($attrbuteId) ->getData("attribute_code"); 1.5 获取所有的产品属性的attribute: $attributes = Mage::getResourceModel ( 'catalog/product_attribute_collection' ) ->addFieldToFilter ( "frontend_input", "select" ) ->load (); 1.6 获取某个product的所有attribute: 注:如果是在 collection 中获取自定义的attribute,必须加 addAttributeToSelect(), 如下: $product=Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("dropdownlistone") 1.7 获取某个种类的所有attribute: $entityTypeId = Mage::getSingleton('eav/config') ->getEntityType('catalog_product') ->getEntityTypeId(); $items = Mage::getResourceSingleton('catalog/product_attribute_collection') ->setEntityTypeFilter($entityTypeId) ->getItems(); 1.8 获取某个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(); 1.9 获取某个attribute的所有多语言label: $attributeLabelsArray= Mage::getResourceModel('eav/entity_attribute') ->getStoreLabelsByAttributeId($attrbuteId); 1.10 获取某个attribute_set的所有attribute: $attributes = Mage::getResourceModel('catalog/product_attribute_collection') ->setAttributeSetFilter($attribute_set_id) ->load(); $attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection') ->load(); 1.11 获取attribute 对象 by attribute code $muarqspFrom = Mage::getSingleton('eav/config')->getAttribute('catalog_product', ' muarqsp_from'); $attrCollection = Mage::getResourceModel('eav/entity_attribute_collection') ->setCodeFilter($attributeCode) ->load() 1.12 通过attributeName得到 attributeSetId Mage::getResourceModel('eav/entity_attribute_set_collection') ->addFieldToFilter('attribute_set_name',$attributSetName) ->getFirstItem()->getId(); 1.13 通过 attributeSetId得到attributeSetName Mage::getModel('eav/entity_attribute_set') ->load($id)->getData("attribute_set_name"); 2. 产品相关操作 2.1 产品缩略图 $_thumb = Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(50, 50)->setWatermarkSize('30x10'); 2.2 product collection $collection = Mage::getResourceModel('catalog/product_collection') ->addStoreFilter() ->addAttributeToSelect("*") ->addAttributeToFilter('entity_id', array('in' => $products)) ->setPageSize(10) ->setCurPage(1); 2.3 删除一个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>'); } } } 3. website 获取对象的方法:get_class_methods($object) 返回对象的类名:get_class($object) 3.1得到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() 3.2 得到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); } 获取后台的配置 Mage::getStoreConfig("clientnumber/total_config/service_ip",0); //get admin config 3.3 generate skin url Mage::getDesign()->getSkinUrl('images/our_shops/shop_logo_default.jpg'); 3.4 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(); 3.5 获取这个网站所代表的国家的代号(如:FR) Mage::getModel('directory/country') ->load(Mage::getStoreConfig('general/country/default'))->getIso2Code(), 3.6 获取登录的用户信息 Mage::getSingleton('customer/session')->getCustomer() 3.7 session,cookie 1) 获取session $session = Mage::getSingleton('customer/session'); 2) session,cookie设置 (1) Model: Mage::getModel(‘core/cookie’); Mage::getModel(‘core/session’); (2)Set Method: Mage::getSingleton(‘core/cookie’)->set(‘name’,'value’); Mage::getSingleton(‘core/session’)->set(‘name’,'value’); (3)Get method: Mage::getSingleton(‘core/cookie’)->get(‘name’); Mage::getSingleton(‘core/session’)->get(‘name’); 3.8 Request对象 Mage::app()->getRequest() 3.9 调用Model对象 Mage::getModel('infinity/model'); 3.10 输出配置文件 //header(‘Content-Type: text/xml’); header(‘Content-Type: text/plain’); echo $config = Mage::getConfig() ->loadModulesConfiguration(‘system.xml’) ->getNode() ->asXML(); exit; 3.11 得到Magento分类的URL Mage::getModel('catalog/category')->load(17)->getUrl(); 3.12 build your URL with valid keys Mage::helper("adminhtml")->getUrl("mymodule/adminhtml_mycontroller/myaction/",array("param1"=>1,"param2"=>2)); 3.13 create key values Mage::getSingleton('adminhtml/url')->getSecretKey("adminhtml_mycontroller","myaction"); 3.14 disable security feature in the admin panel 在管理面板中禁用安全功能 admin panel -> System -> Configuration -> Admin section: “Add Secret key to Urls”. 3.15 后台模块跳转: Mage::app()->getResponse()->setRedirect(Mage::helper('adminhtml')->getUrl("adminhtml/promo_quote/index")); 3.16 get a drop down lists options for a mulit-select attribute 多属性选择下拉列表 $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_id'); foreach ( $attribute->getSource()->getAllOptions(true, true) as $option) { $attributeArray[$option['value']] = $option['label']; } 3.17 获取栏目图片 public function getImageUrl($category) { return Mage::getModel('catalog/category')->load($category->getId())->getImageUrl(); } public function getThumbnailUrl($category) { $image=Mage::getModel('catalog/category')->load($category->getId())->getThumbnail(); if ($image) { $url = Mage::getBaseUrl('media').'catalog/category/'.$image; } return $url; } 3.18 判断是否首页:$this->getIsHomePage() Mage::getSingleton('cms/page')->getIdentifier() == 'home' && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms' ) 3.19 主题颜色 $attributes = $_product->getAttributes(); $themeColor = $attributes['theme_color']->getFrontend()->getValue($_product); 3.20 获取configurable产品simple product if($_product->getTypeId() == "configurable"): $ids = $_product->getTypeInstance()->getUsedProductIds(); foreach ($ids as $id) : $simpleproduct = Mage::getModel('catalog/product')->load($id); $simpleproduct->getName()." - ".(int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty(); $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product); endforeach; endif; 3.21 get the attributes of Configurable Product. $attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product); 3.22 当前路径 $currentUrl = $this->helper('core/url')->getCurrentUrl(); 3.23 通过资源配置方式创建目录 $installer = $this; $installer->startSetup(); // make directory for font cache try { $domPdfFontCacheDir = join(DS, array('lib', 'Symmetrics', 'dompdf', 'fonts')); $domPdfFontCacheDir = Mage::getBaseDir('var') . DS . $domPdfFontCacheDir; if (!file_exists($domPdfFontCacheDir)) { mkdir($domPdfFontCacheDir, 0777, true); } } catch(Exception $e) { throw new Exception( 'Directory ' . $domPdfFontCacheDir . ' is not writable or couldn't be ' . 'created. Please do it manually.' . $e->getMessage() ); } $installer->endSetup(); 3.24 在controllers 实现跳转 Mage::app()->getFrontController() ->getResponse() ->setRedirect('http://your-url.com'); ××××× $cms_id = Mage::getSingleton('cms/page')->getIdentifier(); $cms_title = Mage::getSingleton('cms/page')->getTitle(); $cms_content = Mage::getSingleton('cms/page')->getContent(); 3.25 获取当前站点货币符号 $storeId = (int) $this->getRequest()->getParam('store', 0); $store=Mage::app()->getStore($storeId); $currencyCode=$store->getBaseCurrency()->getCode(); $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId); $attributeData = $attribute->getData(); $frontEndLabel = $attributeData['frontend_label']; $attributeOptions = $attribute->getSource()->getAllOptions(); 3.26 设置meta信息 $template = Mage::getConfig()->getNode('global/page/layouts/'.Mage::getStoreConfig("featuredproducts/general/layout").'/template'); this->loadLayout(); $this->getLayout()->getBlock('root')->setTemplate($template); $this->getLayout()->getBlock('head')->setTitle($this->__(Mage::getStoreConfig("featuredproducts/general/meta_title"))); $this->getLayout()->getBlock('head')->setDescription($this->__(Mage::getStoreConfig("featuredproducts/general/meta_description"))); $this->getLayout()->getBlock('head')->setKeywords($this->__(Mage::getStoreConfig("featuredproducts/general/meta_keywords"))); $this->renderLayout(); 4. magento中调用static block(静态块)的几种方法 通常情况下,在magento程序中使用静态块用来创建广告、促销图片及静态的内容等等 以下以在magento中利用静态块来创建首页两侧的广告 在后台创建一个ad1静态块 (1)如果要在.phtml文件中直接调用这个静态块,那可以采用以下方法 <?php $block = Mage::getModel(‘cms/block’) ->setStoreId(Mage::app()->getStore()->getId()) ->load(‘ad1′); $content = $block->getContent(); // Block的原始内容已经获得 $processor = Mage::getModel(‘core/email_template_filter’); echo $html = $processor->filter($content); ?> Mage::getModel(‘core/email_template_filter’)->filter()是必须的,因为Static Block里可能包含Magento的模板语言(如:{{store url=”"}}),fiter将翻译成实际的值 Magento中调用静态Block主要有两个地方。 是否感觉这代码太长了呢,那你还可以这么写 <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('order_form')->toHtml() ?> (2)在CMS页面的Content中调用这个静态块呢?你可以采用以下方法 {{block type=”cms/block” name=”cms_ad1_block” block_id=”ad1″ }} (3)在layout中调用静态块 <reference name=”footer”> <block type=”cms/block” name=”ad1″ before=”-”> <action method=”setBlockId”><block_id>ad1</block_id></action> </block> </reference> 5. 时间 5.1 获取当前的时间 1) $date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null); $date = $date->toString('yyyy-MM-dd hh:m:s'); 2) Mage::getModel('core/date')->date(); date("Y-m-d", Mage::getModel('core/date')->timestamp(time())); Magento中默认时区为GMT, 不能直接使用time(), date()等方法,否则会出现时间差。 用下面的方法取当前时间(和后台设置的时区一致): date("Y-m-d", Mage::getModel('core/date')->timestamp(time())); 获得UTC时间的方法 $date = Mage::app()->getLocale()->utcDate($store, $value, true, Varien_Date::DATETIME_INTERNAL_FORMAT); $this->setData(‘date_start’, $date->toString(Varien_Date::DATETIME_INTERNAL_FORMAT)); $date = Mage::app()->getLocale()->date(); $dStr = $date->toString(Varien_Date::DATETIME_INTERNAL_FORMAT); //$dStr 可以用于存储到数据库的datetime字段. 5.2 格式化时间 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; } 5.3 加减日期 Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss'); 5.4 日期过滤 $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); 5.5 判断日期是否有效 Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $special_from_date, $special_to_date) 6. collection 6.1 在Configuation中添加validate <validate>validate-number</validate> 6.2 获取当前的controller $moduleName=Mage::app()->getRequest()->getModuleName(); $controllerName=Mage::app()->getRequest()->getControllerName(); $actionName=Mage::app()->getRequest()->getActionName(); $fullActionName=$moduleName."_".$controllerName."_".$actionName; 6.3 controller 中 添加block $this->getLayout() ->createBlock('clientnumber/inputform', 'checkout.cart.inputclientnumber') ->setTemplate('clientnumber/input.phtml') ->toHtml() 6.5添加breadcrumbs在 controller中(为前端页面添加面包屑,如 Category/product这里的导航 ): 在controller文件中填充面包屑数据,在block的phtml文件中显示 1). 在controller的Action方法中 //判断是否存在名字为breadcrumbs的Block(默认都存在,后面有说明) if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) { // 该条目有目标链接地址 $breadcrumbsBlock->addCrumb('category', array( 'label' => 'Category', 'title' => 'Category Title', 'link' => 'http://www.google.com', 'readonly' => true, )); // 该条目没有链接地址,一般作为最后一个条目 $breadcrumbsBlock->addCrumb('product', array('label' => Mage::helper('catalog')->__('Product'))); } 2). 在该action对应的Layout文件中添加Block Xml代码: <block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/> 相应的在你的Block的合适位置输出面包屑 <?php echo $this->getChildHtml('breadcrumbs'); ?> 以上描述的是面包屑的一般原理,Magento实际上已经默认声明了Block Xml代码: <block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/> 而且默认的几个layout模板文件(page/1column.phtml,page/2columns-left.phtml..等)已经做了 <?php echo $this->getChildHtml('breadcrumbs'); ?> 6.6 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'))); 6.7 在controllers 实现跳转 Mage::app()->getFrontController() ->getResponse() ->setRedirect('http://your-url.com'); 7. 获取quote中的所有的item $quote=Mage::getSingleton('checkout/session')->getQuote(); foreach ($quote->getAllItems() as $item) { $proId[]=$item->getProduct()->getId(); } 8. 发送邮件 $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); 9. block 9.1 用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(); } 9.2 利用静态block <?php echo $this->getLayout()->createBlock('clientnumber/widget_name') ->setObject($this->getAddress()) ->toHtml() ?> 9.3 调用static block 1) 如果要在.phtml文件中直接调用这个静态块,那可以采用以下方法 <?php $block = Mage::getModel('cms/block') ->setStoreId(Mage::app()->getStore()->getId()) ->load('order_form'); $content = $block->getContent(); // Block的原始内容已经获得 $processor = Mage::getModel('core/email_template_filter'); echo $html = $processor->filter($content); ?> Mage::getModel(‘core/email_template_filter’)->filter()是必须的, 因为Static Block里可能包含Magento的模板语言(如:{{store url=”"}}),fiter将翻译成实际的值 Magento中调用静态Block主要有两个地方。 是否感觉这代码太长了呢,那你还可以这么写 <?php echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘order_form’)->toHtml() ?> 2) magento中的CMS功能,可以让我们很方便的在PHP中嵌入经常要更改的内容,这样我们可以通过在CMS中直接修改文章内容, 而不需要去修改源代码,最经典的就是我们的首页就是写在CMS Static block中的。 如何在CMS页面的Content中调用这个静态块呢?你可以采用以下方法 {{block type=”cms/block” name=”cms_test_block” block_id=”order_form” }} 将里面order_form改成你的静态块对应的block_id则可 3) 怎么样在layout中调用静态块呢? <reference name=”footer”> <block type=”cms/block” name=”order_form” before=”-”> <action method=”setBlockId”><block_id>order_form</block_id></action> </block> </reference> magento中调用CMS静态块(Static Block)教程到此就结束了,你应该能够灵活的运用magento中的静态块了吧! 10. 获取指定level目录 $parent = Mage::app()->getStore()->getRootCategoryId(); $categoryModel = Mage::getModel('catalog/category'); $storeCategories = $categoryModel->getCategories($parent, 2); //获取level 2 11. 数据库 11.1 修改数据库结构 $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 "); 11.2 magento操作数据库 eg.1 $this->getSelect() ->from(array('e' => $this->getEntity()->getFlatTableName()), null) ->columns(array('status' => new Zend_Db_Expr(Mage_Catalog_Model_Product_Status::STATUS_ENABLED))); $this->addAttributeToSelect(array('entity_id', 'type_id', 'attribute_set_id')); if ($this->getFlatHelper()->isAddChildData()) { $this->getSelect() ->where('e.is_child=?', 0); $this->addAttributeToSelect(array('child_id', 'is_child')); } $select=$this->getSelect()->from(array('e'=>$this->getEntity()->getEntityTable())); $select->joinRight( array('t'=>'test_product'), 'e.entity_id = t.entity_id', array() ); eg.2 $resource = Mage::getSingleton('core/resource'); $read= $resource->getConnection('read'); $tempTable = $resource->getTableName('eav_attribute'); //用其他表也是可以的 $wheres = "`entity_type_id` =4 "; //SELECT count(*) as num FROM `eav_attribute` WHERE (`entity_type_id` =4 ) //$select = $read->select() ->from($tempTable, array('count(*) as num')) ->where($wheres); //SELECT `eav_attribute`.* FROM `eav_attribute` WHERE (`entity_type_id` =4 ) //$select = $read->select() ->from($tempTable) ->where($wheres); //SELECT `eav_attribute`.`attribute_code` FROM `eav_attribute` WHERE (`entity_type_id` =4 ) $select = $read->select() ->from($tempTable, array('attribute_code')) ->where($wheres); $result = $read->fetchAll($select); eg.3 $resource = Mage::getSingleton('core/resource'); $read= $resource->getConnection('read'); $select = "select * from catalog_product_entity where entity_id =5"; $result = $read->fetchAll($select); //$result = $read->fetchOne($select); $instructors = array(); foreach($result as $item){ $instructors[$item['entity_id']] = array('position' => $item['sku']); } $dbw = Mage::getSingleton('core/resource')->getConnection('write'); $sql="update catalog_product_entity set sku='sku11' where entity_id=5"; $dbw->query( $sql ); magento--调用数据库的步骤--使用magento机制访问数据库 在后台附加一个属性,譬如品牌.然后,在产品详细页面,把同个品牌的产品都调用出来!下面是程序代码 public function getOtherProduct(){ $_producty = $this->getProduct(); $_biaoshi = $_producty['biaoshi']; $resource = Mage::getSingleton('core/resource'); $read = $resource->getConnection('catalog_read'); $categoryProductTable = $resource->getTableName('catalog/category_product'); //$productEntityIntTable = $resource->getTableName('catalog/product_entity_int'); // doesn't work $productEntityIntTable = (string)Mage::getConfig()->getTablePrefix().'catalog_product_entity_int'; $eavAttributeTable = $resource->getTableName('eav/attribute'); $product_attribute_valueTable = (string)Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar'; //return $product_attribute_valueTable; // var_dump($productEntityIntTable); exit; // Query database for featured product $select = $read->select() ->from(array('cp'=>$categoryProductTable)) // ->join(array('pei'=>$productEntityIntTable),'pei.entity_id=cp.product_id', array()) ->join(array('pss'=>$product_attribute_valueTable),'pss.entity_id=cp.product_id',array()) ->joinNatural(array('ea'=>$eavAttributeTable)) // ->joinNatural(array('pss'=>$product_attribute_valueTable)) // ->where('cp.category_id=?', $categoryId) ->where('pss.value=?',$_biaoshi) // ->where('ea.a') ->where('ea.attribute_code="biaoshi"'); $rows = $read->fetchAll($select); $ids = array(); foreach($rows AS $row) { $ids[] = $row['product_id']; } $ret = implode(',', $ids); $ids = array_unique($ids); // return $ids; $productList = array(); foreach($ids as $idq){ $product = Mage::getModel('catalog/product')->load($idq); $productList[] = $product; } // $product = Mage::getModel('catalog/product')->load($this->getProductId()); // $collection = Mage::getModel('catalog/product')->getCollection(); // $collection->getSelect()->where('e.entity_id in (?)', $ids); // $collection->addAttributeToSelect('*'); // $productList = $collection->load(); return $productList; // return $ids; } 如果你想成为一个magento二次开发程序员,上面的代码,你会感兴趣 12. 打印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(); 13. test code for quote $quote=Mage::getSingleton('checkout/session')->getQuote(); foreach ($quote->getAllVisibleItems() as $item) { echo $item->getProductId(); }

最后

以上就是大力犀牛最近收集整理的关于Magento 开发过程中常用的使用技巧与方法的全部内容,更多相关Magento内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部