Magento的+ JQuery的+阿贾克斯 - 如何重装只是部分我的自定义模块,而不是整个区块的?我的、区块、自定义、重装

2023-09-10 17:50:40 作者:伪淑女

我刚刚给在5天内,在这里你可以选择一些属性创建一个简单的产品配置,为Magento的模板任务,并计算出的价格为您,淡化了一个新的形象,改变添加到购物车按钮到新的产品

在此我不得不在PHP或jQuery和Magento中没有经验只是一些基本知识(以前从来没有做过一个自定义模块。)我唯一的编程背景是OOP游戏在动作脚本3。

到目前为止,我的code ++工程,不知何故。我有一些变量,我可以点击一些单选按钮和变量的变化是通过Ajax的方法更新。由于URL我的块索引方法被调用这不只是加载和渲染我的布局。之后,我加入了返回的HTML(这是我的整个块)我最外面的div的父母在我的块。它的工作原理,但我似乎无法找到一个方法来制作动画的变化,似乎有种很慢,如果阿贾克斯每个用户只需改变一次重建整个街区一个选项。

有没有更优雅的方式,只是重新加载修改的部分,顺畅动画的变化,让我想起块所做的投入?

下面是下载源文件: http://www.roflxd.de/doorconfig.zip

我重装系统,系统自动装完后出现,无法启动出现OXCOOOOOOF,希望高手指点下怎么重装安装,在线

如果您需要看网站本身,请给我发短信:)

在此先感谢!

我的座PHTML:

 < PHP

                $类型=简单;
                $颜色='FFFFFF';
                $大小='2500x1800';

                如果(使用isset($ _ POST ['色'])){
                    $颜色=#。 $ _ POST ['色'];
                }

                如果(使用isset($ _ POST ['型'])){
                    $型= $ _ POST ['类型'];
                }

                如果(使用isset($ _ POST ['大小'])){
                    $大小= $ _ POST ['大小'];
                }

                $ currentStoreUrl =法师:: getBaseUrl();

                $ currentProduct = $这个 - > getProduct($类型,$颜色,$大小);

                $ currentId = $ currentProduct->的getId();

                $ currentUrl = $ currentProduct-> getProductUrl();

                $ currentPrice = $这个 - >用getPrice($ currentId);

                $ currentImgUrl = $这个 - > getDoorBaseImgUrl($类型,$大小);

?>

< D​​IV ID =door_wrapper级=>
    < D​​IV ID =door_left_wrapper级=MJ-grid48>

        <形式ID =TESTFORM>

            < D​​IV ID =door_colors>

                <标签ID =FFFFFF>白色<输入类型=无线电名称=切换值=FFFFFF>< /标签>
                <标签ID =000000>黑<输入类型=无线电名称=切换值=000000>< /标签>
                <标签ID =736D6C>灰色<输入类型=无线电名称=切换值=736D6C>< /标签>

            < / DIV>

            < D​​IV ID =door_model>

                < PHP的print_r($ _ POST); ?>

                <?PHP的echo $类型;?>
                <?PHP的echo $颜色;?>
                <?PHP的echo $大小;?>

                < BR>

                <?PHP的echo $ currentImgUrl;?>
            < / DIV>

            < D​​IV ID =door_size>

                <选择名称=doorsizes>
                < /选择>

            < / DIV>

            ?< PHP如果($ currentProduct-> isSaleable()):>
                <按钮式=按钮>
                    < A HREF =< PHP的echo $ currentStoreUrl。结帐/车/增加产品=放?$ currentId。;数量= 1;?>>
                        测试
                    &所述; / a取代;
                < /按钮>
            < PHP的东西:??>
                <按钮禁用>缺货&LT的; /按钮>
            < PHP ENDIF;?>

        < /形式GT;

    < / DIV>

    < D​​IV ID =door_right_wrapper级=MJ-grid48>

        < D​​IV ID =door_img>
            < IMG SRC =< PHP的echo $ currentImgUrl;>中>
        < / DIV>

        < D​​IV ID =结果>< / DIV>
    < / DIV>

< / DIV>

<脚本类型=文/ JavaScript的>

    变量$ COL =000000;
    变量$ TYPE =高级;
    变量$大小=3050x2150;

    功能ajaxUpdate()
    {
        $ j.ajax({
            网址:/ doorconfig / AJAX /指数,
            键入:POST,
            数据:{颜色:$山坳,类型:$类型,大小:$大小},
            背景:$ J(下'#door_wrapper)父()。
            成功:函数(数据)
                     {
                        $ J(下这一点)。html的(数据)$(本).fadeIn(慢)。
                     }
        });
    };

    $ J(下文件)。就绪(函数()
                       {
                          $ J(下输入[名称=切换]:电台)。改变(函数()
                                                                {
                                                                    ajaxUpdate();
                                                                })
                       });

< / SCRIPT>
 

我的座PHP的:

 < PHP
类Geeklab_DoorConfig_Block_Doorconfig扩展Mage_Core_Block_Template
{

    公共职能getProduct($类型,$颜色,$大小)
    {

        //获取产品系列
        $集合=法师:: getModel('目录/产品) - > getCollection();

        //选择需要的属性
        $收藏 - > addAttributeToSelect('doorconfig_enable');
        $收藏 - > addAttributeToSelect('doorconfig_color');
        $收藏 - > addAttributeToSelect('doorconfig_size');
        $收藏 - > addAttributeToSelect('doorconfig_type');

        //滤波器选择产品
        $收藏 - > addFieldToFilter('doorconfig_enable',
                阵列(
                        '情商'=>法师:: getResourceModel(目录/产品)
                                     - >的getAttribute('doorconfig_enable)
                                     - >的getSource()
                                     - > getOptionId(是)
                     )
        );

        $收藏 - > addFieldToFilter('doorconfig_color',
                阵列(
                        '情商'=>法师:: getResourceModel(目录/产品)
                                     - >的getAttribute('doorconfig_color)
                                     - >的getSource()
                                     - > getOptionId($颜色)
                     )
        );

        $收藏 - > addFieldToFilter('doorconfig_size',
                阵列(
                        '情商'=>法师:: getResourceModel(目录/产品)
                                     - >的getAttribute('doorconfig_size)
                                     - >的getSource()
                                     - > getOptionId($大小)
                     )
        );

        $收藏 - > addFieldToFilter('doorconfig_type',
                阵列(
                        '情商'=>法师:: getResourceModel(目录/产品)
                                     - >的getAttribute('doorconfig_type)
                                     - >的getSource()
                                     - > getOptionId($型)
                     )
        );

        $产品= $收藏 - > getFirstItem();

        返回$产品;
    }

    公共职能用getPrice($ ID)
    {
        $产品=法师:: getModel('目录/产品) - >负载($ ID);
        $ _taxHelper =新Mage_Tax_Helper_Data;
        $ finalprice = $ _taxHelper->用getPrice($产品$产品 - > getFinalPrice(),TRUE);
        $ finalprice = $这个 - > getCurrency();
        返回$ finalprice;
    }

    公共职能getCurrency()
    {
        返回Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrency$c$c())->getSymbol();
    }

    公共职能getDoorImageDir()
    {
        返回法师:: getBaseUrl(Mage_Core_Model_Store :: URL_TYPE_MEDIA)。 所见即所得/ geeklab / doorconfig /';
    }

    公共职能getDoorBaseImgUrl($类型,$大小)
    {
        返回$这个 - > getDoorImageDir()。用strtolower($大小)。 _。 str_replace函数(\ 040,\ 137,用strtolower($类))。 巴纽;
    }

    公共职能getDoorColorImgUrl($颜色,$大小)
    {
        返回$这个 - > getDoorImageDir()。用strtolower($大小)。 _。用strtolower($颜色)。 巴纽;
    }
}

?>
 

和我AjaxController.php

 < PHP

类Geeklab_DoorConfig_AjaxController扩展Mage_Core_Controller_Front_Action
{
   公共职能的indexAction()
   {
        $这个 - > loadLayout();
        $这个 - > renderLayout();
   }

}
?>
 

解决方案

于是我想出了一个解决方案,工程只是真棒。我增加了一个控制器动作和模型在我ajax调用做Magento的相互作用。因此,让我告诉你它是如何做的,我希望有人能从中获利迟早:)

我的新动作:

 公共职能updateAction()
   {

      //实例化产品型号
      $产品型号=法师:: getModel('doorconfig /产品');

      //从模型更新的值
      $ currentProduct = $ productModel-> getProduct($ _ POST);
      $ currentProductId = $ currentProduct->的getId();
      $ currentProductUrl = $ currentProduct-> getProductUrl();
      $ currentPrice = $ productModel->用getPrice($ currentProductId);
      $ currentType = $这个 - >调用getRequest() - >的getPost('doorconfig_type');
      $ currentSize = $这个 - >调用getRequest() - >的getPost('doorconfig_size');
      $ currentProductBaseImgUrl = $ productModel-> getDoorBaseImgUrl($ currentType,$ currentSize);

      //填充Resultarray
      $结果= array("currentProductId"=>$currentProductId,"currentPrice"=>$currentPrice,"currentProductUrl"=>$currentProductUrl,"currentProductBaseImgUrl"=>$currentProductBaseImgUrl);

      在JSON // EN code结果
      $这个 - > GETRESPONSE() - > setBody(法师::帮手(核心) - > jsonEn code($结果));

      返回$结果;
   }
 

我的模型刚大部分业务逻辑从我的块,所以没什么特别指出这一点。

最后更新阿贾克斯部分现在触发我的新控制器动作,接收结果作为一个JSON EN code和DOM变化的值:

 <脚本类型=文/ JavaScript的>

   变量$价格=;
   变量$ baseImgUrl =;
   变量$ PRODUCTURL =;
   变量$ productId参数=;
   变量$ F = $ J(下#attributeform);
    变量$ FORMDATA;
    变量$ currentStoreUrl =< PHP的echo $ currentStoreUrl>?;

   功能ajaxUpdate()
   {

      $ j.ajax({
         网址:/ doorconfig /指数/更新,
         键入:POST,
         数据:$ FORMDATA,
         数据类型:JSON,
         成功:函数(数据)
                {
                  $ productId参数= data.currentProductId;
                  $价格= data.currentPrice;
                  $ baseImgUrl = data.currentProductBaseImgUrl;
                  $ PRODUCTURL = data.currentProductUrl;
                     $ J(下#结果)文本($价格)。

                     。$ J(下#addtocart)ATTR(?结帐/车/增加产品=HREF',$ currentStoreUrl + + $ productId参数+&放大器;数量= 1);
                     $ J(下#productimg)ATTR('src'中,$ baseImgUrl)。

                     的console.log(数据);

                   },
            错误:功能(错误)
                  {
                     的console.log(错误:);
                     执行console.log(错误);
                     警报(ERROR);
                  }
        });
    };

   $ J(下文件)。就绪(函数()
   {

      $ J(下#结果)文本。('<?PHP的echo $ defaultProductPrice;?>');
      $ J(下#addtocart)ATTR。(HREF','<?PHP的echo $ currentStoreUrl结帐/车/增加产品=?$ defaultProductId&放大器;数量= 1。>?) ;
      $ J(下#moreinfo)ATTR(HREF','<?PHP的echo $ defaultProductUrl;?>')。
      $ J(下#productimg)ATTR('src'中,'<?PHP的echo $ defaultProductImgUrl;?>')。
      $Ĵ(#attributeform)[0] .reset段();

      $ J(下的形式[名称= attributeform])。改变(函数()
      {

         $ FORMDATA = $ f.serialize();
         ajaxUpdate();
      })
   });

< / SCRIPT>
 

如果您需要任何进一步的解释或想提高的东西,请发表评论:)

I was just recently given the task to create a simple Product configurator for our Magento Template in 5 days, where you can choose some attributes and it calculates the price for you, fades over a new image and changes the add to cart button to the new product.

Before this I had no experience in PHP or JQuery and just some basics in Magento (never done a custom module before.) My only programming Background is OOP Games in Action Script 3.

So far my code works somehow. I have some variables that I can change on click of some radio buttons and the variables are updated via the ajax method. As URL my block index method is called which does just load and render my layout. After I add the returned HTML (which is my whole block) to the parent of my outermost div in my block. It works but I can't seem to find a way to animate the changes and it seems kind of slow if the ajax rebuilds the whole block each time the user just changes one option.

Is there a more elegant way to just reload the changed parts, smoothly animate the changes and make my block remember the inputs that were made?

Here are the source files for download: http://www.roflxd.de/doorconfig.zip

If you need to see the site itself, please message me :)

Thanks in advance!

My Block phtml:

    <?php 

                $type = 'Simple';
                $color = 'FFFFFF';
                $size = '2500x1800';

                if (isset($_POST['color'])) {
                    $color = "#" . $_POST['color'];
                }

                if (isset($_POST['type'])) {
                    $type = $_POST['type'];
                }

                if (isset($_POST['size'])) {
                    $size = $_POST['size'];
                }

                $currentStoreUrl = Mage::getBaseUrl();

                $currentProduct = $this->getProduct($type,$color,$size);

                $currentId = $currentProduct->getId();

                $currentUrl = $currentProduct->getProductUrl();         

                $currentPrice = $this->getPrice($currentId);

                $currentImgUrl = $this->getDoorBaseImgUrl($type, $size);

?>

<div id="door_wrapper" class="">
    <div id="door_left_wrapper" class="mj-grid48">

        <form id="testform">

            <div id="door_colors">

                <label id="FFFFFF">White<input type="radio" name="toggle" value="FFFFFF"></label>
                <label id="000000">Black<input type="radio" name="toggle" value="000000"></label>
                <label id="736D6C">Grey<input type="radio" name="toggle" value="736D6C"></label>

            </div>

            <div id="door_model" >

                <?php print_r($_POST); ?>

                <?php echo $type;?>
                <?php echo $color;?>
                <?php echo $size;?>

                <br>

                <?php echo $currentImgUrl;?>
            </div>

            <div id="door_size">

                <select name="doorsizes">
                </select>

            </div>

            <?php if ($currentProduct->isSaleable()): ?>
                <button type="button">
                    <a href="<?php echo $currentStoreUrl . "checkout/cart/add?product=" . $currentId . "&qty=1";?>">
                        Test
                    </a>
                </button>
            <?php else: ?>
                <button disabled>Out of Stock</button>
            <?php endif;?>

        </form>

    </div>

    <div id="door_right_wrapper" class="mj-grid48">

        <div id="door_img">
            <img src="<?php echo $currentImgUrl;?>">
        </div>

        <div id="result"></div>
    </div>

</div>

<script type="text/javascript">

    var $col = "000000";
    var $type = "Advanced";
    var $size = "3050x2150";

    function ajaxUpdate()
    {         
        $j.ajax({
            url: "/doorconfig/ajax/index",
            type: "POST",
            data: {color : $col, type : $type, size : $size },
            context: $j('#door_wrapper').parent(),
            success: function(data) 
                     {
                        $j(this).html(data).$(this).fadeIn(slow);
                     }
        });
    };

    $j(document).ready(function() 
                       {    
                          $j("input[name=toggle]:radio").change(function ()
                                                                {
                                                                    ajaxUpdate();
                                                                })
                       });   

</script>

My Block php:

    <?php
class Geeklab_DoorConfig_Block_Doorconfig extends Mage_Core_Block_Template
{

    public function getProduct($type,$color,$size)
    {

        //Get Product Collection
        $collection = Mage::getModel('catalog/product')->getCollection();

        //Select needed Attributes
        $collection->addAttributeToSelect('doorconfig_enable'); 
        $collection->addAttributeToSelect('doorconfig_color');
        $collection->addAttributeToSelect('doorconfig_size');
        $collection->addAttributeToSelect('doorconfig_type');

        //Filter for Selected Product
        $collection->addFieldToFilter('doorconfig_enable',
                array(
                        'eq' => Mage::getResourceModel('catalog/product')
                                    ->getAttribute('doorconfig_enable')
                                    ->getSource()
                                    ->getOptionId('Yes')
                     )
        );

        $collection->addFieldToFilter('doorconfig_color',
                array(
                        'eq' => Mage::getResourceModel('catalog/product')
                                    ->getAttribute('doorconfig_color')
                                    ->getSource()
                                    ->getOptionId($color)
                     )
        );

        $collection->addFieldToFilter('doorconfig_size',
                array(
                        'eq' => Mage::getResourceModel('catalog/product')
                                    ->getAttribute('doorconfig_size')
                                    ->getSource()
                                    ->getOptionId($size)
                     )
        );

        $collection->addFieldToFilter('doorconfig_type',
                array(
                        'eq' => Mage::getResourceModel('catalog/product')
                                    ->getAttribute('doorconfig_type')
                                    ->getSource()
                                    ->getOptionId($type)
                     )
        );

        $product = $collection->getFirstItem();

        return $product;
    }

    public function getPrice($id)
    {
        $product = Mage::getModel('catalog/product')->load($id);
        $_taxHelper  = new Mage_Tax_Helper_Data;
        $finalprice = $_taxHelper->getPrice($product, $product->getFinalPrice(), true);
        $finalprice .= $this->getCurrency();
        return $finalprice;
    }

    public function getCurrency()
    {
        return Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
    }

    public function getDoorImageDir()
    {
        return Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'wysiwyg/geeklab/doorconfig/';
    }

    public function getDoorBaseImgUrl($type, $size)
    {
        return $this->getDoorImageDir() . strtolower($size) . '_' . str_replace("\040", "\137", strtolower($type)) . '.png';
    }

    public function getDoorColorImgUrl($color, $size)
    {
        return $this->getDoorImageDir() . strtolower($size) . '_' . strtolower($color) . '.png';
    }
}

?>

And my AjaxController.php

    <?php

class Geeklab_DoorConfig_AjaxController extends Mage_Core_Controller_Front_Action
{
   public function indexAction ()
   {
        $this->loadLayout();
        $this->renderLayout();
   }

}
?>

解决方案

So I came up with a solution that works just awesome. I added another controller action and a model to do the Magento Interactions during my ajax calls. So let me show you how it's done, I hope somebody can profit from this sooner or later :)

My new Action:

public function updateAction ()
   {

      //Instantiate Product Model
      $productModel = Mage::getModel('doorconfig/product');

      //Get Updated Values from the Model
      $currentProduct = $productModel->getProduct($_POST);
      $currentProductId = $currentProduct->getId();
      $currentProductUrl = $currentProduct->getProductUrl();
      $currentPrice = $productModel->getPrice($currentProductId);
      $currentType = $this->getRequest()->getPost('doorconfig_type');
      $currentSize = $this->getRequest()->getPost('doorconfig_size');
      $currentProductBaseImgUrl = $productModel->getDoorBaseImgUrl($currentType,$currentSize);

      //Populate Resultarray
      $result = array("currentProductId"=>$currentProductId,"currentPrice"=>$currentPrice,"currentProductUrl"=>$currentProductUrl,"currentProductBaseImgUrl"=>$currentProductBaseImgUrl);

      //Encode Result in JSON
      $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

      return $result;
   }

My model just got most of the business logic from my block, so nothing special to point out about that.

And finally the updated Ajax section which now triggers my new controller action, receives the result as a JSON encode and changes the values in the DOM:

<script type="text/javascript">

   var $price = "";
   var $baseImgUrl = "";
   var $productUrl = "";
   var $productId = "";
   var $f = $j("#attributeform");
    var $formData;
    var $currentStoreUrl = "<?php echo $currentStoreUrl ?>";

   function ajaxUpdate()
   {

      $j.ajax({
         url: "/doorconfig/index/update",
         type: "POST",
         data: $formData,
         dataType: "json",
         success: function(data) 
                {
                  $productId = data.currentProductId;
                  $price = data.currentPrice;
                  $baseImgUrl = data.currentProductBaseImgUrl;
                  $productUrl = data.currentProductUrl;
                     $j("#result").text($price);

                     $j("#addtocart").attr('href',  $currentStoreUrl + "checkout/cart/add?product=" + $productId + "&qty=1");
                     $j("#productimg").attr('src', $baseImgUrl);

                     console.log(data);

                   },
            error: function(error)
                  {
                     console.log("Error:");
                     console.log(error);
                     alert("ERROR");
                  }
        });
    };

   $j(document).ready(function() 
   {

      $j("#result").text('<?php echo $defaultProductPrice; ?>');
      $j("#addtocart").attr('href', '<?php  echo $currentStoreUrl . "checkout/cart/add?product=" . $defaultProductId . "&qty=1" ?>');
      $j("#moreinfo").attr('href', '<?php echo $defaultProductUrl; ?>');
      $j("#productimg").attr('src', '<?php echo $defaultProductImgUrl; ?>');
      $j("#attributeform")[0].reset();

      $j("form[name=attributeform]").change(function () 
      {

         $formData = $f.serialize();
         ajaxUpdate();
      })
   });   

</script>

If you need any further explanation or wanna improve something please comment :)