Jump to content

Assign variable to order detail template


Socrates

Recommended Posts

Hi, I want to assign a variable to the template that shows the details of an order, specifically in the section that displays information about the products. The template is located at: \src\PrestaShopBundle\Resources\views\Admin\Sell\Order\Order\Blocks\View\product.html.twig

I have been able to do this by modifying the OrderController located at: src\PrestaShopBundle\Controller\Admin\Sell\Order\OrderController.php but I don't want to modify the core. I want to override it.

I have found it impossible. Does anyone know how to do it?

Link to comment
Share on other sites

  On 3/22/2023 at 1:45 PM, ventura said:

Which variable you need to access from .twig ?

Expand  

I want to show the color of a product in the order detail. For this, it would pass that value to a variable that would be displayed in the request. As I say, I have managed to do it directly from the OrderController but I have not been able to override it or do it in a custom module. Sorry for my bad english, i speak spanish.

Link to comment
Share on other sites

  On 3/22/2023 at 3:27 PM, daninapoli said:
  • ¿Puedes mostrarme el código que cambiaste? no necesita un módulo personalizado por ahora ...

Expand  

Aquí creé las dos variables $colorTitle y $colorValue y les asigné los valores correspondientes. Donde 'value' es el color del producto.

public function viewAction(int $orderId, Request $request): Response
    {
        try {
            /** @var OrderForViewing $orderForViewing */
            $orderForViewing = $this->getQueryBus()->handle(new GetOrderForViewing($orderId, QuerySorting::DESC));
        } catch (OrderException $e) {
            $this->addFlash('error', $this->getErrorMessageForException($e, $this->getErrorMessages($e)));

            return $this->redirectToRoute('admin_orders_index');
        }

        $colorTitle = '';
        $colorValue = '';

        foreach( $orderForViewing->getProducts()->getProducts() as $product ){
            $product_order = new \Product($product->getId());
            foreach( $product_order->getFrontFeaturesStatic( 1,$product->getId() ) as $feature ){
                if( $feature['id_feature'] == 1 ){
                    $colorTitle = $feature['name'];
                    $colorValue = $feature['value'];
                }
            }
        }

Luego asigno las variables al final de  la clase.

 return $this->render('@PrestaShop/Admin/Sell/Order/Order/view.html.twig', [
            'showContentHeader' => true,
            'enableSidebar' => true,
            'orderCurrency' => $orderCurrency,
            'meta_title' => $metatitle,
            'help_link' => $this->generateSidebarLink($request->attributes->get('_legacy_controller')),
            'orderForViewing' => $orderForViewing,
            'addOrderCartRuleForm' => $addOrderCartRuleForm->createView(),
            'updateOrderStatusForm' => $updateOrderStatusForm->createView(),
            'updateOrderStatusActionBarForm' => $updateOrderStatusActionBarForm->createView(),
            'addOrderPaymentForm' => $addOrderPaymentForm->createView(),
            'changeOrderCurrencyForm' => $changeOrderCurrencyForm->createView(),
            'privateNoteForm' => $privateNoteForm ? $privateNoteForm->createView() : null,
            'updateOrderShippingForm' => $updateOrderShippingForm->createView(),
            'cancelProductForm' => $cancelProductForm->createView(),
            'invoiceManagementIsEnabled' => $orderForViewing->isInvoiceManagementIsEnabled(),
            'changeOrderAddressForm' => $changeOrderAddressForm ? $changeOrderAddressForm->createView() : null,
            'orderMessageForm' => $orderMessageForm->createView(),
            'addProductRowForm' => $addProductRowForm->createView(),
            'editProductRowForm' => $editProductRowForm->createView(),
            'backOfficeOrderButtons' => $backOfficeOrderButtons,
            'merchandiseReturnEnabled' => $merchandiseReturnEnabled,
            'priceSpecification' => $this->getContextLocale()->getPriceSpecification($orderCurrency->iso_code)->toArray(),
            'previousOrderId' => $orderSiblingProvider->getPreviousOrderId($orderId),
            'nextOrderId' => $orderSiblingProvider->getNextOrderId($orderId),
            'paginationNum' => $paginationNum,
            'paginationNumOptions' => $paginationNumOptions,
            'isAvailableQuantityDisplayed' => $this->configuration->getBoolean('PS_STOCK_MANAGEMENT'),
            'internalNoteForm' => $internalNoteForm->createView(),
            'colorTitle' => $colorTitle,
            'colorValue' => $colorValue,
        ]);

Todo esto lo hago en el OrderController.php el cual es parte del core de Prestashop. No debería hacer eso, pero la verdad me ha sido imposible hacer override.

Esto está funcionando perfectamente ahora.

Edited by Socrates
Había pegado mal el código (see edit history)
Link to comment
Share on other sites

  • 3 months later...
  On 3/27/2023 at 10:49 AM, Socrates said:

Aquí creé las dos variables $colorTitle y $colorValue y les asigné los valores correspondientes. Donde 'value' es el color del producto.

public function viewAction(int $orderId, Request $request): Response
    ...

Luego asigno las variables al final de  la clase.

 return $this->render('@PrestaShop/Admin/Sell/Order/Order/view.html.twig', [
            ...
            'colorTitle' => $colorTitle,
            'colorValue' => $colorValue,
        ]);

Todo esto lo hago en el OrderController.php el cual es parte del core de Prestashop. No debería hacer eso, pero la verdad me ha sido imposible hacer override.

Esto está funcionando perfectamente ahora.

Expand  

Estoy en la misma, quiero agregar una variable que intento obtener de la DB al template shipping.html.twig en la pagina del Pedido. Todavia no he logrado en mi caso encontrar el metodo render que agrega todas las variables ya existentes en el template, pero si puedo ayudarte con el hecho de como sobreescribir el template sin tocar el core.
Basicamente la unica manera (y la oficial mencionada en la documentacion de PS) es creando un modulo. No necesita ser un modulo especifico ni estar ubicado en ningun hook en particular, podes crearlo con ESTA herramienta de prestashop y luego una vez creado el modulo, dentro de la carpeta Views del modulo debes crear la misma ruta del template que queres sobreescribir. Si el tempate tiene blocks podes extender el original y solo sobreescribir el bloque deseado o directamente sobreescribir todo el template.
Aca te dejo el link de la docu oficial donde lo explica con un ejemplo.
https://devdocs.prestashop-project.org/1.7/modules/concepts/templating/admin-views/

Nota: con la herramienta para generar el boilerplate del modulo tenes que tener una consideracion en el campo Module name debes poner el nombre del modulo sin espacios, pero utiliza solo PascalCase no camelCase, no kebab-case, no snake_case. Porque es este campo el que va a utilizar para crear el nombre de la class php ppal del modulo y si usas guiones vas a generar un error de sintaxis y cuando lo instales va a romper.

Edited by crisalidainhalada (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...