PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label overriding. Show all posts
Showing posts with label overriding. Show all posts

Thursday, October 27, 2022

[FIXED] how to override tpl module in prestashop 1.7.1.1

 October 27, 2022     overriding, prestashop-1.7     No comments   

Issue

im trying to override the tpl of ps_categorytree module, but it didn't work i tried to put the file under override like this:

override/themes/laber_ethan_home5/modules/ps_categorytree/views/templates/hook/ps_categorytree.tpl

-im using prestashop 1.7.1.1 and i bought a theme.

Help please!


Solution

you don't need to put this in override folder, simply use the modules folder that is in the active theme. The correct way to put your tpl file is:

/themes/laber_ethan_home5/modules/ps_categorytree/views/templates/hook/ps_categorytree.tpl

Hope it helps you, bye.



Answered By - Addis
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 23, 2022

[FIXED] How to set Fedex Career in custom shipping module?

 August 23, 2022     fedex, magento2, overriding, php     No comments   

Issue

FedEx module's Carrier.php is extended in custom shipping module of our Magento store. I'm looking for a way to set FedEx carrier to "custom shipping" as below.

I don't seem to locate the method from the right class that returns the array of methods objects. Please help me find it. I tried to do it with $fedex_results->getAllRates() It isn't happening.

<?php

namespace Perfectmakeupmirrors\CustomShipping\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Perfectmakeupmirrors\PmmFedex\Model\PmmFedexCarrier;

/**
 * Custom shipping model
 */
class Customshipping extends AbstractCarrier implements CarrierInterface
{
    const FEDEX_METHODS = [
        'EUROPE_FIRST_INTERNATIONAL_PRIORITY' => 'Europe First Priority',
        'FEDEX_1_DAY_FREIGHT' => '1 Day Freight',
        'FEDEX_2_DAY_FREIGHT' => '2 Day Freight',
        'FEDEX_2_DAY' => '2 Day',
        'FEDEX_2_DAY_AM' => '2 Day AM',
        'FEDEX_3_DAY_FREIGHT' => '3 Day Freight',
        'FEDEX_EXPRESS_SAVER' => 'Express Saver',
        'FEDEX_GROUND' => 'Ground',
        'FIRST_OVERNIGHT' => 'First Overnight',
        'GROUND_HOME_DELIVERY' => 'Home Delivery',
        'INTERNATIONAL_ECONOMY' => 'International Economy',
        'INTERNATIONAL_ECONOMY_FREIGHT' => 'Intl Economy Freight',
        'INTERNATIONAL_FIRST' => 'International First',
        'INTERNATIONAL_GROUND' => 'International Ground',
        'INTERNATIONAL_PRIORITY' => 'International Priority',
        'INTERNATIONAL_PRIORITY_FREIGHT' => 'Intl Priority Freight',
        'PRIORITY_OVERNIGHT' => 'Priority Overnight',
        'SMART_POST' => 'Smart Post',
        'STANDARD_OVERNIGHT' => 'Standard Overnight',
        'FEDEX_FREIGHT' => 'Freight',
        'FEDEX_NATIONAL_FREIGHT' => 'National Freight'
    ];
    const SHIPPING_STANDARD = 'STD';
    const SHIPPING_2ND_DAY = '2DY';
    const SHIPPING_OVERNIGHT = 'ON';
    protected $_shipping_mode_strings = array(
        self::SHIPPING_STANDARD => 'Standard Ground',
        self::SHIPPING_2ND_DAY => 'Second Day',
        self::SHIPPING_OVERNIGHT => 'Next Day Air',
    );

    /**
     * @var string
     */
    protected $_code = 'customshipping';

    /**
     * @var bool
     */
    protected $_isFixed = true;

    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    private $rateResultFactory;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    private $rateMethodFactory;

    /**
     * @var \Perfectmakeupmirrors\CustomShipping\Helper\Data
     */
    private $helper;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    private $carrierFedex;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
     * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        \Perfectmakeupmirrors\CustomShipping\Helper\Data $helper,
        \Perfectmakeupmirrors\PmmFedex\Model\PmmFedexCarrier $carrierFedex,
        array $data = []
    ) {
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);

        $this->rateResultFactory = $rateResultFactory;
        $this->rateMethodFactory = $rateMethodFactory;
        $this->carrierFedex = $carrierFedex;
        $this->_logger = $logger;
        $this->helper = $helper;
    }

    /**
     * Custom Shipping Rates Collector
     *
     * @param RateRequest $request
     * @return \Magento\Shipping\Model\Rate\Result|bool
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        
        $this->_logger->info("Start of Custom Shipping collectRates");
        if ($request->getDestCountryId() == "CA") {
            $this->_logger->info("Country ID: " . $request->getDestCountryId());
            $fedex_results = $this->carrierFedex->collectRates($request);
            // $this->_logger->info("Fedex Rate " . $fedex_rate);
            // 1. Get the array of method objects from $fedex_results object           
            //$this->_logger->info($fedex_results->getAllRates()); 
            
            // 2. Get the array of methods objects.


            // 3. Loop through the array of method objects to set carrier.
            return $fedex_results;
            // Assemble FedEx methods.
            

        }

Solution

Use this to see if it helps.

$method->setCarrier($this->_code);


Answered By - CodeForGood
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] How to check if string exists in Enum of strings?

 July 07, 2022     class, enums, oop, overriding, python     No comments   

Issue

I have created the following Enum:

from enum import Enum

class Action(str, Enum):
    NEW_CUSTOMER = "new_customer"
    LOGIN = "login"
    BLOCK = "block"

I have inherited from str, too, so that I can do things such as:

action = "new_customer"
...
if action == Action.NEW_CUSTOMER:
    ...

I would now like to be able to check if a string is in this Enum, such as:

if "new_customer" in Action:
    ....

I have tried adding the following method to the class:

def __contains__(self, item):
    return item in [i for i in self]

However, when I run this code:

print("new_customer" in [i for i in Action])
print("new_customer" in Action)

I get this exception:

True
Traceback (most recent call last):
  File "/Users/kevinobrien/Documents/Projects/crazywall/utils.py", line 24, in <module>
    print("new_customer" in Action)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 310, in __contains__
    raise TypeError(
TypeError: unsupported operand type(s) for 'in': 'str' and 'EnumMeta'

Solution

I just bumped into this problem today; I had to change a number of subpackages for Python 3.8.

Perhaps an alternative to the other solutions here is the following, inspired by the excellent answer here to a similar question, as well as @MadPhysicist's answer on this page:

from enum import Enum, EnumMeta


class MetaEnum(EnumMeta):
    def __contains__(cls, item):
        try:
            cls(item)
        except ValueError:
            return False
        return True    


class BaseEnum(Enum, metaclass=MetaEnum):
    pass


class Stuff(BaseEnum):
    foo = 1
    bar = 5

Tests (either in py37 or 38):

>>> 1 in Stuff
True

>>> Stuff.foo in Stuff
True

>>> 2 in Stuff
False

>>> 2.3 in Stuff
False

>>> 'zero' in Stuff
False


Answered By - Pierre D
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, June 30, 2022

[FIXED] What is the correct domain for a new translation in a PrestaShop class override?

 June 30, 2022     module, overriding, prestashop, translation     No comments   

Issue

Can you help me with the use of the "domain" parameter in $this->trans() function ?

In my own module I have an override for the CartRule class. My override works correctly - it is copied from my module to the override folder by Presta and the code functions.

I have a new translated string inside, and I do not know what value to give for "domain".

My code:

$this->trans('Promotion codes cannot be combined', array(), 'Shop.Notifications.Error'); \\ ID, parameters, domain

For domain I have tried:

  1. "Shop.Notifications.Error" (same as the other strings): and then looked in BO > Theme Translations > My Theme (or classic theme) > French (store language)

  2. "Modules.[Mymodule].Admin" (for Mymodule I used a captialized short name): and then looked in BO > Module Translations > My Module > French (store language). This approach follows the PrestaShop rules.

Each time I have not found my string.

Do you have some ideas?

N.B. other answers on SO make use of $this->l which is not available in this context. I have also tried $this->module->trans() but "module" is not available in this context.


Solution

First of all in your module we have to specify which strings are translatable.

Translating for Prestashop (version 1.7.5 and older):

TPL:

    {l s='My text to translate' mod='modulename'}

PHP:

    $this->module->l('My text to translate');

Translating for Prestashop (version 1.7.6 and newer):

TPL:

    {l s='My text to translate' d='Modules.Modulename.Somefile'}

TWIG:

    {{ 'My text to translate'|trans({}, 'Modules.Modulename.Admin') }}

PHP:

    // For back-office translations we use "Admin"
    $this->trans('My text to translate', array(), 'Modules.Modulename.Admin');

    // For front-office translations we use "Shop"
    $this->trans('My text to translate', array(), 'Modules.Modulename.Shop');

Ash you can see we need to declare its a translatable string from a Module, with the Modulename (with a capital), and then define where the translatable string is located Admin, shop

Important note Using the prestashop new translation system needs to be declared in your module. so in your main php file, mymodule.php add following code:

    public function isUsingNewTranslationSystem()
    {
        return true;
    }

PrestaShop Developer Documentation (translations)

Information about the Classic module translation system (1.7.5 and <) can be found here.

Information about the New module translation system (1.7.6 and >) can be found here.

Translating your module:

After defining all translatable strings we install our module to a Prestashop web-shop.

When our module is installed we have to go to:

  1. Back office
  2. International -> Translations
  3. Modify translations
  4. Type of translation -> Installed modules translations
  5. Select your module -> modulename
  6. Select your language -> Language you want to translate

This progress will generate a translation file (.php) in your module.

Translation file location: modulename/translations/isocode.php

Good to know is that when you have one translated PHP file of your module (example en.php) you can translate the same, en.php, file multiple times and save it under a different isocode for example nl.php.



Answered By - Crezzur
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, May 18, 2022

[FIXED] How can tweaks to existing methods in an auto-generated C# partial class be persisted?

 May 18, 2022     c#, code-generation, overriding, partial, sealed     No comments   

Issue

I am working with Visual Studio Coded UI Tests, and wish to persist tweaks to the generated code.

The code is generated as a partial class in UIMap.cs and UIMap.Designer.cs, and so I know one solution would be to create a method with a slightly different name, such as myMethod_persist in UIMap.cs and use this instead of myMethod in UIMap.Designer.cs, which will be overwritten every time the source is regenerated.

This however seems very messy, and so what I'd prefer, is to instead override myMethod in UIMap.cs. This way the interface is not complicated with lots of gumph, and I don't have to remember to change every instance of myMethod in calling code to myMethod_persist

Unfortunately when it comes to C# I'm a bit of a noob, and don't even know if this is possible.

Basically what I want is this:

[UIMap.Designer.cs]
partial class myClass
{
    public override void myMethod( int a ){ somethingHorrible(int a); };
}

[UIMap.cs]
partial class myClass
{
    public sealed override void myMethod( int a ){ somethingNice(int a); };
}

But I know that the sealed and override keywords are usually used with derived subclasses classes, not partial classes. Is this possible? If not then what would be my best alternatives?


Solution

If you have no control over the auto-generation itself (ie. a framework or 3rd party generator) your options are somewhat limited. The two approaches that come to mind are to modify the generated code--which as you noted is not practical for changes that are significant and perhaps accumulating over time--and/or to create a derived class and use that instead of using the auto-generated class directly (assuming you control the code which would be using them, which seems likely).

A derived class (inheriting the auto-generated class) would be able to use override or new in the method declarations you want to replace. However, there are a lot of caveats to this approach as well. You can only "override" a method that was delcared as virtual in the base class (or was itself an override of another underlying virtual base, etc). You can also replace a method with a "new" one in the derived class, but the other code in the base class will not know about your "new" version and will not call it (whereas they will call your "override" because they know the method to be virtual). There are also issues of accessiblity; your derived class won't have access to private members of the base class.

But for some set of things you want to do it could work. In some cases you might have to tweak the auto-generated code slightly such as adding the keyword "virtual" or changing "private" members to "protected" so that you can access them from your derived class.

Added: Of course, you can also add new members to the original generated class in your own permanent file for the same partial class, and this code would have access to the class's private members. That can be another way to give your derived class access to the private members, such as by creating a protected property to wrap access to a private member field. If you didn't need to make changes to existing methods you wouldn't necessarily need to create a derived class, but your example talked about wanting to "override" methods from the auto-generated code, so presumably they already exist there.

Also note that a Designer file--such as for a Form or UserControl--does not usally get completely overwritten, so cautious changes outside the core generated code (eg. not inside the "Windows Form Designer generated code" region) can be made (and are persisted). For example, it is sometimes necessary to add a call to your own custom clean-up method in the Dispose(...) method in the Designer file.



Answered By - Rob Parker
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 27, 2022

[FIXED] how can I fix this weak warning? "The field doesn’t override an inherited getter or setter."

 April 27, 2022     dart, flutter, inherited, overriding, warnings     No comments   

Issue

It shows this: "The field doesn’t override an inherited getter or setter." And because of this issue I can't push my Code in Git as it fails on test and analyze.

Any suggestions on how I can solve it? I shifted _startDate and _endDate out of Override but now it shows: "The method doesn’t override an inherited method." for displayDatePicker.

import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:date_range_picker/date_range_picker.dart' as DateRagePicker;

class Datepicker extends StatefulWidget {
  @override
  _DatepickerState createState() => _DatepickerState();
}

class _DatepickerState extends State<Datepicker> {

  DateTime _startDate = DateTime.now();
  DateTime _endDate = DateTime.now().add(Duration(days: 7));
  @override

  Future displayDatePicker(BuildContext context) async {
    {
      final List<DateTime> picked = await DateRagePicker.showDatePicker(
          context: context,
          initialFirstDate: _startDate,
          initialLastDate: _endDate,
          firstDate: new DateTime(DateTime.now().year),
          lastDate: new DateTime(DateTime.now().year + 2));
      if (picked != null && picked.length == 2) {
        setState(() {
          _startDate = picked[0];
          _endDate = picked[1];
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          RaisedButton(
            child: Text('select Date'),
            onPressed: () async {
              await displayDatePicker(context);
            },
            color: Colors.red,
            textColor: Colors.white,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(18.0),
                side: BorderSide(color: Colors.red)),
          ),
          //Text("from:${_startDate}"),
          //Text("until:${_endDate}"),
          Text(
              "from:${DateFormat('MM/dd/yyyy').format(_startDate).toString()}"),
          Text("until:${DateFormat('MM/dd/yyyy').format(_endDate).toString()}")
        ],
      ),
    );
  }
}

Solution

displayDatePicker is not a method of State<Datepicker>, thus, we just need to remove the @override line above Future displayDatePicker:

  // remove this line ---> @override

  Future displayDatePicker(BuildContext context) async {
    {
      final List<DateTime> picked = await DateRagePicker.showDatePicker(
          context: context,
          initialFirstDate: _startDate,
          initialLastDate: _endDate,
          firstDate: new DateTime(DateTime.now().year),
          lastDate: new DateTime(DateTime.now().year + 2));
      if (picked != null && picked.length == 2) {
        setState(() {
          _startDate = picked[0];
          _endDate = picked[1];
        });
      }
    }
  }


Answered By - Stefano Amorelli
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 9, 2022

[FIXED] 'Error: Call to a member function allow() on a non-object' in CakePHP 3 AuthComponent

 March 09, 2022     authorization, cakephp, cakephp-3.0, overriding     No comments   

Issue

Following the CakePHP which looks a bit confusing and not so straight forward, I have created a basic authentication logic, however, I cannot seem to load Auth component.

Here is the code part from the AppController.php:

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
            'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]],
            'loginAction' => ['controller' => 'Users', 'action' => 'login'],
            'loginRedirect' => ['controller' => 'Groups', 'action' => 'index'],
            'logoutRedirect' => ['controller' => 'Users', 'action' => 'login']
    ]);  
}


//Allow basic views

public function beforeFilter(Event $event)
{
    $this->Auth->allow(['index', 'view', 'display']);
}

Now no matter which controller or action I run, I always receive the following error:

Error: Call to a member function allow() on a non-object 

that is referencing the following line:

$this->Auth->allow(['index', 'view', 'display']);

It has to be a straight forward thing, but I just cannot find it in the docummentation, therefore any help or guidance is much appreciated.


Solution

Check that your child controller's method initialize() is calling the parent method.

class MyController extends AppController
{
    public function initialize() {
        parent::initialize();
        //rest of code
    }
}


Answered By - Inigo Flores
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing