在view.phtml中获取所选产品的ID-s(Magento)

时间:2016-07-18 13:04:42

标签: magento

我想在管理面板产品编辑器中添加自定义标签,并在表格中显示所有产品,就像在“最近的产品”或“向上销售”标签中一样。

之后,我想在view.phtml中获取所选产品的ID。从那里我将处理我的代码。

如果遵循此代码,请遵循本教程。

安装程序脚本 app / code / community / Inchoo / CustomLinkedProducts / sql / inchoo_customlinkedproducts_setup / install-0.0.1.php

<?php

$installer = $this;

$data = array(
    array(
        'link_type_id'  => Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link::LINK_TYPE_CUSTOM,
        'code'          => 'custom'
    )
);

foreach ($data as $bind) {
    $installer->getConnection()->insertForce($installer->getTable('catalog/product_link_type'), $bind);
}

$data = array(
    array(
        'link_type_id'                  => Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link::LINK_TYPE_CUSTOM,
        'product_link_attribute_code'   => 'position',
        'data_type'                     => 'int'
    )
);

$installer->getConnection()->insertMultiple($installer->getTable('catalog/product_link_attribute'), $data);

管理界面 app / code / community / Inchoo / CustomLinkedProducts / Block / Adminhtml / Catalog / Product / Edit / Tab.php

<?php

class Inchoo_CustomLinkedProducts_Block_Adminhtml_Catalog_Product_Edit_Tab
extends Mage_Adminhtml_Block_Widget
implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
    public function canShowTab() 
    {
        return true;
    }

    public function getTabLabel() 
    {
        return $this->__('Custom Linked Products');
    }

    public function getTabTitle()        
    {
        return $this->__('Custom Linked Products');
    }

    public function isHidden()
    {
        return false;
    }

    public function getTabUrl() 
    {
        return $this->getUrl('*/*/custom', array('_current' => true));
    }

    public function getTabClass()
    {
        return 'ajax';
    }    
}

控制器 app / code / community / Inchoo / CustomLinkedProducts / controllers / Adminhtml / Catalog / ProductController.php

<?php

require_once(Mage::getModuleDir('controllers','Mage_Adminhtml').DS.'Catalog'.DS.'ProductController.php');

class Inchoo_CustomLinkedProducts_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
    public function customAction()
    {
        $this->_initProduct();
        $this->loadLayout();
        $this->getLayout()->getBlock('catalog.product.edit.tab.custom')
            ->setProductsCustom($this->getRequest()->getPost('products_custom', null));
        $this->renderLayout();
    }

    public function customGridAction()
    {
        $this->_initProduct();
        $this->loadLayout();
        $this->getLayout()->getBlock('catalog.product.edit.tab.custom')
            ->setProductsRelated($this->getRequest()->getPost('products_custom', null));
        $this->renderLayout();
    }     
}

管理员布局 app / design / adminhtml / default / default / layout / inchoo_customlinkedproducts.xml

<?xml version="1.0" encoding="UTF-8"?>

<layout>

    <adminhtml_catalog_product_edit>
        <reference name="product_tabs">
            <action method="addTab">
                <name>custom</name>
                <block>inchoo_customlinkedproducts/adminhtml_catalog_product_edit_tab</block>
            </action>
        </reference>
    </adminhtml_catalog_product_edit>

    <adminhtml_catalog_product_custom>
        <block type="core/text_list" name="root" output="toHtml">
            <block type="inchoo_customlinkedproducts/adminhtml_catalog_product_edit_tab_custom" name="catalog.product.edit.tab.custom"/>
            <block type="adminhtml/widget_grid_serializer" name="custom_grid_serializer">
                <reference name="custom_grid_serializer">
                    <action method="initSerializerBlock">
                        <grid_block_name>catalog.product.edit.tab.custom</grid_block_name>
                        <data_callback>getSelectedCustomProducts</data_callback>
                        <hidden_input_name>links[custom]</hidden_input_name>
                        <reload_param_name>products_custom</reload_param_name>
                    </action>
                    <action method="addColumnInputName">
                        <input_name>position</input_name>
                    </action>
                </reference>
            </block>
        </block>
    </adminhtml_catalog_product_custom>

    <adminhtml_catalog_product_customgrid>
        <block type="core/text_list" name="root" output="toHtml">
            <block type="inchoo_customlinkedproducts/adminhtml_catalog_product_edit_tab_custom" name="catalog.product.edit.tab.custom"/>
        </block>
    </adminhtml_catalog_product_customgrid>

</layout>

自定义标签 app / code / community / Inchoo / CustomLinkedProducts / Block / Adminhtml / Catalog / Product / Edit / Tab / Custom.php

class Inchoo_CustomLinkedProducts_Block_Adminhtml_Catalog_Product_Edit_Tab_Custom extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('custom_product_grid');
        $this->setDefaultSort('entity_id');
        $this->setUseAjax(true);
        if ($this->_getProduct()->getId()) {
            $this->setDefaultFilter(array('in_products' => 1));
        }
        if ($this->isReadonly()) {
            $this->setFilterVisibility(false);
        }
    }

    protected function _getProduct()
    {
        return Mage::registry('current_product');
    }

    protected function _addColumnFilterToCollection($column)
    {
        // Set custom filter for in product flag
        if ($column->getId() == 'in_products') {
            $productIds = $this->_getSelectedProducts();
            if (empty($productIds)) {
                $productIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('entity_id', array('in' => $productIds));
            } else {
                if($productIds) {
                    $this->getCollection()->addFieldToFilter('entity_id', array('nin' => $productIds));
                }
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }
        return $this;
    }

    protected function _prepareCollection()
    {
        $collection = Mage::getModel('catalog/product_link')->useCustomLinks()
            ->getProductCollection()
            ->setProduct($this->_getProduct())
            ->addAttributeToSelect('*');

        if ($this->isReadonly()) {
            $productIds = $this->_getSelectedProducts();
            if (empty($productIds)) {
                $productIds = array(0);
            }
            $collection->addFieldToFilter('entity_id', array('in' => $productIds));
        }

        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    public function isReadonly()
    {
        return $this->_getProduct()->getCustomReadonly();
    }

    protected function _prepareColumns()
    {
        if (!$this->isReadonly()) {
            $this->addColumn('in_products', array(
                'header_css_class'  => 'a-center',
                'type'              => 'checkbox',
                'name'              => 'in_products',
                'values'            => $this->_getSelectedProducts(),
                'align'             => 'center',
                'index'             => 'entity_id'
            ));
        }

        $this->addColumn('entity_id', array(
            'header'    => Mage::helper('catalog')->__('ID'),
            'sortable'  => true,
            'width'     => 60,
            'index'     => 'entity_id'
        ));

        $this->addColumn('name', array(
            'header'    => Mage::helper('catalog')->__('Name'),
            'index'     => 'name'
        ));

        $this->addColumn('type', array(
            'header'    => Mage::helper('catalog')->__('Type'),
            'width'     => 100,
            'index'     => 'type_id',
            'type'      => 'options',
            'options'   => Mage::getSingleton('catalog/product_type')->getOptionArray(),
        ));

        $sets = Mage::getResourceModel('eav/entity_attribute_set_collection')
            ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId())
            ->load()
            ->toOptionHash();

        $this->addColumn('set_name', array(
            'header'    => Mage::helper('catalog')->__('Attrib. Set Name'),
            'width'     => 130,
            'index'     => 'attribute_set_id',
            'type'      => 'options',
            'options'   => $sets,
        ));

        $this->addColumn('status', array(
            'header'    => Mage::helper('catalog')->__('Status'),
            'width'     => 90,
            'index'     => 'status',
            'type'      => 'options',
            'options'   => Mage::getSingleton('catalog/product_status')->getOptionArray(),
        ));

        $this->addColumn('visibility', array(
            'header'    => Mage::helper('catalog')->__('Visibility'),
            'width'     => 90,
            'index'     => 'visibility',
            'type'      => 'options',
            'options'   => Mage::getSingleton('catalog/product_visibility')->getOptionArray(),
        ));

        $this->addColumn('sku', array(
            'header'    => Mage::helper('catalog')->__('SKU'),
            'width'     => 80,
            'index'     => 'sku'
        ));

        $this->addColumn('price', array(
            'header'        => Mage::helper('catalog')->__('Price'),
            'type'          => 'currency',
            'currency_code' => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
            'index'         => 'price'
        ));

        $this->addColumn('position', array(
            'header'            => Mage::helper('catalog')->__('Position'),
            'name'              => 'position',
            'type'              => 'number',
            'validate_class'    => 'validate-number',
            'index'             => 'position',
            'width'             => 60,
            'editable'          => !$this->_getProduct()->getCustomReadonly(),
            'edit_only'         => !$this->_getProduct()->getId()
        ));

        return parent::_prepareColumns();
    }

    public function getGridUrl()
    {
        return $this->getData('grid_url')
            ? $this->getData('grid_url')
            : $this->getUrl('*/*/customGrid', array('_current' => true));
    }

    protected function _getSelectedProducts()
    {
        $products = $this->getProductsCustom();
        if (!is_array($products)) {
            $products = array_keys($this->getSelectedCustomProducts());
        }
        return $products;
    }

    public function getSelectedCustomProducts()
    {
        $products = array();
        foreach (Mage::registry('current_product')->getCustomProducts() as $product) {
            $products[$product->getId()] = array('position' => $product->getPosition());
        }
        return $products;
    }    
}

应用程序/代码/小区/ Inchoo / CustomLinkedProducts /型号/目录/产品/ Link.php

<?php

class Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link extends Mage_Catalog_Model_Product_Link
{
    const LINK_TYPE_CUSTOM   = 6;

    public function useCustomLinks()
    {
        $this->setLinkTypeId(self::LINK_TYPE_CUSTOM);
        return $this;
    }

    public function saveProductRelations($product)
    {
        parent::saveProductRelations($product);

        $data = $product->getCustomLinkData();
        if (!is_null($data)) {
            $this->_getResource()->saveProductLinks($product, $data, self::LINK_TYPE_CUSTOM);
        } 
    }
}

应用程序/代码/小区/ Inchoo / CustomLinkedProducts /型号/目录/ Product.php

<?php

class Inchoo_CustomLinkedProducts_Model_Catalog_Product extends Mage_Catalog_Model_Product
{
    public function getCustomProducts()
    {
        if (!$this->hasCustomProducts()) {
            $products = array();
            $collection = $this->getCustomProductCollection();
            foreach ($collection as $product) {
                $products[] = $product;
            }
            $this->setCustomProducts($products);
        }
        return $this->getData('custom_products');
    }

    public function getCustomProductIds()
    {
        if (!$this->hasCustomProductIds()) {
            $ids = array();
            foreach ($this->getCustomProducts() as $product) {
                $ids[] = $product->getId();
            }
            $this->setCustomProductIds($ids);
        }
        return $this->getData('custom_product_ids');
    }

    public function getCustomProductCollection()
    {
        $collection = $this->getLinkInstance()->useCustomLinks()
            ->getProductCollection()
            ->setIsStrongMode();
        $collection->setProduct($this);
        return $collection;
    }

    public function getCustomLinkCollection()
    {
        $collection = $this->getLinkInstance()->useCustomLinks()
            ->getLinkCollection();
        $collection->setProduct($this);
        $collection->addLinkTypeIdFilter();
        $collection->addProductIdFilter();
        $collection->joinAttributes();
        return $collection;
    }   
}

Fontend layout app \ design \ frontend \ rwd \ default \ layout.xml

<?xml version="1.0" encoding="UTF-8"?>

<layout>

    <catalog_product_view translate="label">
        <reference name="right">
            <block type="inchoo_customlinkedproducts/catalog_product_list_custom" name="catalog.product.custom" before="-" template="inchoo/catalog/product/list/custom.phtml"/>
        </reference>
    </catalog_product_view>    

</layout>

自定义phtml app \ design \ frontend \ rwd \ default \ template \ inchoo \ catalog \ product \ list.php

<?php if($this->getItems()->getSize()): ?>
<div class="block block-custom">
    <div class="block-title">
        <strong><span><?php echo $this->__('Custom Linked Products') ?></span></strong>
    </div>
    <div class="block-content">
        <p class="block-subtitle"><?php echo $this->__('Check items to add to the cart or') ?>&nbsp;<a href="#" onclick="selectAllCustom(this); return false;"><?php echo $this->__('select all') ?></a></p>
        <ol class="mini-products-list" id="block-custom">
        <?php foreach($this->getItems() as $_item): ?>
            <li class="item">
                <?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
                    <?php if (!$_item->getRequiredOptions()): ?>
                        <input type="checkbox" class="checkbox custom-checkbox" id="custom-checkbox<?php echo $_item->getId() ?>" name="custom_products[]" value="<?php echo $_item->getId() ?>" />
                    <?php endif; ?>
                <?php endif; ?>
                <div class="product">
                    <a href="<?php echo $_item->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_item->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" /></a>
                    <div class="product-details">
                        <p class="product-name"><a href="<?php echo $_item->getProductUrl() ?>"><?php echo $this->htmlEscape($_item->getName()) ?></a></p>
                        <?php echo $this->getPriceHtml($_item, true, '-custom') ?>
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <a href="<?php echo $this->getAddToWishlistUrl($_item) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a>
                        <?php endif; ?>
                    </div>
                </div>
            </li>
        <?php endforeach ?>
        </ol>
        <script type="text/javascript">decorateList('block-custom', 'none-recursive')</script>
    </div>
    <script type="text/javascript">
    //<![CDATA[
    $$('.custom-checkbox').each(function(elem){
        Event.observe(elem, 'click', addCustomToProduct)
    });

    var customProductsCheckFlag = false;
    function selectAllCustom(txt){
        if (customProductsCheckFlag == false) {
            $$('.custom-checkbox').each(function(elem){
                elem.checked = true;
            });
            customProductsCheckFlag = true;
            txt.innerHTML="<?php echo $this->__('unselect all') ?>";
        } else {
            $$('.custom-checkbox').each(function(elem){
                elem.checked = false;
            });
            customProductsCheckFlag = false;
            txt.innerHTML="<?php echo $this->__('select all') ?>";
        }
        addCustomToProduct();
    }

    function addCustomToProduct(){
        var checkboxes = $$('.custom-checkbox');
        var values = [];
        for(var i=0;i<checkboxes.length;i++){
            if(checkboxes[i].checked) values.push(checkboxes[i].value);
        }
        if($('custom-products-field')){
            $('custom-products-field').value = values.join(',');
        }
    }
    //]]>
    </script>
</div>
<?php endif ?>

等\模块\ Inchoo_CustomLinkedProducts.xml

<?xml version="1.0" encoding="UTF-8"?>

<config>
    <modules>
        <Inchoo_CustomLinkedProducts>
            <active>true</active>
            <codePool>community</codePool>
        </Inchoo_CustomLinkedProducts>
    </modules>
</config>

所以问题是如何在view.phtml中获取产品的ID-s。我尝试了一切,但它不起作用。然后我就像教程展示一样克隆了Magento的相关产品块inchoo_customrelatedproducts / catalog_product_list_custom并且它可以工作但是相关的产品没有用。

有没有办法从这段代码中获取view.phtml中所选产品的ID?

1 个答案:

答案 0 :(得分:0)

您应该尝试创建新的属性组。