Override magento 2 block ../module_sales/block/adminhtml/totals.php - magento2

I am trying to override magento block but everytime main block from vendor is executed. No errors are shown.
Magento block:
vendor/magento/module_sales/block/adminhtml/totals.php
Created block in custom module:
[vendor]/[module]/block/adminhtml/totals.php
Modified di.xml file in:
[vendor]/[module]/etc/di.xml
Preference in di.xml file:
...
<preference for="Magento\Sales\Block\Adminhtml\Totals"
type="Iways\Sales\Block\Adminhtml\Totals" />
...
Content of block in custom module:
namespace Iways\Sales\Block\Adminhtml;
use Magento\Framework\DataObject;
use Magento\Sales\Block\Adminhtml\Totals as DefaultTotals;
class Totals extends DefaultTotals
{
...
I have tried to check if file is executed with xdebug but it isnt.

If you override a block, you also want to add a sequence in your module.xml. You have to make sure the module of the block you want to override is being loaded before your module is being loaded. See Component load order. Add the module Magento_Sales to your sequence.
If that doesn't work:
Are you sure your module is registered by Magento, can you find your module in `app/etc/config.php'?
Are you sure there's no other module which overrides that block already?

The block that I was trying to extend has already been extended by another block in:
module_sales/block/adminhtml/order/totals.php
So in general, all I needed to do is to extend that block mentioned above.

Posting this solution for Magento v-2.3.5
Override this class \Magento\Sales\Block\Adminhtml\Order\Totals
app/code/Taktheer/ExtendCoupanTotals/etc/di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Block\Adminhtml\Order\Totals" type="Taktheer\ExtendCoupanTotals\Rewrite\Magento\Sales\Block\Adminhtml\Order\Totals"/>
</config>
app/code/Taktheer/ExtendCoupanTotals/Rewrite/Magento/Sales/Block/Adminhtml/Order/Totals.php
<?php
/**
* Copyright © Unyscape Infocom Pvt. Ltd. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Taktheer\ExtendCoupanTotals\Rewrite\Magento\Sales\Block\Adminhtml\Order;
class Totals extends \Magento\Sales\Block\Adminhtml\Order\Totals
{
/**
* Initialize order totals array
*
* #return $this
*/
protected function _initTotals()
{
parent::_initTotals();
$order = $this->getSource();
if ($order->getCouponCode()) {
$discountLabel = __('Discount (%1)', $order->getCouponCode());
} else {
$discountLabel = __('Discount');
}
$this->_totals['discount'] = new \Magento\Framework\DataObject(
[
'code' => 'discount',
'value' => $order->getDiscountAmount(),
'base_value' => $order->getBaseDiscountAmount(),
'label' => $discountLabel,
]
);
return $this;
}
}
======================== Happy Coding =============================

Related

SuiteCRM v7.10.29 Custom API v4.1

I am creating a custom API for SuiteCRM. When I attempt to run the new API from {CRM Home}/custom/service/v4_1_custom I receive an 'HTTP ERROR 500'. There are not errors in the error_log file or the SuiteCRM.log file.
I have followed the method in the following two url's
https://fayebsg.com/2013/05/extending-the-sugarcrm-api-updating-dropdowns/
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_10.0/Integration/Web_Services/Legacy_API/Extending_Web_Services/
registry.php
<?php
require_once('service/v4_1/registry.php');
class registry_v4_1_custom extends registry_v4_1
{
protected function registerFunction()
{
parent::registerFunction();
$this->serviceClass->registerFunction('test', array(), array());
}
}
SugarWebServicesImplv4_1_custom.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('service/v4_1/SugarWebServiceImplv4_1.php');
class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{
/**
* #return string
*/
public function test()
{
LoggerManager::getLogger()->warn('SugerWebServiceImplv4_1_custom test()');
return ("Test Worked");
} // test
} // SugarWebServiceImplv4_1_custom
I found the answer to this issue.
In the file {SuiteCRM}/include/entryPoint.php there are many files that are included thru require_once. In this list of require_once files, there were 4 files that were set as require not require_once. These were classes and therefore could not be included a second time. I changed these to require_once and the HTTP Error 500 went away and the custom APIs started working.

Error: DDL statements are not allowed in transactions while running setup:upgrade. Running Data Patch

Magento 2.3.1
After making the data patch at the following location:
vendor/ModuleName/Setup/Patch/Data/AddMyColumnPatch.php
(Code given below for AddMyColumnPatch.php)
When I run bin/magento setup:upgrade to get this patch installed I get following error at cli:
DDL statements are not allowed in transactions
I have used the following file as reference to add a column to my table using data patch:
vendor/magento/module-quote/Setup/Patch/Data/InstallEntityTypes.php
Follow lines from 47 to 65.
My AddMyColumnPatch.php code is:
<?php
namespace Vendor\ModuleName\Setup\Patch\Data;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;
use Magento\Quote\Setup\QuoteSetupFactory;
use Magento\Sales\Setup\SalesSetupFactory;
use Psr\Log\LoggerInterface;
/**
*/
class AddressSuburbPatch implements DataPatchInterface, PatchRevertableInterface
{
/**
* Attribute Code of the Custom Attribute
*/
const CUSTOM_ATTRIBUTE_CODE = 'my_column';
/**
* #var \Magento\Framework\Setup\ModuleDataSetupInterface
*/
private $moduleDataSetup;
/**
* #var \Magento\Quote\Setup\QuoteSetupFactory
*/
private $quoteSetupFactory;
/**
* #var Magento\Sales\Setup\SalesSetupFactory
*/
private $salesSetupFactory;
/**
* #var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* #param \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup
*/
public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
QuoteSetupFactory $quoteSetupFactory,
SalesSetupFactory $salesSetupFactory,
LoggerInterface $logger
)
{
$this->moduleDataSetup = $moduleDataSetup;
$this->quoteSetupFactory = $quoteSetupFactory;
$this->salesSetupFactory = $salesSetupFactory;
$this->logger = $logger;
}
/**
* {#inheritdoc}
*/
public function apply()
{
$this->moduleDataSetup->getConnection()->startSetup();
$this->logger->debug('DDL Statements error');
$quoteSetup = $this->quoteSetupFactory->create(['setup' => $this->moduleDataSetup]);
$quoteSetup->addAttribute('quote_address', self::CUSTOM_ATTRIBUTE_CODE, ['type' => 'text']);
$salesSetup = $this->salesSetupFactory->create(['setup' => $this->moduleDataSetup]);
$salesSetup->addAttribute('order_address', self::CUSTOM_ATTRIBUTE_CODE, ['type' => 'text']);
$this->logger->debug('Script working');
$this->moduleDataSetup->getConnection()->endSetup();
}
/**
* {#inheritdoc}
*/
public static function getDependencies()
{
return [
];
}
public function revert()
{
$this->moduleDataSetup->getConnection()->startSetup();
$this->moduleDataSetup->getConnection()->endSetup();
}
/**
* {#inheritdoc}
*/
public function getAliases()
{
return [];
}
}
After going through declarative schema docs again and referencing core Magento code for quote module and PayPal module I have figured out that if you want to add a field into an existing table in Magento >=2.3 you should use configure declarative schema for that. Read more:
https://devdocs.magento.com/guides/v2.4/extension-dev-guide/declarative-schema/db-schema.html
So create a db_schema.xml file under Vendor/ModuleName/etc
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="quote_address" resource="checkout" comment="Sales Flat Quote Address">
<column xsi:type="varchar" name="suburb" nullable="true" length="255" comment="Suburb for Quote Address" />
</table>
<table name="sales_order_address" resource="sales" comment="Sales Flat Order Address">
<column xsi:type="varchar" name="mycolumn" nullable="true" length="255" comment="mycolumn for Sales Order Address" />
</table>
</schema>
Then generate whitelist for your db_schema as follows:
bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_ModuleName
Run again and your column will be added to quote_address and order_sales_address tables.
bin/magento setup:upgrade
However, further investigation revealed that there is no need of making data patch for adding columns in flat tables quote_address and sales_order_address. Only declaring columns in db_schema.xml will do the job.

How to write Monolog logs into a file AND remote database

I have a Symfony2 -project and it writes the logs into different files beautifully, but I would like it to write the logs into a remote database(mongodb) as well. I would like to keep the actual log files in the servers as a backup in case something goes wrong with the database connection.
Question 1:
Is it even possible to save the same logs into two different places at the same time?
Question 2:
How do I save the logs into the mongodb? I don't necessarily need specific mongodb-instructions, but some guidelines on how to write into a remote db with monologger. The mongodb-specific instructions are also welcome if available. ;)
Question 3(OPTIONAL):
Can I get a full error stack into the logs somehow? Where could one find a full list of what data the Monolog can actually write and how to write?
There was a very good Blogpost sometime back for logging to a mysql database with monolog and doctrine. I can't find it anymore so i will just add the neccessary Files here and you can adjust it.
The whole logic is done in the DatabaseHandler so you can just change from
mysql inserts to a handling for your mongodb.
This code is not mine if anyone knows the original post please comment.
BacktraceLoggerListener.php
namespace UtilsBundle\EventListener;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class BacktraceLoggerListener{
private $_logger;
public function __construct(LoggerInterface $logger = null)
{
$this->_logger = $logger;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$this->_logger->addError($event->getException());
}
}
DatabaseHandler.php
namespace UtilsBundle\Logger;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
/**
* Stores to database
*
*/
class DatabaseHandler extends AbstractProcessingHandler{
protected $_container;
/**
* #param string $stream
* #param integer $level The minimum logging level at which this handler will be triggered
* #param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($level = Logger::DEBUG, $bubble = true)
{
parent::__construct($level, $bubble);
}
/**
*
* #param type $container
*/
public function setContainer($container)
{
$this->_container = $container;
}
/**
* {#inheritdoc}
*/
protected function write(array $record)
{
// Ensure the doctrine channel is ignored (unless its greater than a warning error), otherwise you will create an infinite loop, as doctrine like to log.. a lot..
if( 'doctrine' == $record['channel'] ) {
if( (int)$record['level'] >= Logger::WARNING ) {
error_log($record['message']);
}
return;
}
// Only log errors greater than a warning
// TODO - you could ideally add this into configuration variable
if( (int)$record['level'] >= Logger::NOTICE ) {
try
{
// Logs are inserted as separate SQL statements, separate to the current transactions that may exist within the entity manager.
$em = $this->_container->get('doctrine')->getManager();
$conn = $em->getConnection();
$created = date('Y-m-d H:i:s');
$serverData = ""; //$record['extra']['server_data'];
$referer = "";
if (isset($_SERVER['HTTP_REFERER'])){
$referer= $_SERVER['HTTP_REFERER'];
}
$stmt = $em->getConnection()->prepare('INSERT INTO system_log(log, level, server_data, modified, created)
VALUES(' . $conn->quote($record['message']) . ', \'' . $record['level'] . '\', ' . $conn->quote($referer) . ', \'' . $created . '\', \'' . $created . '\');');
$stmt->execute();
} catch( \Exception $e ) {
// Fallback to just writing to php error logs if something really bad happens
error_log($record['message']);
error_log($e->getMessage());
}
}
}
}
We used xml here but this can be done in
services.yml too
services.xml
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="utils.database.logger" class="UtilsBundle\Logger\DatabaseHandler">
<call method="setContainer">
<argument type="service" id="service_container" />
</call>
</service>
<service id="utils.backtrace.logger.listener" class="UtilsBundle\EventListener\BacktraceLoggerListener">
<argument type="service" id="logger" />
<tag name="monolog.logger" channel="backtrace" />
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>
</services>
And lastly add the handler to your monolog config in
config_**.yml so here for production for example
config_prod.yml
monolog:
handlers:
main:
type: rotating_file
action_level: error
max_files: 10
handler: nested
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
console:
type: console
database:
type: service
level: notice
id: utils.database.logger
channels: ["!translation"]
Hope that helps
Hope I can some things up for you:
Question 1: Yes its possible. E.G. you can do smt. like:
$this->logger->pushHandler(new StreamHandler('/path/to/logs/123_info.log', Logger::INFO));
$this->logger->pushHandler(new StreamHandler('/path/to/logs/456_warning.log', Logger::INFO));
So if $this->logger->addInfo("testinfo"); this is getting logged in both streams.
Question 2: There is a MongoDBHandler as according to the StreamHandler. You should be able do configure it and pass it along to the pushHandler method or if you want to have it in your services look at MongoDBConfiguration.
Question 3:
This should help: Configure Monolog
Hope that helps.

Magento2- How to copy custom data from quote to order and order item

I am building a custom module in Magento 2 that has a custom discount. I am trying to copy the discount from quote, quote item to order and order item.
In Magento 1, I declare the config.xml like this:
<fieldsets>
<sales_convert_quote_address>
<custom_discount_amount><to_order>*</to_order></custome_discount_amount>
<base_custom_discount_amount><to_order>*</to_order></base_custome_discount_amount>
</sales_convert_quote_address>
<sales_convert_quote_item>
<custome_discount_amount><to_order_item>*</to_order_item></custome_discount_amount>
<base_custom_discount_amount><to_order_item>*</to_order_item></base_custom_discount_amount>
</sales_convert_quote_item>
</fieldsets>
and my custom discount amount was copied to tables: sales_flat_order and sales_flat_order_item as expected.
In Magento 2, I created a file named fieldset.xml with this code:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Object/etc/fieldset.xsd">
<scope id="global">
<fieldset id="sales_convert_quote_item">
<field name="custom_discount_amount">
<aspect name="to_order_item" />
</field>
<field name="base_custom_discount_amount">
<aspect name="to_order_item" />
</field>
</fieldset>
<fieldset id="sales_convert_quote_address">
<field name="custom_discount_amount">
<aspect name="to_order" />
</field>
<field name="base_custom_discount_amount">
<aspect name="to_order" />
</field>
</fieldset>
</scope>
</config>
but there is no success.
What else do I need to do in Magento 2 to make it work? Can you guys please help me?
In Magento 2 without using fieldset you can also copy custom data from quote item to order item by using plugin.
create di.xml in your module etc folder.
app/code/Vender/Yourmodule/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Quote\Model\Quote\Item\ToOrderItem">
<plugin name="cedapi_quote_to_order_item" type="Vender\Yourmodule\Model\Plugin\Quote\QuoteToOrderItem"/>
</type>
</config>
Create a class to your module and define a function. app/code/Vender/Yourmodule/Model/Plugin/Quote
Create QuoteToOrderItem.php file
<?php
namespace Vender\Yourmodule\Model\Plugin\Quote;
use Closure;
class QuoteToOrderItem
{
/**
* #param \Magento\Quote\Model\Quote\Item\ToOrderItem $subject
* #param callable $proceed
* #param \Magento\Quote\Model\Quote\Item\AbstractItem $item
* #param array $additional
* #return \Magento\Sales\Model\Order\Item
* #SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundConvert(
\Magento\Quote\Model\Quote\Item\ToOrderItem $subject,
Closure $proceed,
\Magento\Quote\Model\Quote\Item\AbstractItem $item,
$additional = []
) {
/** #var $orderItem \Magento\Sales\Model\Order\Item */
$orderItem = $proceed($item, $additional);//result of function 'convert' in class 'Magento\Quote\Model\Quote\Item\ToOrderItem'
$orderItem->setCustomDesign($item->getCustomDesign());//set your required
return $orderItem;// return an object '$orderItem' which will replace result of function 'convert' in class 'Magento\Quote\Model\Quote\Item\ToOrderItem'
}
}
After spend some time and research issue, i stucked here:
Magento\Quote\Model\QuoteManagement.php
line 446
public function mergeDataObjects(
$interfaceName,
$firstDataObject,
$secondDataObject
) {
if (!$firstDataObject instanceof $interfaceName || !$secondDataObject instanceof $interfaceName) {
throw new \LogicException('Wrong prototype object given. It can only be of "' . $interfaceName . '" type.');
}
$secondObjectArray = $this->objectProcessor->buildOutputDataArray($secondDataObject, $interfaceName);
$this->_setDataValues($firstDataObject, $secondObjectArray, $interfaceName);
return $this;
}
Which ignores converted attributes because logic of merging based on presence getters and setters of target model\interface. So, if you converting attributes which haven't setters and getters in target model they will be ignored here:
Magento\Framework\Reflection\DataObjectProcessor.php line 75
public function buildOutputDataArray($dataObject, $dataObjectType)
{
$methods = $this->methodsMapProcessor->getMethodsMap($dataObjectType);
$outputData = [];
/** #var MethodReflection $method */
foreach (array_keys($methods) as $methodName) {
if (!$this->methodsMapProcessor->isMethodValidForDataField($dataObjectType, $methodName)) {
continue;
}
$value = $dataObject->{$methodName}();
$isMethodReturnValueRequired = $this->methodsMapProcessor->isMethodReturnValueRequired(
$dataObjectType,
$methodName
);
Maybe you might to use observer or plugin to avoid this problem. (issue encountered in 2.0.6 Magento version)
For anybody looking at this in the future, the fact that the fieldset XML doesn't work has been acknowledged by Magento as a bug. There is a core patch available in the ticket (not reproduced here since it may need to be tweaked with new Magento versions).
https://github.com/magento/magento2/issues/5823

Typo3 - Extbase CommandController for scheduler task

i ve created an empty extbase/fluid extension and added an ImportCommandController for a scheduler task. For some reason i am not able to load that task in my scheduler. Please note that i want to realise my task via CommandController (http://wiki.typo3.org/CommandController_In_Scheduler_Task) and NOT via \TYPO3\CMS\Scheduler\Task\AbstractTask.
ext_localconf.php
<?php
if (!defined('TYPO3_MODE')) {
die('Access denied.');
}
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][] = 'VENDORx\\Sched\\Command\\ImportCommandController';
Classes/Command/ImportCommandController.php
<?php
namespace VENDORx\Sched\Command;
/**
*
*
* #package Sched
* #license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
*
*/
class ImportCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController {
public function importCommand($commandIdentifier= NULL) {
echo 'command run';
}
}
?>
any idea whats missing??
As Jost already mentioned you neet proper Annotations:
/**
* #param integer $commandIdentifier
*/
public function importCommand($commandIdentifier = NULL) {
$this->outputLine('command run');
}
Select "Extbase-CommandController-Task" in dropdown
You'll get another select field on the bottom where you can find your "ImportCommand" select and save