programing

Magento-사용자 입력을 기반으로 한 견적 / 주문 제품 항목 속성

nasanasas 2020. 11. 23. 08:15
반응형

Magento-사용자 입력을 기반으로 한 견적 / 주문 제품 항목 속성


요약

상품에 저장되지 않거나 일반 상품 속성처럼 상품 편집 페이지에 표시되는 상품 속성을 만들고 싶습니다. 대신 주문 / 견적 항목에 저장하고 주문, 송장 등에 표시되기를 원합니다. 또한 카트에 제품을 추가하기 전에 프런트 엔드에서 고객이 구성 할 수도 있습니다.

세부

  • 단지와 같은 사용자 정의 옵션 , 폼 요소는 프론트 엔드 제품 페이지에 추가해야합니다.
    • 맞춤 옵션 과 달리 실제 제품 속성 이 아닙니다 . 관리 제품 페이지 또는 속성 세트에 표시되지 않아야합니다.
    • 고객은 유효한 값을 제공해야합니다. 서버 측 유효성 검사를 수행 할 수 있어야합니다.
    • html을 생성하는 .phtml 템플릿을 갖고 싶습니다. 현재 만족스러운 (디자인) 결과로 app / design / frontend / base / default / catalog / product / view / type / default.phtml 을 재정의 할 수 있습니다 . 그러나 나는 그 가치를 포착하고, 검증하고, 결국 저장하는 방법을 모릅니다.
  • 이 양식 요소의 값은 견적 / 주문 제품 항목과 함께 저장되어야합니다.
    • 이 값은 모든 인보이스, 주문, 판매 이메일에 표시되어야합니다.
    • 템플릿을 사용하여 출력을 제어하거나 적어도 값을 표시하는 데 사용되는 문자열을 반환 할 수 있어야합니다.

내 질문

  1. <input>제품이 장바구니에 추가 될 때 프런트 엔드 제품 페이지 의 값을 견적 항목에 확인하고 최종적으로 저장 하고 나중에 주문 항목에 대한 체크 아웃 프로세스에 저장하려면 어떻게해야합니까?
  2. 이 값을 주문, 송장, 판매 이메일 및 해당 페이지에 어떻게 표시합니까?
  3. 내 값이 특정 값으로 설정된 항목이있는 주문을 가져 오기 위해 주문 컬렉션을 필터링하려면 어떻게해야합니까?

업데이트 1

다음 과 같은 이벤트 중에 catalog/product모델 에서이 코드를 실행할 수 있다는 것을 발견 sales/quote_item했습니다.sales_quote_item_qty_set_after

$infoBuyRequest = $product->getCustomOption('info_buyRequest');
$buyRequest = new Varien_Object(unserialize($infoBuyRequest->getValue()));
$myData = $buyRequest->getMyData();

이러한 방식으로 <input>제품 페이지의 내 사용자 지정, 고객 제공 데이터를 검색 할 수있었습니다 .

나는 이것이 info_buyRequest견적 및 주문 항목과 함께 저장 되었다고 생각 합니다. 그렇다면 이것은 부분적으로 내 문제 1과 2를 해결했습니다. 그러나 여전히이 코드를 실행하는 데 적합한 위치를 알 수 없으며 백엔드 주문 / 견적 / 보고서 페이지에 표시하는 방법을 모릅니다. 또한 이것은 데이터베이스에 직렬화 된 값으로 저장되기 때문에 내 사용자 지정 데이터를 기반으로 견적 / 주문 항목 컬렉션을 얻는 것이 가장 어려울 것이라고 믿습니다.


Magento는 제품 속성 또는 제품 사용자 지정 옵션이 아닌 옵션을 추가하는 기능을 제공합니다. 옵션 코드로 제품 및 견적 항목에 설정됩니다 additional_options.

수행해야 할 두 단계가 있으며 각 단계는 이벤트 관찰자를 통해 처리 할 수 ​​있습니다. 추가 옵션이 재정렬을 수행하도록하려면 세 번째 이벤트도 관찰해야합니다.

견적 항목에 옵션 추가

첫 번째 단계는 이벤트 옵저버를 추가하여로드 된 제품을 카트에 추가하기 전에 추가 옵션을 설정하는 것입니다. 한 가지 옵션은 catalog_product_load_after이벤트 를 사용하는 것 입니다.

<catalog_product_load_after>
    <observers>
        <extra_options>
            <type>model</type>
            <class>extra_options/observer</class>
            <method>catalogProductLoadAfter</method>
        </extra_options>
    </observers>
</catalog_product_load_after>

이벤트 옵저버에서 요청한 페이지가 실제로 장바구니에 추가 작업인지 확인을 추가 할 수 있습니다. 이 옵저버 방법의 요점은 additional_options제품 모델 옵션에 특별한 옵션을 추가하는 것 입니다.

public function catalogProductLoadAfter(Varien_Event_Observer $observer)
{
    // set the additional options on the product
    $action = Mage::app()->getFrontController()->getAction();
    if ($action->getFullActionName() == 'checkout_cart_add')
    {
        // assuming you are posting your custom form values in an array called extra_options...
        if ($options = $action->getRequest()->getParam('extra_options'))
        {
            $product = $observer->getProduct();

            // add to the additional options array
            $additionalOptions = array();
            if ($additionalOption = $product->getCustomOption('additional_options'))
            {
                $additionalOptions = (array) unserialize($additionalOption->getValue());
            }
            foreach ($options as $key => $value)
            {
                $additionalOptions[] = array(
                    'label' => $key,
                    'value' => $value,
                );
            }
            // add the additional options array with the option code additional_options
            $observer->getProduct()
                ->addCustomOption('additional_options', serialize($additionalOptions));
        }
    }
}

추가 옵션은 제품에서 견적 항목으로 자동으로 이동됩니다. 이 옵저버를 설치하면 옵션이 카트와 체크 아웃 리뷰에 표시됩니다.

주문 항목에 옵션 추가

그것들을 지속 시키려면 한 명의 추가 관찰자가 필요합니다 (Magento 1.5 이후에만).

<sales_convert_quote_item_to_order_item>
    <observers>
        <extra_options>
            <type>model</type>
            <class>extra_options/observer</class>
            <method>salesConvertQuoteItemToOrderItem</method>
        </extra_options>
    </observers>
</sales_convert_quote_item_to_order_item>

여기에서 옵션을 견적 항목에서 주문 항목으로 이동합니다.

public function salesConvertQuoteItemToOrderItem(Varien_Event_Observer $observer)
{
    $quoteItem = $observer->getItem();
    if ($additionalOptions = $quoteItem->getOptionByCode('additional_options')) {
        $orderItem = $observer->getOrderItem();
        $options = $orderItem->getProductOptions();
        $options['additional_options'] = unserialize($additionalOptions->getValue());
        $orderItem->setProductOptions($options);
    }
}

From this point on the additional options will be visible in the customer order history in the frontend and the order emails, as well as in the admin interface order view, invoices, shipments, creditmemos and PDFs.

Add support for reorders

In order to carry the oprions over to the new order during a reorder, you need to take care to copy them over. Here is one possibility using the checkout_cart_product_add_after event.

<checkout_cart_product_add_after>
    <observers>
        <extra_options>
            <type>singleton</type>
            <class>extra_options/observer</class>
            <method>checkoutCartProductAddAfter</method>
        </extra_options>
    </observers>
</checkout_cart_product_add_after>

The parsing of the extra options and building the additional options array should be moved into a separate function to avoid code duplication, but for this example I'll leave the required logic for each method in place for clarity.

public function checkoutCartProductAddAfter(Varien_Event_Observer $observer)
{
    $action = Mage::app()->getFrontController()->getAction();
    if ($action->getFullActionName() == 'sales_order_reorder')
    {
        $item = $observer->getQuoteItem();
        $buyInfo = $item->getBuyRequest();
        if ($options = $buyInfo->getExtraOptions())
        {
            $additionalOptions = array();
            if ($additionalOption = $item->getOptionByCode('additional_options'))
            {
                $additionalOptions = (array) unserialize($additionalOption->getValue());
            }
            foreach ($options as $key => $value)
            {
                $additionalOptions[] = array(
                    'label' => $key,
                    'value' => $value,
                );
            }
            $item->addOption(array(
                'code' => 'additional_options',
                'value' => serialize($additionalOptions)
            ));
        }
    }
}

Translation:

There is no mechanism in place to translate these option labels or values. Here are a few ideas that might be useful in that regard.

In a quote_item_load_after event observer, get the additional options array and set $option['print_value'] = $helper->__($option['value']);. If print_value is set, Magento will use that for rendering the display.
The same can be done with order items.

There is no such thing as a print_label, but you could set a custom index (label_source maybe) and set the label on the fly using that as the source, e.g. $option['label'] = $helper->__($option['label_source']);.

Beyond that you would probably have to resort to modifying the templates (grep for getItemOptions()), or overriding the block classes (grep additional_options).


It is possible to add custom fields to the Quote item. How to add custom fields for Order Line Items in Magento to get started. I've used these instruction recently to add a custom fields to a Magento Quote Item and the concept is fine, but there are a few practices in that article that are not great. Things I'd do differently:

  1. Use a setup script to add fields to the database rather than doing it directly.
  2. Use Magento's Request object rather than accessing $_REQUEST directly.
  3. Use extensions and rewrites rather than modifying the Magento core.
  4. Make the changes to config.xml from an extension rather than modifying the core.

Generally it's best to avoid modifying the Magento core, and apply your customisations via a module as it makes upgrades easier/possible in the future. If you've not created your own extension before moduleCreator can help you generate the necessary boilerplate.


My Solution in Magento 1.8

Set option to quote item

$quoteItem = $cart->getQuote()->getItemById($itemId);
$quoteItem->addOption(array('label' => 'buymode', 'code' => 'buymode', 'value' => $data['buymode']));
$quoteItem->save();

Access option from QuoteItem

$quoteItem->getOptionByCode('buymode')->getValue();

Transfer option to OrderItem

Register for event sales_convert_quote_item_to_order_item

public function onConvertQuoteItemToOrderItem($observer) {
    $orderItem = $observer->getOrderItem();
    $quoteItem = $observer->getItem();
    $options = $orderItem->getProductOptions();
    $options['buymode'] = $quoteItem->getOptionByCode('buymode')->getValue();
    $orderItem->setProductOptions($options);
}

Access option from OrderItem

$orderItem->getProductOptionByCode('buymode')

참고URL : https://stackoverflow.com/questions/9412074/magento-quote-order-product-item-attribute-based-on-user-input

반응형