texts: Restrict access to pages for non logged users

texts:
I need to restrict access to all pages except / customers, contacts and home page
My code is don`n work
    <?php

use Magento\Customer\Model\Context;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;

class Restrictcmspage implements ObserverInterface
{

    /**
     * RestrictWebsite constructor.
     */
    public function __construct(
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Framework\App\Response\Http $response,
        \Magento\Framework\UrlFactory $urlFactory,
        \Magento\Framework\App\Http\Context $context,
        \Magento\Framework\App\ActionFlag $actionFlag
    )
    {
        $this->_response = $response;
        $this->_urlFactory = $urlFactory;
        $this->_context = $context;
        $this->_actionFlag = $actionFlag;
    }

    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        $allowedRoutes = [

            'customer_account_index',
            'customer_account_login',
            'customer_account_loginpost',
            'customer_account_create',
            'customer_account_createpost',
            'customer_account_logoutsuccess',
            'customer_account_confirm',
            'customer_account_confirmation',
            'customer_account_forgotpassword',
            'customer_account_forgotpasswordpost',
            'customer_account_createpassword',
            'customer_account_resetpasswordpost',
            'customer_section_load'
        ];

        $request = $observer->getEvent()->getRequest();
        $isCustomerLoggedIn = $this->_context->getValue(Context::CONTEXT_AUTH);
        $actionFullName = strtolower($request->getFullActionName());

        if (!$isCustomerLoggedIn && !in_array($actionFullName, $allowedRoutes)) {
            $this->_response->setRedirect($this->_urlFactory->create()->getUrl('customer/account/login'));
        }

    }
}
?>

But this code does not work correctly, I cannot add my pages and this code restricts the login to the admin panel
If the page is not in the allowed list, return the main page


texts: Auto Cron is Not Working When I want to add Data into DataBase

texts:
Here Data Was Successfully Addded Into Database When i Run php bin\magento cron:run Command But AutoMatically Data Wasn't Added.

vendor\module_name\Cron\Test.php

use Psr\Log\LoggerInterface;

class Test {
    protected $logger;

    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }

   /**
    * Write to system.log
    *
    * @return void
    */
    public function execute() {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $tableName = $resource->getTableName('my_employee');
        $sql = "Insert Into " . $tableName . " (name, position,status) Values ('Cron','CronTesting','0')";
        $connection->query($sql);
    }
}

vendor\module_name\etc\frontend\crontab.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="custom_cronjob" instance="Vendor\Module_name\Cron\Test" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

vendor\module_name\etc\frontend\cron_groups.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/cron_groups.xsd">
    <group id="custom_crongroup">
        <schedule_generate_every>1</schedule_generate_every>
        <schedule_ahead_for>4</schedule_ahead_for>
        <schedule_lifetime>2</schedule_lifetime>
        <history_cleanup_every>10</history_cleanup_every>
        <history_success_lifetime>60</history_success_lifetime>
        <history_failure_lifetime>600</history_failure_lifetime>
        <use_separate_process>1</use_separate_process>
    </group>
</config>


texts: Unable to override interface in magento2

texts:
I want to declare new method in interface "Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface"

I tried to override interface using di.xml

<preference for="Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface" type="Custom\DownloadableImport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface" />
<preference for="Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregator" type="Custom\DownloadableImport\Model\Import\ErrorProcessing\ProcessingErrorAggregator" />

But this doesn't seems  to work. Is there any way to override interface in magento2


texts: Magento 2: how override translates in language pack?

texts:
I installed language pack in **app/i18n/magento2translations/language_nl_nl/** with file nl_NL.csv It's works perfect.
Also, I added in custom theme file app/design/frontend/vendor/theme/i18n/nl_NL.csv with my custom translates, but it's not working for me (mode: developer, static content and caches were cleaned).
When I move custom translates to language pack's nl_NL.csv custom translates works fine.
I think the language pack has more priority as a custom theme i18n translates.
How override translates in language pack in the correct way?


texts:
I am trying to create a shopping cart rule, so far in the Conditions tab I have

If ALL  of these conditions are TRUE :

If total quantity  equals or greater than  5  for a subselection of items in cart matching ALL  of these conditions:
Category  is  686

In Actions I have Buy x get Y Free and I have the following options:

Discount Amount 1
Maximum Qty Discount is Applied To 0
Discount Qty Step (Buy X) 5
Apply to Shipping Amount NO
Free Shipping NO
Stop Further Rules Processing NO

But I have tried adding the 5 items that match and I have a coupon I have entered the coupon, but it says invalid. I have also tried it without a coupon and it does not seem to add the free product.


texts: i had upgraded magento 1.9 to magento 2.4 but it did not work properly so i decided to get back but when i restored it i can see this problem

texts:
error log
[14-Apr-2021 15:18:01 Australia/Sydney] PHP Fatal error:  Uncaught Error: Class 'Magento\Framework\App\ErrorHandler' not found in /home/martarab/public_html/bin/magento:20
Stack trace:
#0 {main}
thrown in /home/martarab/public_html/bin/magento on line 20


texts: White screen in order view at magento admin

texts:
I already read alot of articles here but no one helped me.
Many orders is showing white screen.

  my php is 5.5.35 magento version 1.9.2.4(clean)

I already check:

max_execution_time
memory_limit

setted(htaccess)

#Magento Developer Mode
SetEnv MAGE_IS_DEVELOPER_MODE "true"

and (index.php)

ini_set('display_errors', 1);

There is no error at exception or system logs

var/log/system.log
var/log/exception.log

I already put old files at adminhtml but nothing happens...

app/design/adminhtml/default/default/

solved patch SUPEE-7405:

Change line 124 in app/code/core/Mage/Adminhtml/Helper/Sales.php from $links = []; to $links = array();

what else I could try?

I found my problem. It´s this foreach:

$order = Mage::getModel('sales/order')->load($item->getOrderId());
$store = Mage::getSingleton('core/store')->load(1);
$quote = Mage::getModel('sales/quote')->setStore($store)->load($order->getQuoteId());
$items = new Mage_Sales_Model_Resource_Quote_Item_Collection();
$quoteItem = $items->addFieldToFilter('item_id', $item->getQuoteItemId())
    ->setQuote($quote)
    ->getFirstItem();

$helper = new Mage_Catalog_Helper_Product_Configuration();
foreach ($helper->getOptions($quoteItem) as $itemOption){
    $text .= '
' . $itemOption['label'] . ':
 ';
    $text .= '
' . $itemOption['print_value'] . '
';
}

$quoteItem returns protected items:

object(Mage_Sales_Model_Quote_Item)#884 (24) { ["_eventPrefix":protected]=> string(16) "sales_quote_item" ["_eventObject":protected]=> string(4) "item" ["_quote":protected]=> NULL ["_options":protected]=> array(0) { } ["_optionsByCode":protected]=> array(0) { } ["_notRepresentOptions":protected]=> array(1)

How the best way to make this foreach?


texts: I am getting error while uploading product, how can i fix that?

texts:
I have managed different stores in magento and different users for this also, i have managed different users for upload product for different store.

When i try to upload product from main store then there is no any error but when i try to upload via different user then this error occured.


texts:
It is ok to drop tables that end in _cl and _tmp

Does anyone have a comprehensive table clean up list? For example, can I clean up all the sales_flat_quote tables that are more than 30 days old?

TRUNCATE sales_flat_quote;
TRUNCATE sales_flat_quote_address;
TRUNCATE sales_flat_quote_address_item;
TRUNCATE sales_flat_quote_item;
TRUNCATE sales_flat_quote_item_option;

EDIT: Sorry this was a two part Question, Drop Tables that end if _cl or _tmp and truncate the other tables


texts: Changes Not Showing Client Side Without Clearing Cache

texts:
Whenever I make changes css or anything I have to ask the client to clear cache to view the changes same for me.

Any advise on how to deal with this.

Magento 2.


texts: Can't update old Configurable Products after update from Magento 2.3 to Magento 2.4.1

texts:
when I update Magento from 2.3 to 2.4.1, I can't save the old Configurable Products, it said that error "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '))' at line 2, query was: SELECT main_table.*, cp_table.type_id FROM cataloginventory_stock_item AS main_table INNER JOIN catalog_product_entity AS cp_table ON main_table.product_id = cp_table.entity_id WHERE (main_table.website_id = '0') AND (main_table.product_id IN())",
but when create a new Configurable Products, it still works perfect.

Do anyone have same problem, please help. Thanks.


texts:
I have a doubt, how patch are given by magento.

SUPEE-10752 (Added Jun 27, 2018)
SUPEE-10888 (Added Sep 18, 2018)
SUPEE-10975 (Added Nov 28, 2018)

Whether that latest patch 10975 included the previous
patches(10752, 10888)


texts: Show address fields in form registration in Magento 2

texts:
I have created another form registration for customer and according to group he will be redirected to a form. I added the fields of address in the first one by adding this code in customer_account_create.xml.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_form_register">
            <action method="setShowAddressFields">
                <argument name="show.address.fields" xsi:type="boolean">true</argument>
            </action>
        </referenceBlock>
    </body>
</page>

but I don't know how to do it for the second. I also tried to do the same in this XML by duplicating the reference block :

<referenceBlock name="customer_form_register_2">
    <action method="setShowAddressFields">
        <argument name="show.address.fields" xsi:type="boolean">true</argument>
    </action>
</referenceBlock>

but I got this error

so how to fix this please


texts: What's the best way to create landing pages in Magento?

texts: I was wondering if the best way to create landing pages and templates for these in Magento is to create cms pages? Write static blocks and then create a new cms page all the time or is there another good way to do this? Is a category page better?


texts:
I am looking for ER diagram of magento 1.9.x so that i can understand magento database flow and table-relationships. if anyone can provide me COMPLETE ER diagram that will really help me. Like i saw a good er diagram of prestashop but could not find such diagram of magento.

Update: For ER Diagram of Magento 2.1.3 check https://magento.stackexchange.com/a/152061/29175 . Thanks to efforts of @Anna Völkl


texts:
In my admin section of magento I am getting error
Uncaught ReferenceError: jQuery is not defined

How I resolve it please let me know


texts: Use of sub query within collection in Magento

texts:
I am using a subquery in Magento collection,

Here is my code.

$websiteId = $this->storeManager->getStore()->getWebsiteId();

$collection = $this->_productCollectionFactory->create();
$collection->setVisibility($this->_productVisibility->getVisibleInSiteIds());
$collection->addAttributeToSelect('*');
$collection->addAttributeToSelect(array('entity_id','sku'));
$collection->addWebsiteFilter($websiteId);
$collection->addStoreFilter();
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$this->_stockFilter->addInStockFilterToCollection($collection);
$collection = $collection
    ->joinField('qty',
        'cataloginventory_stock_item',
        'qty',
        'product_id=entity_id',
        '{{table}}.stock_id=1',
        'left'
    )
    ->addAttributeToSelect('stock_status')
    ->addAttributeToSort ( 'entity_id', 'DESC' )
    ->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);

$collection->addAttributeToFilter(array(
    array(
            'attribute' => 'qty',
            'gt'=>0),
        array(
            'attribute' => 'type_id',
            'eq' => 'grouped'),
        array(
        'attribute' => 'type_id',
        'eq' => 'configurable')
))->load();
$subquery = new \Zend_Db_Expr('(SELECT b.parent_id FROM cataloginventory_stock_item AS a JOIN catalog_product_relation AS b ON a.product_id = b.child_id WHERE a.qty <= 0)');

$collection->addFieldToFilter('e.entity_id', array('nin' => $subquery));

But I am getting error after using the above code, Can anyone help me on how to use a subquery in magneto 2 collections.

Thank you for your help.


texts: How to limit number of characters typed in Short Description in the Admin Panel?

texts:
Is it possible to limit the number of characters typed on the Short Description text area in the Admin Panel?

My Magento version is 1.9.3.1 .


texts: Change the sitemap.xml size limit in magento 1.x.x

texts:
It seems that Magento 1.x.x. generated sitemap.xml is limited to 10MB.

Is there any way to change the limit?

I do know that I'll need to split the generated sitemap into smaller chunks after that to satisfy google.

It just seems weird to me that there is no functionality for changing the sitemap size, or generated multiple small ones.

I suppose i could go to a online crawler/generator but they are usually very slow and not that effective/clean.


texts: Grouped products doesn't display on category page only at first time

texts:
I am facing this unusual issue where grouped products are not being displayed only when the page loads for the first time.

After refreshing the category page all products are being displayed.

I have tried following 2 fix:

Disable and then Re-Enable:

  I have tried to disable-enable them, it fixed the issue
  temporarily. But after 2 days it is again the same.

As mentioned in answer by Mudit, every time I save/update any product, the cache for Blocks HTML output gets invalidated:

  I have also tried a corn job with following code to clear invalidated
  caches every minute:

$invalid = Mage::app()->getCacheInstance()->getInvalidatedTypes();
foreach($invalid as $i)
{
    Mage::app()->getCacheInstance()->cleanType($i["id"]);
}

  This refreshes the cache every minute but, issue still persists.

Any guidance on this?


texts: Different new order emails based on customer group

texts:
I want to customise the new order email based upon the customer group. Ideally it would be great to have separate email templates for each group.

I have found the following plugin http://goo.gl/1JOsHR however wanted to know if this is the best way to go about this before I brought it or if there is a better extension  or method out there


texts:
i want to update update magento 1.9.1.0 to 1.9.2.0

i google most of link here but could not find proper answer, i am bit stucked how to proceed

1: i tried to updated all modules using "Magento connect manager"
but i had issue

i console i see some conflict error

also after process is completed it keep on redirecting me to download page

i tried this two three times same error ,

i need help the proper way to update modules


texts:
I have created a class in module as im working on discount module.

class Custom extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal
{
    protected $_priceCurrency;

    public function __construct(
        \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
    ) {
        $this->_priceCurrency = $priceCurrency;
    }

    public function collect(
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total
    ) {
        parent::collect($quote, $shippingAssignment, $total);
        $baseDiscount = 10;
        $discount = $this->_priceCurrency->convert($baseDiscount);
        $total->addTotalAmount('customdiscount', $discount);
        $total->addBaseTotalAmount('customdiscount', $baseDiscount);
        $total->setBaseGrandTotal($total->getBaseGrandTotal() - $baseDiscount);
        $quote->setCustomDiscount($discount);

        return $this;
    }
}

I'm getting an error like

  syntax error, unexpected '   protected' (T_STRING), expecting function (T_FUNCTION) in C:\xampp1\htdocs\Magento\app\code\Discout\Mode\Model\Quote\Custom.php on line 6


texts: extending custom(not core based) classes

texts:
In my project I have a "lib" directory with different custom libs/classes from php community. But unfortunately I need to extend several classes from "lib" directory.
How can I do that in magento way? I mean, helper doesn't fit for this role because I need to path constructor arguments etc.
Thanks a lot!


texts: Magento 2 How to make magento not to cache static content of Checkout module?

texts:
I'm modifying the checkout process, every time I edit a html file or a javascript file, I must use the command magento setup:static-content:deploy because the html or javascript is cached by magento. Doing deployment is very time wasting, how to make the magento not to cache the static content? I've tried to switch to developer mode, but the static content still be cached.
Thanks


texts:
@edit
It has already been solved

How would the unit test of this plugin be?
public function afterPrepare(uiMassAction $subject, $result)
{
    $roleName = $this->adminSession->getUser()->getRole()->getRoleName();

    if ($roleName !== self::ROLE_ADMIN) {
        $subject->setData('config', []);
    }

    return $result;
}

adminSession has already been mocked, but I can't call getUser(), getRole() and geRoleName().
protected function setup(): void
{
    $this->adminSession       = $this->createMock(Session::class);
    $this->uiMassAction       = $this->createMock(uiMassAction::class);

    $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
    $this->class   = $objectManager->getObject(MassAction::class, [
        'adminSession' => $this->adminSession
    ]);
}

I'm learning test unit, can someone help me?


texts: SQL Syntax Error near 'cat_index.is_parent=1'

texts:
One of my webshops had an issue regarding products being shown which are not supposed to be shown. So, a friend of me and I came to a fix. Add code to the observer "catalog_produyct_collection_apply_limitations_after". The following code has been added:

public function catalogProductCollectionApplyLimitationsAfter($observer) {
    $collection = $observer->getCollection();
    $select = $collection->getSelect();
    $from = $select->getPart('from');

    if(array_key_exists('joinCondition',$from['cat_index'])) {
        if(strpos($from['cat_index']['joinCondition'],'is_parent') === false) {
            $from['cat_index']['joinCondition'] = $from['cat_index']['joinCondition'] . 'AND cat_index.is_parent=1';
            $collection->getSelect()->setPart('from', $from);
        }
    }
}

However, after a while this results in an error when visiting the webshop. This error shows up:

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cat_index.is_parent=1
   LEFT JOIN core_store AS store_index ON store_index.st' at line 3, query was: SELECT COUNT(DISTINCT e.entity_id) FROM catalog_product_flat_3 AS e
   INNER JOIN report_compared_product_index AS idx_table ON (idx_table.product_id=e.entity_id) AND (idx_table.visitor_id = '5477917')
   INNER JOIN catalog_category_product_index AS cat_index ON cat_index.product_id=e.entity_id AND cat_index.store_id=3AND cat_index.is_parent=1
   LEFT JOIN core_store AS store_index ON store_index.store_id = idx_table.store_id
   LEFT JOIN core_store_group AS store_group_index ON store_index.group_id = store_group_index.group_id
   LEFT JOIN catalog_category_product_index AS store_cat_index ON store_cat_index.product_id = e.entity_id AND store_cat_index.store_id = idx_table.store_id AND store_cat_index.category_id=store_group_index.root_category_id
   LEFT JOIN enterprise_catalogpermissions_index AS perm ON perm.category_id=cat_index.category_id
                          AND perm.customer_group_id= 0 AND perm.website_id=3 WHERE (e.status = 1) AND (cat_index.visibility IN(3, 2, 4) OR store_cat_index.visibility IN(3, 2, 4)) AND (perm.grant_catalog_category_view != -2 OR perm.grant_catalog_category_view IS NULL) AND (cat_index.store_id=3) AND (cat_index.is_parent=1)

When I save the php file which contains the observer rewrite without any change, the webshop is working again for a short while. I'm not sure what is causing this and why this is happening.

I hope anyone is able to help me out.


texts: The install seemed to finish without any issue at all however looking at the frontend and backend its not loading any css or js as seen in inspect tool in chrome developer tools.


texts: How Can I Change product prices on checkout step 4 (After customer choose payment method)?

texts:
public function paymentEvent(Varien_Event_Observer $observer) {
    $this->log("Entramos al observer");
    $quote = $observer->getQuote();
    $store = Mage::app()->getStore($quote->getStoreId());
    $cartItems = $quote->getAllVisibleItems();

    foreach($cartItems as $item) {
       $productId = $item->getProductId();
       $product = Mage::getModel('catalog/product')->load($productId);
       $newPrice = $this->getNewPrice($product->getPrice()); // Function that calculate the newPrice (%)
       $product->setPrice($newPrice);
       $this->log($product->getPrice()); // this shows the new price
       $product->save(); // this doesn't save nothing, on step 5 the price is the same.
    }
    $this->log("Observer END");
    return $this;
}


texts: Magento 2.2.8 - Error Creating Product Through API with Images

texts:
I have a Java desktop app that has the ability to link directly with Magento 2. I migrated a client from Magento 1.7.0.2 to Magento 2.1 then upgraded them from that to 2.2.8. Afterwards, I performed a delta migration to bring the changes from M1 to M2.

I am currently unable to create products through the REST API as I get the following stack trace in my logs. I don't get these on the server and get them through my local Java logs.

Error Response Message: ErrorResponse{message='Cannot save product.', errors=null, code=null, parameters=null, trace='#0 [internal function]: Magento\Catalog\Model\Product\Gallery\GalleryManagement->create('2296', Object(Magento\Catalog\Model\Product\Gallery\Entry))
#1 /html/vendor/magento/module-webapi/Controller/Rest/SynchronousRequestProcessor.php(95): call_user_func_array(Array, Array)
#2 /html/vendor/magento/module-webapi/Controller/Rest.php(244): Magento\Webapi\Controller\Rest\SynchronousRequestProcessor->process(Object(Magento\Framework\Webapi\Rest\Request\Proxy))
#3 /html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Webapi\Controller\Rest->dispatch(Object(Magento\Framework\App\Request\Http))
#4 /html/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Webapi\Controller\Rest\Interceptor->___callParent('dispatch', Array)
#5 /html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Webapi\Controller\Rest\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#6 /html/generated/code/Magento/Webapi/Controller/Rest/Interceptor.php(39): Magento\Webapi\Controller\Rest\Interceptor->___callPlugins('dispatch', Array, Array)
#7 /html/vendor/magento/framework/App/Http.php(136): Magento\Webapi\Controller\Rest\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#8 /html/generated/code/Magento/Framework/App/Http/Interceptor.php(24): Magento\Framework\App\Http->launch()
#9 /html/vendor/magento/framework/App/Bootstrap.php(257): Magento\Framework\App\Http\Interceptor->launch()
#10 /html/index.php(39): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http\Interceptor))
#11 {main}'}

I looked up the issue and found that if the media_gallery attribute in eav_attribute is set to varchar instead of static, this can possibly happen. I changed the attribute to static and flushed my caches. But there was no change. I'm not entirely sure where the main differences are between this database with migrated M1 data and a fresh Magento 2.2.8 install. It does work on a fresh install so I'm fairly confident it's a database schema issue, but I'm not 100 percent on that.


texts:
I am trying to add a new getter and setter to \Magento\Catalog\Api\Data\CategoryTreeInterface.

I have created a new interface -
 \Wildcard\CategoriesApi\Api\Data\CategoryTreeInterfaceand a new model - \Wildcard\CategoriesApi\Model\Category.

When I call the /V1/categories endpoint the property is not shown.

However, if I directly add the getter and setter to the core interface, it works.

My 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\Catalog\Api\Data\CategoryTreeInterface" type="Wildcard\CategoriesApi\Api\Data\CategoryTreeInterface"/>
    <preference for="Magento\Catalog\Model\Category" type="Wildcard\CategoriesApi\Model\Category"/>
    <preference for="Wildcard\CategoriesApi\Api\Data\CategoryTreeInterface" type="Wildcard\CategoriesApi\Model\Category"/>

</config>

PHPStorm does highligh the Wildcard\CategoriesApi\Api\Data\CategoryTreeInterface in the type parameter in the first preference as not being able to resolve. I have triple checked my namespacing and file/folder names but they are all correct.

Can someone please help with how to add my methods to the interface?

Using Magento 2.1.7


texts: Invoice PDF, add new line in insertDocumentNumber

texts:
I have added the Invoice Creation Date to the invoice PDF, modifying the the app\code\core\Mage\Sales\Order\Pdf\Ivoice.php like so:

$this->insertDocumentNumber(
    $page,
    Mage::helper('sales')->__('Invoice # ')
    . $invoice->getIncrementId()
    . " - "
    . Mage::helper('sales')->__('Invoice Date')
    . " "
    . Mage::helper('core')->formatDate($invoice->getCreatedAt(), 'medium', false)
);

But instead of the string " - " I wish to insert a new line, I've already tried "\n" and "<br>"


texts: Magento 2 customer session setAfterAuthUrl() failed to set redirect URL

texts:
I have created custom module for custom blog wishlist. So I have set authentication while trying to save blog into wishlist as below
Controller >> save.php

public function execute()
{
    $data = [];
    /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

    if(!$this->_customerSession->isLoggedIn()) {
        $resultRedirect->setPath($this->url->getCurrentUrl());
        $this->_customerSession->setAfterAuthUrl($this->url->getCurrentUrl());
        $this->_customerSession->authenticate();
        return false;
    }

    $requestParams = $this->getRequest()->getParams();

    $postId = $requestParams['postid'];
    if (!$postId) {
        $resultRedirect->setPath('*/');
        return $resultRedirect;
    }

    /** @var \VendorName\Blog\Model\Post\Wishlist $model */
    $model = $this->wishlistFactory->create();

    $data['post_id'] = $postId;
    $data['customer_id'] = $this->_customerSession->getCustomer()->getId();
    // $data['update_at'] = $date;

    $model->setData($data);

    try {
            $model->save();
            $this->messageManager->addSuccess(__('Post Saved.'));
            $this->dataPersistor->clear('blog_post');
            if ($this->getRequest()->getParam('back')) {
                return $resultRedirect->setPath('ideas-blog/category/home');
            }
            return $resultRedirect->setPath('blog/post/wishlist');
        } catch (LocalizedException $e) {
            $this->messageManager->addError($e->getMessage());
        } catch (\Exception $e) {
            echo"<pre/>"; print_r($e->getMessage());exit;
            $this->messageManager->addException($e, __('Something went wrong while saving the post in wishlist.'));
        }

        $this->dataPersistor->set('blog_post', $data);
        return $resultRedirect->setPath('blog/post/wishlist');
}

$this->url->getCurrentUrl() has the current URL on which customer should be redirect after login successfully.

But I have created one plugin for another module which allow me to set redirect path after login :

public function afterExecute(
    \Magento\Customer\Controller\Account\LoginPost $subject,
    $result
    )
{
    $errorMessages = $this->messageManager->getMessages()->getErrors();
    if(!count($errorMessages))
        $result->setPath('customerview/account');

    return $result;
}

Above plugin will redirect to my custom account view page after normal login, but I want to redirect to custom wishlist page if set path as 'blog/wishlist'

So any idea how to do that?


texts: Insert phtml in custom CMS page Magento 2

texts:
i had created a new module on Magento 2.
It have:

setup -> UpgradeData.php :

    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        /**@var \Magento\Cms\Model\Page $page */
        if (version_compare($context->getVersion(), '1.1') < 0) {
            $page = $this->_pageFactory->create();
            $page->setTitle('Voucher CMS')
                ->setIdentifier('voucher-cms')
                ->setIsActive(true)
                ->setPageLayout('1column')
                ->setStores(array(0))
                ->setContent('{{block class="Cincuenta\\Voucher\\Block\\Product\\View\\Extra" block_id="voucher-cms" template="Cincuenta_Voucher::voucher/voucher.phtml"}}
')
                ->save();
        }

        $setup->endSetup();
    }

It creates well my new CMS with the content.

I had a phtml on view -> frontend -> templates -> voucher -> voucher.phtml:

<h1> Test Voucher</h1>

and Block - Product -View - Extra.php:

<?php

namespace Cincuenta\Voucher\Block\Product\View;

class Extra extends \Magento\Catalog\Block\Product\View
{

}

Code on my CMS:

{{block class="Cincuenta\\Voucher\\Block\\Product\\View\\Extra" block_id="voucher-cms" template="Cincuenta_Voucher::voucher/voucher.phtml"}}

But when i try to see my H1 in my CMS, it don't give me nothing, but a few times gives me an error that i was calling a wrong block.


texts: Admin email send on register.phtml firing on page load not form submit

texts:
I followed the tutorial below. I'm trying to send an email to the administrator when a new user signs up. The email is sending it's just sending when I hit the page not after filling out the information. How can I only have it send after they fill out the registration form??

http://inchoo.net/magento/magento-custom-emails/#comments

In my config.xml

<email>
  <custom_email_template1 module="SampleModule1">
    ActiveCodeline custom email module
    <file>activecodeline_custom_email1.html</file>
    <type>html</type>
  </custom_email_template1>
</email>

In App/local/en_us/template/email/activecodeline_custom_email1.html

ActiveCodeline custom email example by Branko Ajzele

Hi there {{var myvar1}} {{var myvar2}} from {{var myvar3}}. This is just some example template to test custom email module.

and lastly in my register.phtml I put this at the bottom.

<?

    $emailTemplate = Mage::getModel('core/email_template')->loadDefault('custom_email_template1');

    //Getting the Store E-Mail Sender Name.
    $senderName = 'billa';

    //Getting the Store General E-Mail.
    $senderEmail = 'email@email.com';

    //Variables for Confirmation Mail.
    $emailTemplateVariables = array();
    $emailTemplateVariables['myvar1'] = 'Email Address';
    $emailTemplateVariables['myvar2'] = 'Ajzele';
    $emailTemplateVariables['myvar3'] = 'ActiveCodeline';

    //Appending the Custom Variables to Template.
    $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);

    //Sending E-Mail to Customers.
    $mail = Mage::getModel('core/email')
    ->setToName('bilaa')
    ->setToEmail('email@email.com')
    ->setBody($processedTemplate)
    ->setSubject('Subject : A New Customer Has Signed Up')
    ->setFromEmail('email@email.com')
    ->setFromName('New Customer Notification')
    ->setType('html');
    try{
    //Confimation E-Mail Send
    $mail->send();
    }
    catch(Exception $error)
    {
    Mage::getSingleton('core/session')->addError($error->getMessage());
    return false;
    }
?>


texts: How to validate Magento 2 form field input value with database table field to find out if already exists?

texts:
I have added following affiliate email field (custom attribute) to the customer registration form. Now I want to validate that if value already exists in the database table.

 <div class="control">
        <input type="text" name="affiliate_email" id="affiliate_email" value="<?= $block->escapeHtml($block->getFormData()->getCustomField()) ?>" title="<?= __('CustomField') ?>" class="input-text"  data-mage-init='{"validation":{}}'>
    </div>

What is the best way to do this ?


texts: After upgrade from CE 2.1.1 > 2.1.5 category select in product admin is blank?

texts:
I've just upgraded Magento from 2.1.1 to 2.1.5 (via composer) and all went well except for 1 bug..

If I go to admin > products > catalog and pick any product from the catalogue to open the edit screen the "Categories" select box is blank?

I have no idea on where to start debugging this as there are no console errors or anything in the logs (Magento or PHP error logs)

I've tried disabling 3rd party modules with no effect?


texts: Magento - How to update order status cancel or declined If credit card did not go through in NMI Payment?

texts:
I have integrated my website with NMI Payment Gateway.
How to update the Order Status Cancel or Declined If Credit card did not go through in NMI in Magento 1.9.3.1?
Please help me with this.


texts: Issue with Google Shopping plugin outputting massive arrays

texts:
I'm working on integrating Google Shopping with my Magento installation but have ran into an issue with the plugin (provided by https://github.com/bluevisiontec/GoogleShoppingApi)

The plugin works great on our UK counterpart, but on the US environment

<?php echo $this->getAttributesSelectHtml(true) ?>

(located at /app/design/adminhtml/default/default/template/googleshoppingapi/types/edit/attributes.phtml) causes large (approximately 40mb) to be output. I've look at the function inside the relevant block and can't seem to find anything wrong.

The server is a newly configured environment running Magento 1.9.1 with PHP 5.4. I encountered the same issue in the old environment we were using, hence changing.


texts: Echo different text if specific product is in cart or not

texts:
I want to show "Text 1", when the Product with the ID 1 is in the cart.
I want to show "Text 2", when the Product with the ID 1 is NOT in the cart.

My code already works for "Text 1". This Text is shown on the right place (in the cart header). But I don´t know how to setup, that there is a "Text 2" shown, when the product with ID 1 is not in cart.

I´m really new into magento and don´t know exactly how to do that.

Here is my code, I came so far until now:

 <?php
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
$found = false;
foreach ($items as $item) {
    if ($item->getProductId() == 1){
        $found = true;
        echo "Text 1";
        break;
    }
}
?>


texts:
I am a newbie to magento and am trying to install magento 2 using cli. I have encountered the following:

  [InvalidArgumentException]
  Script "magento" is not defined in this package

php70 /usr/bin/composer run-script -- magento setup:install - was the command I was attempting to use... I was was hoping for some detailed steps on correcting this.


texts: Magento2 - Incompatibility in data (magento miration error)

texts:
here is the error i am getting during migration

  [2020-02-26 07:12:10][ERROR]: Incompatibility in data. Source
  document: eav_attribute. Field: source_model. Error: Class
  eav/entity_attribute_source_custom is not mapped in record
  attribute_id=563

I tried to use the below code in class-map.xml but not worked. and I also chaned the class-map.xml.dist to class-map.xml.

 <?xml version="1.0" encoding="UTF-8"?>

<!-- /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -->

<classmap xs:noNamespaceSchemaLocation="../class-map.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">

<rename>

<from>eav/entity_attribute_source_custom </from>

<to>Afg\Customerattribute\Model\Customer\Attribute\Source\Useurterm</to>

</rename>

</classmap>

the error I am getting after change the name of class-map.xml is

  Invalid map filename


texts: How to translate coupon title "Discount"

texts:
I tried to translate with the translate.csv file, but in this case it doesn't work.

I also tried to find the file in "checkout" folder (every file in the folder) but it doesn't contain the word "Discount".

Any suggestion how this can be done?


texts: Maximum allowed file size for upload is 2m?

texts:
I get this error:

  "Maximum allowed file size for upload is 2m. Please check your server PHP settings"

Magento ver 1.9.1.0
VPS Linux server with WHM Manager and cPanel access.

Every time I try to upload a file larger then 2M inside Magento it gives me that error.
I have added the line php_value upload_max_filesize 10M to both my .htaccess and php.ini files in the public_html folder.

I have gone into WHM and into the configuration editor and changed it to 10mb there. I hop into cPanel and in the PHP Configuration it says its set to 10m, but, when I go to sewchacha.com/phpinfo.php it says that the max upload size is set to 2M.

I have multiple other sites on this server in their own cPanel's and they show the correct 10m with the phpinfo.php file. It is only this site that doesn't show it correctly. Yes I have restarted the server several times after making the changes in the .ini and .htaccess files.

Is there something in Magento that is overriding the server settings?

Am I missing something?

Thank you for your help!


texts:
I was wondering if there is way to install/upgrade Magento2 every night using a shell install script run by cron. Our server runs Centos/Nginx/Php-fpm.

Question: I was fiddling with some code and thought I'd share it now - because maybe an auto-cron isntall script for Magento2 already exists?

#!/bin/sh

su myusername
MAGEDIR="/home/myusername/domains/example.com/public_html/"
cd $MAGEDIR
rm -rf $MAGEDIR*
git clone https://github.com/magento/magento2.git
chown -R myusername $MAGEDIR
sudo find $MAGEDIR -type d -exec chmod 700 {} \;
sudo find $MAGEDIR -type f -exec chmod 600 {} \;
composer install
chown -R myusername $MAGEDIR

check for complete reinstall flag or nightly update

cd $MAGEDIR/bin
if {update}
php magento setup:install --base_url=http://example.com --backend_frontname=beheer --db_host --db_name --db_user --db_password --admin_firstname=admin --admin_lastname=admin --admin_email=info@admin.com --admin_user=admin --admin_password=MYPASSWD --language=en_US --currency=dollar --timezone=Ams/nl
{else}
complete reinstall here
--clean_database

check for sample data flag


texts: How to display errors from a custom controller in the view cart page?

texts:
I've created a custom controller to add multiple items from a grid view to the cart all at one time.

Works just fine - the problem is the success and error messages are not being displayed on the view cart page.

Here is the controller:

<?php

    class BigBlockStudios_UpdateCart_ManageController extends Mage_Core_Controller_Front_Action {

        // add multiple products to the cart
        public function multipleProdAddAction() {

            $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : 'checkout/cart';

            $success = '';

            $errors = '';

            $cart = Mage::helper('checkout/cart')->getCart();

            $items = $_POST['data'];

            foreach($items as $key => $item){

                $sku = $item['sku'];

                $qty = $item['qty'];

                $id = Mage::getModel('catalog/product')->getIdBySku($sku);

                if(!$id || $qty <= 0) {

                    unset($items[$key]);

                }else{

                    try {

                        $params = array('qty' => $qty);

                        $id = Mage::getModel('catalog/product')->getIdBySku($sku);

                        $product = Mage::getModel('catalog/product')->load($id);

                        $cart->addProduct($product, $params);

                        $success .= $product->getName(). " is successfully added into cart
";

                    }catch(Exception $e) {

                        $errors .= $e->getMessage() . '
';

                    }

                }

            }

            $cart->save();

            if(strlen($success) > 1) {
                Mage::getSingleton('core/session')->addSuccess(Mage::helper('checkout')->__($success));
            }

            if(strlen($errors) > 1){
                Mage::getSingleton('core/session')->addError(Mage::helper('checkout')->__($errors));
            }

            $this->_redirect($redirect);

        } // multipleProdAddAction()

    } // controller

?>

The view cart page is displaying messages, if I add an item from a default product page, I get the success message.

What is the correct way of doing this?


texts: Displaying new set of thumbnails in Configurable Product Swatches

texts:
So, this question has been asked multiple times in the past and yet I didn't find an answer for it.

I am running Magento 1.9.2 which comes with Configurable Product Swatches. Now I can display product image according to the selected color.

However, Is it possible to load a whole set of new images when user change the color value, instead of only changing 1 image per Color?

For example: Let's say I have T-shirt with different colors, and I want to display front and back of the T-shirt accordingly to the color.

Putting both front and back of the T-shirt in 1 image is NOT the solution.

If this is not supported by default in Magento, Is there any plugin that can guarantee this feature?


texts: Second Website doesnt show in configuration

texts:
I have added a second Website (with own store and view) to my Magento 1.8 installation. The first website/shop works great, no problem.

However, If I try to do some basic things as:
* edit this second website/store/view settings from Configuration I cant select this website/store/view. I am only seeing the initial one
* try to add a new page, only for this new website I cant add as the same, I cant select the second website for this.

Any clue ?


texts: From price for configurables in Magento 2

texts:
Trying to find a simple and elegant way to display a from price for configurables prior to an attribute bring set, eg size.

So on product page the price renderer would initially say From X and then drop the From once an attribute is selected.

Any hints would be appreciated.


texts: Empty the Cart items but keep the quote and quote items

texts: I have added a button on cart page. Clicking on the button the cart items should get deleted but the quote should not be erased.


texts:
How can I fetch Order URL on frontend just like its done in Customer Account dashboard > My Orders ?

The code written in history.phtml file for Order URL is as under:

<a href="<?php echo $this->getViewUrl($_order) ?>"><?php echo $this->__('View Order') ?>

How can I call the function getVIewUrl() and pass my order_id to fetch the Order URL ?

I do not want to use BaseUrl() and then append sales/order/view/order/id/$orderId.

Please Help

Thanks


texts: Magento 1.x search product by specific value in http queryString

texts:
Been trying to search how to search item in magento 1.x to return JSON output when requesting something like.

www.site.com/api/rest/product?desc=Dress&color=black

Been to their doc and the reference they have isn't very clear, as I tried this example and just changed BlackBerry%208100%20Pearl to the item I have in my store and it returned []. I'm using a data sample from the download section.

http://magentohost/api/rest/products?filter[1][attribute]=name&filter[1][in]=BlackBerry%208100%20Pearl

My question is if its possible to have something like my example when searching for products?


texts: can't filter collection by custom attribute

texts:
I have a custom attribute called parent_sku, I setted it to yes in Product Listing from the backend menu, and almost all the products have a value in this attribute.

I tried:

$subCollection = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect(array('id','parent_sku'))
        ->addAttributeToFilter('parent_sku', array('eq' => $parent_sku));

I also tried (I know it is the same):

$subCollection = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect(array('id','parent_sku'))
        ->addAttributeToFilter('parent_sku', $parent_sku));

$parent_sku has a valid value, that is the same of the value that have some of the products in parent_sku attribute.

But I get always $subCollection empty.

count($subCollection)  // this is always zero


texts: How to fix 'getFirstItem does not limit the result of collection load to one item` warning?

texts:
I am validating an extension using ECG Sniffs and I get a warning 'getFirstItem does not limit the result of collection load to one item

Here is how I am trying to get default configured website.

$websites = Mage::getModel('core/website')
                    ->getCollection()
                    ->addFieldToFilter('is_default', 1);
$website = $websites->getFirstItem();

Here I try to replace $websites->getFirstItem() with $websites->getSelect()->limit() as per a suggestion but it gives another warning Data access method LIMIT detected outside of Resource Model

Can anybody please help me how to fix the warning?

P.S. I am neither magento nor PHP developer.


texts: Is it possible to stop rendering filters for some categories in Magento 2?

texts: How can I prevent/stop rendering layered navigation (filters) for some categories in product list page in Magento 2 ?


texts: Show Item Weight - Shopping Cart - Magento 2

texts: How can I show the weight for each item in the shopping cart? Is there any option to enable for that?


texts: Magento 2.0.5. Could not determine temp directory, please specify a cache_dir manually

texts:
After installing magento 2.0.5 on a webserver (allinkl.com) i am recieving following error when i try to add come products in the backend: "Could not determine temp directory, please specify a cache_dir manually"

i already looked for solutions, but without any sucess.

what i did till now:

1) changed file.php ('cache_dir'=> '/var/tmp/')
2) var/cache/ and var/tmp/ both have chmod777 recursively

also i contacted the webhost regarding this failure (in my case i can not edit php.ini), they told me to try following:

1) create "temp" folder in magento root
2) edit .htaccess: add "php_value session.save_path /www/htdocs/xxxx/domain/temp/"

But this also did not work out.

Would be great if somebody could tell me how to solve this issue.


texts: Magento removes `save_rewrites_history` from custom attribute list from REST API call

texts:
I was trying to update a product with new url-key. But create permanent redirect to the old url doesnt work from API.

First i am creating product with this JSON data http://domain.com/rest/all/V1/products

$post ='{
        "product": {
        "sku": "B501-SKU",
        "name": "B501",
        "price": 30.00,
        "status": 1,
        "type_id": "simple",
        "attribute_set_id":4,
        "weight": 1
      }
    }';

Now if i want to update the url and create a 301 redirect from old url to new url then i am hitting this http://domain.com/rest/all/V1/products/B501-SKU  (sku of the product)

    $post ='{
  "product": {
   "name": "B506",
   "customAttributes": [
        {
        "attribute_code":"meta_title",
        "value":"test"
        },
        {
        "attribute_code":"save_rewrites_history",
        "value":1
        },
        {
        "attribute_code": "url_key",
        "value": "b506"
        }
    ]
 }
}';

Now if i go to Magento\Catalog\Model\ProductRepository save() function and try to print the product object i will see that it has removed save_rewrites_history and has kept rest as is. probably because its not attribute.

A solution to the problem

1) created a new attribute and if you set the attribute value then

if($product->getData('new_attribute') == 1 && $this->areaCode->getAreaCode() == 'webapi_rest') {
        $product->setData('save_rewrites_history',1);
    }

It fixed the problem but can anyone tell me how magento refines the data before the save function? Why only attributes are getting passed.


texts:
Updating a project from 2.1.x to 2.3.  Running into an weird issue where 'compiled_config' cache won't disable.  Tried disabling via cli with

php bin/magento cache:disable compiled_config

and it will output

Changed cache status:
     compiled_config: 1 -> 0

But the cache will turn right back on.

Also tried to disable through env.php and it will turn right back on as well.

Not seeing anything related in Magento logs.  All other caches will disable.

Anyone know where to look or how to resolve this?


texts:
How can call the _isPcDev in the addManuallyArrayfunction function.
this._isPcDev or this._isPcDev() not working


texts: Magento-2.3: Multishipping Tablerates Issue

texts:
I have setup fresh Magento 2.3.2 - configured tablerates for Multi-shipping.

It seems while selecting the shipping Method its showing rates properly.

but after selection and going to next step its not showing properly,
it's showing last selected rates for every shipping address. Please Help..

  Checkout:

  Order Overview:

  Tablerates:

  Cart:

  Wrong amount in quote_address Table:


texts: Filter orders using Product Id in Magento 2 Order rest API

texts:
I am using this API "http://localhost/test/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=product_id&searchCriteria[filter_groups][0][filters][0][value]=24"
to filter orders by product id.

But getting this message

  "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_id'
  in 'where clause', query was: SELECT main_table.* FROM sales_order
  AS main_table WHERE ((product_id = '24'))".

If I am using filter on entity_id then it is working fine.I found in response that both of the fields stored at different positions.

eg. {
    "items": [
        {
            "entity_id": 1,
            "items": [
                {

                    "product_id": 14,
                }
            ]
        }
    ]
}

That's why API is not accepting "product_id" filter.
So how can a I apply filter on "product_id"


texts: Magento CE with 1M Products - dealing with Indexing

texts:
I'm operating a reseller website and have combined multiple suppliers which has resulted in a large catalog of a little over 1M product (500k+ products with 2 store views).

I've done all the usual performance tweaks, purchased a dedicated server and the site performs well with the exception of the indexes - they become invalidated daily due to inventory updates, price updates and the addition of new products that come into the feeds.

Regular indexing takes hours upon hours and pricing is not being updated properly resulting in selling a product for a loss.

I'm looking for a permanent solution to deal with this, I know it was addressed in EE 1.13

  The introduction of incremental indexing reduces the need to perform a full re-index and most indexing operations are now automated - saving you and your staff time and energy to focus on revenue-generating activities. - See more at: http://magento.com/blog/magento-news/introducing-magento-enterprise-edition-113#sthash.v6XslKCZ.dpuf

@philwinkle mentioned the following here:

  Product, URL Rewrite, and Inventory Indexing are the major issues when running a catalog this size.

There is 1 CE Edition module that I'm looking at (mirasvit Fast Asynchronous Re-indexing) but not sure if its the right way to go.

How are companies with large catalogs dealing with indexing in Magento CE? How can this problem be addressed in CE as it was in EE?


texts: How to find the block to override for the navigation menu magento 2

texts:
current setup:

Magento 2.2.4 installed with composer.

I want to replace the navigation menu with a different navigation menu (MCP Menu Creator Pro).  I think I am supposed to extend the magento/module-theme default.xml layout under the Magento_Theme folder in my  Pearl/weltpixel/Magento_Theme/

My questions are:

1) how do I find the block name of the navigation block I want to replace? when viewing the home page even with the hints turned on under Stores->Configuration->Advanced->Developer->Debug I am not able to reliably find the block I want to replace

2) I was given this block to add for Menu Creator Pro:

<block class="Magebay\Menupro\Block\Menu" name="menupro_group_1" ifconfig="menupro/setting/enable" template="Magebay_Menupro::menupro/menupro.phtml">
    <action method="setData"><name>groupmenu_id</name><value>1</value></action>
</block>

Honestly, I am not sure where to put this in the default.xml or what to wrap it with (shouldn't there be some reference that tells magento2 to use this nav menu rather than the default?).  When looking through the official magento 2.2 docs, it says that <action> is not the preferred element and one should use an <arguments> element set instead!?

Appreciate the help as I begin to understand the magento 2 structure.

note: the Weltpixel_NavigationLinks module included with the Pearl theme has been disabled by

php bin/magento module:disable WeltPixel_NavigationLinks
php bin/magento setup:upgrade


texts: Grab all input fields and email the info to admin upon new customer registration?

texts:
I'm looking for a way to grab all the filled out fields when a new customer registers and email the information to the admin. This includes some custom fields that are on the registration page.

I'm by no means an expert developer and would love a tutorial if it's even possible to accomplish this. I've yet to be able to find anything specific to what I need.

To elaborate step by step what I need:

User fills out new registration form

-->

After submit, all the data (Name, Email, Address, Custom fields)
will be emailed to the admin email.

Any ideas?


texts: Payment Method Sales/Order grid - Magento 1.9

texts:
We load the following code to show the payment method inside the Sales/Order grid.

But this displays the payment code and we want to display the payment title.

How can we change our current code to show the title?

CODE:

$select->joinLeft(array('payment' => $collection->getTable('sales/order_payment')), 'payment.parent_id=main_table.entity_id', array('payment_method' => 'method'));

CODE filterPaymentMethod:

public function filterPaymentMethod($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return $this;
    }

    $collection->getSelect()->having(
        "group_concat(`sales_flat_order_item`.sku SEPARATOR ', ') like ?", "%$value%");

    return;
}


texts: Magento 2: Data Migration From Non Magento Database to Magento Database

texts:
I already have One MySQL database which is not in Magento. I need to Map field 1 by 1 & put into Magento 2 Database.

Need to perform Data Migration from Non Magento DB to Magento 2.

There may be some extra fields attributes will be added for Product & Customer & same way some of them will be removed.

Don't think can use Magento 2 Default Admin Import.

I have below options

Export Non Magento Database in CSV & Convert it to that CSV in
Magento CSV format
Make a script which fetches data from Non
Magento Database & Put Entry in relevant Magento 2 Database Tables.

Major part is Images. Following http://docs.magento.com/m2/ce/user_guide/system/data-import-product-images.html

Customer will provide Zip folder of all images via FTP. They will provide in Product Id/SKU wise format. Need to manage that as well.

Please let me know which is the best method & how to proceed

Magento 2: Product Import Error - Product Type is invalid or not supported. Duplicates found in column names [SOLVED]


texts: Manage different stocks for different stores/store views in magento 1.9

texts:
My site has different stores(city as it is called). I want to manage the stocks for these stores.
i.e.
"Assign/manage different product quantity to each store for the same product."
or in other word (if i am interpreting correctly)
"Change magento inventory settings to store view scope instead of global(default)."

I know that we have a few paid modules available online which incorporate warehouses to solve this issue. But their prices are huge.

Could you please give me some logic to work this out.

Thank you so much in advance.


texts: Magento 2 Admin Navigation Previous & Next

texts:
In Magento 1 we use an extension that makes it easy to switch to the next order/product in Magento backend. I can't find such an module for Magento 2. Do anyone have an idea, how to implement this?
The standard way in Magento is, to go back to the order list. For order management it would be better to open the next or prevoous order.


texts: magento customer group during registration

texts:
i want to assign customer to specific customer group during , registration , how can i do it.

Bascially want to add dropdown , showing list of all available groups from which user can choose

i want to do it via modules or observer which observer should i call to do this pls help


texts: How to use region updater in custom module?

texts:
I want to use the country and region/state fields in the custom form of my custom module.

I am able to get countries list & states list of US now i want to update regions on the basis of country selected but i am not able how i can use /app/code/core/Mage/Checkout/view/frontend/js/region-updater.js here.

Thanks,


texts: Addtocart Rest api for Configurable product in magento2?

texts: Addtocart Rest api for Configurable product in magento2 ?


texts:
I need help creating module that allows to comment products. Module should add new attribute "allow commenting" with yes/no.

Products that are allowed for commenting should be displayed in a
list.
When user opens product with enabled commenting, he sees product
view with list of approved comments and a form to add new comment:
name, e-mail, and text.
All comments are shown in the Magento backend, in separate menu tab
under Vendor->Product Comments.
In admin panel there should be default buttons, like edit, delete, save, back etc. So I am stuck at database.

First of all I created module ProductComments.

Then I created InstallData.php

    <?php

namespace Magebit\ProductComments\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        /**
         * Add attributes to the eav/attribute
         */

        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'commenting',
            [
                'group' => 'General',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Allow Comments',
                'input' => 'boolean',
                'class' => '',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'global' => \Magento\Catalog\Model\Resource\Eav\Attribute::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '1',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to' => ''
            ]
        );
    }
}

And now I am thinking about the database, my idea is to create something like this, but will it be enough?

comment_id
product_id
date
email
name
comment - text
status - pending, approved, not approved


texts: getting error after change attribute input type

texts:
I have a page that I getting all products with some attributes. (room, color, size, price)

I change "Catalog Input Type for Store Owner" for room attribute on database. It was dropdown, now multiselect.

After this change the page returning null. Is anyone know why?

It's the part of code:

$room = $_POST['room'];
$collection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    //->addAttributeToFilter('color', 7)
    ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left')
    ->addAttributeToFilter('category_id', array('in' => $catID))
    ->addAttributeToFilter('size', array('in'=>$size))
    ->addAttributeToFilter('room', array('in'=>$room))
    ->addStoreFilter()
    ->setOrder('created_at', 'desc')
    ->setPage($pageNumber, $productPerPage)
    ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
    //$collection->getSelect()->order('rand()');
    //$collection->getSelect()->limit(12);
    $collection->addAttributeToFilter('price', array('gt'=>$priceL));
    $collection->addAttributeToFilter('price', array('lt'=>$priceG));

Edit: If I remove "->addAttributeToFilter('room', array('in'=>$room))" line, it's perfectly working.


texts: How to change the default rating collection in magento?

texts:
Actually we have two group of customers. Both are having ability to see different products. But in the product page at the reviews section, for both customers, for ratings they should be able to see the rating of both products compinely.

For example:

Main product sku is 'mainsku' -> it is for normal group of cutomers
then Other product sku is 'mainsku_CGG' -> it is for special group of

In both products's rating.
Customers should be able to the rating as combined and calculated percentage rating of both.

Means
mainsku->100% rating
mainsku_CGG -> 80% rating

So in product page rating should be 90% (Average of two), and number of ratings also should be get added.

I don't know how to change the ratings collection here.
Can anyone help here?


texts: move discount block below order total in checkout_index_index in sidebar

texts:
i want to move discount block below order total on one-page-checkout, like below in screenshot

I tried below code in checkout_index_index.xml but it is placing copon block in bottom
<referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="sidebar" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="summary" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="discount" xsi:type="array">
                                                    <item name="component" xsi:type="string">Magento_SalesRule/js/view/payment/discount</item>
                                                    <item name="children" xsi:type="array">
                                                        <item name="errors" xsi:type="array">
                                                            <item name="sortOrder" xsi:type="string">0</item>
                                                            <item name="component" xsi:type="string">Magento_SalesRule/js/view/payment/discount-messages</item>
                                                            <item name="displayArea" xsi:type="string">messages</item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>


texts: How to add Space between Currency Symbol and Price?

texts:
Before you put your answer I want to declare few things here we are using another currency name is Rupee (PKR) not US dollar so what i need to do to put space like this Rs. 23, i tried from admin panel to put &nbsp like this thing ahead symbol manually but from this way &nbsp is also showing on customer order emails and PDF order invoices which makes all things ugly. So there is another way to put space between this currency (Rs. ) ?? please help me to do this, so far i tried all possible ways which are described on internet but not getting success.. Please help me to fix it, it important to put space between this currency and price figures.
Thank you!


texts:
Has anyone successfully got multiple stores/storeviews running on Magento 2.3 using the URI as an identifier?

EG
https://www.example.com/ = default store/view

https://www.example.com/store2/ = second store/view

I have the essentials sorted, but the additional element in the uri appears to be interfering with the normal workings of Magento, resulting on constant 404 pages.

This is presumably because the standard convention is module/controller/action for URIs in Magento, so this setup is essentially looking for the "store2" module.

I have considered using the "add storeview to url" option, but this would result in the default being "www.example.com/default/", which the client does not want.
Logical (and typically documented) way to solve this would be to use a subdomain, but the client does not want to use "store2.example.com" format, insisting on the "www.example.com/store2/".

Any thoughts anyone?

Thanks


texts: Magento 2 server always full with cache files

texts:
Hi I am running my Magento 2.4.1 site in AWS with almost 3000 SKU but in a day it creates 40 50 GB of cache files I have correct permission website is running without any expectation error
how to control this cache problem
or how can I create Magento 2 Cron job to clear cache automatically 2 3 times I a day


texts:
I have write custom controller in magento 2 for mobile, then call this controller form mobile and pass post data, but post value not getting in controller.

What I did:

My Controller:

  <?php

  namespace Vendor\Module\Controller\Create;

  class Vendor extends \Magento\Framework\App\Action\Action
  {
      /**
       * @var \Magento\Store\Model\StoreManagerInterface
       */
      protected $storeManager;

      /**
       * @var \Magento\Customer\Model\CustomerFactory
       */
      protected $customerFactory;

      protected $addressFactory;

      /**
       * @param \Magento\Framework\App\Action\Context      $context
       * @param \Magento\Store\Model\StoreManagerInterface $storeManager
       * @param \Magento\Customer\Model\CustomerFactory    $customerFactory
       */
      public function __construct(
          \Magento\Framework\App\Action\Context $context,
          \Magento\Store\Model\StoreManagerInterface $storeManager,
          \Magento\Customer\Model\CustomerFactory $customerFactory,
          \Magento\Customer\Model\AddressFactory $addressFactory
      ) {
          $this->storeManager     = $storeManager;
          $this->customerFactory  = $customerFactory;
          $this->addressFactory = $addressFactory;

          parent::__construct(  $context);
      }

      public function execute()
      {
          $post = $this->getRequest()->getPostValue();
          echo "<pre>";
          print_r($post);

      }
  }

Call this controller form Mobile app and post form data, not getting post data form mobile app in my side.

Suggest me Why? how to call custom controller form mobile app.


texts: REST API authorization errors with POST requests only

texts:
I've set up a REST API client (using Ruby) and Magento 1.9.1 back in 2015 and it worked flawlessly.

But a few weeks ago I noticed that every once in a while a got an exception:

Integrity constraint violation: 1062 Duplicate entry ...  for key 'UNQ_OAUTH_NONCE_NONCE', the query was INSERT INTO oauth_nonce (nonce, timestamp) VALUES (?, ?)

and the request returns a 401 status.

After lots of trial and error I noticed that every time I send a POST request to the API (i.e create product, assign website, upload picture, ...) I receive that error. GET and PUT requests work without this error.

But surprisingly the requested operation is always performed successfully!

In other words, this happens:

I send the POST request.
Magento validates the Oauth parameters and stores the nonce.
Magento performes the requested operation.
Magento once again tries to check the Oauth parameters. This fails, because the nonce is already stored in the oauth_nonce table.
A get a 401 error, even if the original operation was successful.

My question: What triggers this behaviour and how can I stop it?

Additional information:

I already tried to remove the unique index in oauch_nonce. This effectively prevents the SQL error, but I get a "signature_invalid" error instead. Again, the requested operation is performed nevertheless.

The exception log just duplicates the error message already returned by the request.

UPDATE: I duplicated the Magento shop on a different machine, by simply copying the files and restoring a database dump. (i.e. no clean setup)

The error does not occur on the different machine. I'm suspecting  that this problem might have an external cause. Perhaps an unfortunate combination of PHP/Apache/Magento/configuration files.


texts: Show select options values on condition in magento 2 admin grid

texts:
I am creating a module where I am listing a custom table, in admin area. I have a status field in the database. What I want is to disable/remove some of the select option from the status field,when user try to edit, based on the condition.
This is my column which shows status:
    <column name="Sub_Status" component="Magento_Ui/js/grid/columns/select">
            <settings>
                <options class="vendor\module\Model\Status\Source\Status" />
                <editor>
                    <editorType>select</editorType>
                </editor>
                <dataType>select</dataType>
                <label translate="true">Status</label>
            </settings>
      </column>

I tried to manipulate data on the related class Status.php
<?php

namespace vendor\module\Model\Status\Source;

use Magento\Framework\Data\OptionSourceInterface;

class Status implements OptionSourceInterface
{
    protected $status;
    //Here you can __construct Model

    public function toOptionArray()
    {
        $result1 = //has all the db records;
        $currentDate = date("m-d-Y");
        for($i=0;$i<count($result1);$i++){
            $subsOrderDate=$result1[$i]['Subcription_Order_Date'];
            $subsOrderSKU=$result1[$i]['Sub_Sku'];
            $check = 'false';
            if($subsOrderDate<$currentDate){
                $check = 'true';
            }
            switch($check){
                case 'true':
                    $result[] = ['value' => 4, 'label' => __('Pending')];
                    break;
                case 'false':
                    $result[] = ['value' => 3, 'label' => __('On Hold')];
                    break;

                default:
                    $result[] = [
                        ['value' => 0, 'label' => __('Cancelled')],
                        ['value' => 1, 'label' => __('Original Order')],
                        ['value' => 2, 'label' => __('Payment Failed')],
                        ['value' => 3, 'label' => __('On Hold')],
                        ['value' => 4, 'label' => __('Pending')]
                    ];
            }
        }
return $result;
}
}

But no luck..How can i achieve this. please help.


texts:
I've just started working at a logistics company and some of our new clients uses the Magento platform.

I've been looking through the API documentation in search of instructions on how to offer shipping quotes, receive orders etc, but I was unable to find it.

Can someone point me to the link in which I can find such documentation?


texts: Magento 2 - Add button to the Header links

texts:
I am trying to add a button called "social media" to be beside the Storeview switcher.
I tried to follow the answer in: Magento 2 - Add a Custom Button to header.phtml
So I  created a CMS block on the backend called 'social media' with id 'social_media'.
I also add the following to the:
app/design/frontend/Smartwave/porto/Smartwave_Porto/layout/default.xml file:
<referenceBlock name="header.links">
    <block class="Magento\Cms\Block\Block" name="social.media" before="-">
        <arguments>
            <argument name="block_id" xsi:type="string">social_media</argument>
        </arguments>
    </block>
</referenceBlock>

However, it didn't work.
So my question: what is the right way to add such a button to the header links in magento 2.3.5 ?


texts: How to filter Product Grid based on custom attribute?

texts:
I have a custom product attribute soldby which is a dropdown attribute.

I am making a custom product grid. In that grid, I want to display products where soldby=abc.

I have written the following code in Grid.php.

prepareCollection()

$collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('soldby');
$collection->addFieldToFilter(array(
    array('attribute'=>'soldby','eq'=>'abc'),
));

But this doesnot work. Now, no products are shown even though there are products with attribute soldby=abc.

How can I achieve this ?


texts: Apply Catalogue price rules from Cron command

texts:
I have this problem with my customers not getting specials between midnight and 1AM. Basically whatever they add to their cart during this hour would be regular price. Yesterday I decided to check out the issue and tried it at 00:01AM and Reapplied the rules and then the issue was solved. My question: is there a way to apply catalogue price rule ( I would do it at 00:01) from my cron command on my cpanel? I am on magento CE 1.9.3.7. I am also using the original RWD theme.
I just checked with siteground and their server is in Chicago. We are in Quebec and the time difference is exactly one hour slower in Chicago. Therefore I guess the catalog rule is applying at the right time (midnight) but in Chicago time.
Does this have anything to do with my issue?


texts: Magento 2.3.5-p1 - Elasticsearch index not found

texts:
Our Magento website has a number of stores:

When I run bin/magento indexer:reindex catalogsearch_fulltext it times out after about 4-5 hours and never completes.  Here is what I can see when I run /_cat/indices?v

So if I'm understanding this correctly, should there be a magento2_product_x_vx for every store? It looks like it's reindexed store1 9 times and store4 only ever gets to 65000 / 94324.  Stores 5, 6 and 7 don't exist and that would explain this error in the log:
Elasticsearch index not found. Run "bin/magento indexer:reindex catalogsearch_fulltext".

Is the issue that there are 2 magento_product_3 versions?
I'm clueless when it comes to Elasticsearch so any help interpreting the Elasticsearch output is greatly appreciated.


texts: How to make drop-down dependent on another drop-down value in admin ui component Magento 2

texts:
I want to update one drop-down option on the change of another drop-down using UI Component in Magento admin section.

Like: have one drop-down with color option ex: Red, Pink, Black, etc. and another drop-down has a size value which depends on color.

How can I dynamically update size option on the change of color using
UI component in Magento admin?


texts: Update order status after updating order shipping address using plugin in Magento 2

texts:
I am trying to update the order status after the shipping address was changed manually from the adminpanel (when the order is already created).

This is my di.xml content:

<type name="Magento\Sales\Model\Order\AddressRepository">
    <plugin name="custom_order_status" type="Vendor\Module\Plugin\OrderAddressAfterSave" sortOrder="1" disabled="false" />
</type>

and the OrderAddressAfterSave content:

    use Magento\Sales\Api\Data\OrderAddressInterface;

    class OrderAddressAfterSave
    {
        public function afterSave(OrderAddressInterface $subject, $result)
        {
            return $result;

        }
    }

If the order status is shipping_error and someone updates the shipping address from adminpanel, I would like to update the order status from shipping_error to processing.

Currently I am running into this error:

Fatal error: Uncaught TypeError: Argument 1 passed to Vendor\Module\Plugin\OrderAddressAfterSave::afterSave() must implement interface Magento\Sales\Api\Data\OrderAddressInterface, instance of Magento\Sales\Model\Order\AddressRepository\Interceptor given, called in path/to/vendor/magento/framework/Interception/Interceptor.php on line 146 and defined in path/to/app/code/Vendor/Module/Plugin/OrderAddressAfterSave.php:8 Stack trace: #0 path/to/vendor/magento/framework/Interception/Interceptor.php(146): Vendor\Module\Plugin\OrderAddressAfterSave->afterSave(Object(Magento\Sales\Model\Order\AddressRepository\Interceptor), Object(Magento\Sales\Model\Order\Address), Object(Magento\Sales\Model\Order\Address)) #1 path/to/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Sales\Model\Order\AddressRepository\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Sales\Model\Ord in /path/to/app/code/Vendor/Module/Plugin/OrderAddressAfterSave.php on line 8

Any idea why? and what would be the best approach to fix this ? Thank you


texts: How to get the attributes of the selected products

texts:
I'm new to Magento. Could you please spare few minutes to help me out?

I have added a new button in Catalog->Manage Products Grid.

When i select few products in the Product List and click my new button, i need to get all the attributes (Price, Product ID, SKU, status, etc,..) for the selected (check box selected) products.

And how to iterate through the list ?
Could you please help me with the above.

Thanks


texts: Magento 2 How Generate Unique Widget phtml Class Names

texts:
I have developed a widget. It has a block class which sets the front-end template. I have this function which generate unique class names.

public function getClassName()
{
    $class = "mywidget-widget-" . md5(uniqid("mywidget-widget"));
    return $class;
}

When I call that function on the front-end phtml file for multiple widgets of the same type, it always returns the first unique key to be generated. Why does this happen?

$block->getClassName()


texts: Applying a coupon code to an existing order - (without cancelling)

texts:
I have a customer that has ordered a product that isn't ready to ship. To compensate the customer, I'd like to offer a discount by applying a coupon code on their pending order.

I'm aware that I can cancel the order and then apply the discount, but since this is a credit card transaction, I do not want to cancel the order or obligate the customer to "checkout" for a second time.

How can a discount be applied to an existing order ? (without cancelling)


texts:
After creating a new theme in app\design\frontend\ appears in my back end under design.

When I change it to my custom theme, CSS or JS is NOT loading.

I tried running the following command:

php bin/magento setup:static-content:deploy

Deleted var\cache, var\generation, pub\static\ - but no luck

However my default theme from fresh installations works just fine. I don't think there is any permission issue otherwise my default would not work. is there anything I am missing?


texts: Magento 2: How to remove category sidebar from the pages?

texts:
Yesterday I had applied porto theme after that category sidebar is coming for every category page and product page.
In Category page it is coming in left side and product page coming in right side.
For reference please find the images and website
https://vitalticks.in


texts: Modifying layout in custompackage/customtheme tutorial

texts:
I am new to Magento and have successfully completed the tutorial at http://www.magentocommerce.com/knowledge-base/entry/ee114-ce19-rwd-dev-guide.
I'd like to start modifying the layout, specifically (to start) new.phtml to
put up a list of courses instead of the standard pictures of products.  (Our
customer sells training courses not the standard products).  Could someone please
point me to another tutorial that explains exactly how to do this or, if the
answer is fairly short, a description of the steps to take would be greatly
appreciated.


texts: Uncaught Error: Call to a member function getSomething() on null in phtml ViewModel magento2

texts:
I have created a ViewModel, when I am calling it in the phtml it giving me the below error
Fatal error: Uncaught Error: Call to a member function getSomething() on null in Magento_Catalog/templates/product/list/items.phtml:16 Stack trace: #0
here is my catalog_product_view.xml
<block name="product.info.upsell.customviewmodel"
                   class="Magento\Framework\View\Element\Template"
                   template="Magento_Catalog::product/list/items.phtml">
                <arguments>
                        <argument name="view_model" xsi:type="object">Noshad\VMpractice\ViewModel\PreparePostData</argument>
                    </arguments>
            </block>

here is my ViewModel class
<?php

namespace Noshad\VMpractice\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;

class PreparePostData implements ArgumentInterface
{

    public function getSomething()
    {
        echo 'find me';
    }

}

here are my items.phtml code
/* @var Noshad\VMpractice\ViewModel\PreparePostData $viewModel */

$viewModel =  $block->getData('view_model');

echo $viewModel->getSomething();

whenever I load the product detail page I gets the below error:
Fatal error: Uncaught Error: Call to a member function getSomething() on null in /var/www/html/practice234/app/design/frontend/Smartwave/porto_child/Magento_Catalog/templates/product/list/items.phtml:16 Stack trace: #0


texts: Calling Third Party Extension Function in other Pages

texts:
I have a third party extension on Magento 1.9 which has the phtml file to display list of favorite brands for the logged in user. It the phtml file of this extension, it does the following to get the list:

$_helper = $this->helper('personalize');
$FavBrands= $this->getBrands();
$count = count($FavBrands);

I want to be able to call the above in other places around the store. I see from above code, it uses ($this). What does it mean, and what change should I do from above to be able to call it getBrands() in for instance (product page).

Note that I am not looking to immediatly insert the block of the third party extension into other pages. I want to reuse their functions to do other things.


texts: Allow filter by all attributes even if product does not exist in current category

texts:
More of a conceptual questions really.

Is there anyway to display and allow filter by all available attributes in every category. For example; in the shoes category, show and allow filter by the 't-shirt' attribute, even though no 't-shirt' products exist in shoes category.

I presume this is not possible unless all products existed in all categories? Which would presumably be an issue for SEO anyway?

I've had a client ask this question and wanted to make sure it wasn't possible before I tell them as much.


texts:
I try render input field in my custom form element like

<render args="ui/form/element/input"/>

but then i get some js errors because elem userChanges and others dont exist(see https://github.com/magento/magento2/blob/2.3-develop/app/code/Magento/Ui/view/base/web/templates/form/element/input.html), how can i bind js component to render template, or how can i use form element inside another form element?


texts:
I'm trying to get all tax rates I set up in my store my custom plugin, I'm using Magento 2.

I found that in db all tax rates are stored in tax_calculation_rate, but I didn't find a method to get all data from this.

Thank you for any help


texts: magento: change sender in reply contact form to customers email address

texts:
When I try to respond to a contact form on my web, although I have configured to send to info@XXXX.com , the sends him something like this:

Example:

----- Mensaje original -----
Desde: klooster@vps34324.xlshosting.net [mailto: klooster@vps34324.xlshosting.net] En nombre Comservices
Enviado el: DATE
Para: info
Asunto: Contact web

Nombre:XXXX XXXX
Correo electrónico: X.XXXX@gmail.com
Teléfono: 066-6666666

This is how magento sent to info@mywebsite.com the email of contact.
How can i change the from of the email?

edit: The objetive is that my email have the From: info@mywebsite.com


texts: Same Root Category (Default) shows on two different websites

texts:
There are two URLs where I want to run my Magento Store with same Magento Installation:
1. http://www.antistaticesd.com
2. http://www.antistaticesd.com/business

First of all, I created a directory name business under my root on my FTP server:

Then, I created another website in the Magento back end, another store and another store view. Therefore there are two each:

WEBSITE: main website (Code: base)
MAIN WEBSITE STORE: (Root Category: Default Category)
DEFAULT STORE VIEW: (Code: default)

WEBSITE: Business Website (Code: business)
MAIN WEBSITE STORE: (Root Category: Business Store)
DEFAULT STORE VIEW: (Code: business_store_view)

This is the code I added to the .htaccess file in "business directory":

SetEnvIf Host .*base.* MAGE_RUN_CODE="base";
SetEnvIf Host .*magento_site_2.* MAGE_RUN_TYPE="business";

The file other than .htaccess is the index.php that I copied from root folder(public_html) to "business" directory.

THE PROBLEM IS AS FOLLOWS:


texts: Magento2: How to filter collection by created_time from custom table in admin grid

texts:
I need to filter custom table collection in admin grid. I'm struggling with this.
Please suggest for this.

Here is my code

namespace Abc\Mkt\Model\ResourceModel\Logs;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection {
    protected function _construct()
    {
        $this->_init(
        'Abc\Mkt\Model\Logs',
        'Abc\Mkt\Model\ResourceModel\Logs'  );
    }
}

di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <virtualType name="AbcMktGridFilterPool" type="Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool">
        <arguments>
            <argument name="appliers" xsi:type="array">
                <item name="regular" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
                <item name="fulltext" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter</item>
            </argument>
        </arguments>
    </virtualType>
    <virtualType name="AbcMktGridDataProvider" type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
        <arguments>
            <argument name="collection" xsi:type="object" shared="false">Abc\Mkt\Model\ResourceModel\Logs\Collection</argument>
            <argument name="filterPool" xsi:type="object" shared="false">AbcMktGridFilterPool</argument>
        </arguments>
    </virtualType>
    <virtualType name="Abc\Mkt\Model\ResourceModel\Logs\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
        <arguments>
            <argument name="mainTable" xsi:type="string">abc_error_logs</argument>
            <argument name="resourceModel" xsi:type="string">Abc\Mkt\Model\ResourceModel\Logs</argument>
        </arguments>
    </virtualType>
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="grazitti_mkt_index_listing_data_source" xsi:type="string">Abc\Mkt\Model\ResourceModel\Logs\Grid\Collection</item>
            </argument>
        </arguments>
    </type>
    <type name="Magento\Framework\Notification\MessageList">
        <arguments>
            <argument name="messages" xsi:type="array">
                <item name="ExpiryAlert" xsi:type="string">Abc\Mkt\Model\System\Message\ExpiryAlert</item>
            </argument>
        </arguments>
    </type>
</config>

Thanks


texts: Magento Category Url error: SQLSTATE[08004] [1040] Too many connections

texts:
Getting following error on one of my category url, need help. How do I fix this

Magento Commerce
    There has been an error processing your request
    SQLSTATE[08004] [1040] Too many connections

Trace:
#0 /home/public_html/includes/src/__default.php(56407): Zend_Db_Adapter_Pdo_Abstract->_connect()
#1 /home/public_html/includes/src/__default.php(56963): Zend_Db_Adapter_Pdo_Mysql->_connect()
#2 /home/public_html/includes/src/__default.php(55076): Varien_Db_Adapter_Pdo_Mysql->_connect()
#3 /home/public_html/includes/src/__default.php(56133): Zend_Db_Adapter_Abstract->query('SET NAMES utf8', Array)
#4 /home/public_html/includes/src/__default.php(57071): Zend_Db_Adapter_Pdo_Abstract->query('SET NAMES utf8', Array)
#5 /home/public_html/includes/src/__default.php(30817): Varien_Db_Adapter_Pdo_Mysql->query('SET NAMES utf8')
#6 /home/public_html/includes/src/__default.php(30748): Mage_Core_Model_Resource->_newConnection('pdo_mysql', Object(Mage_Core_Model_Config_Element))
#7 /home/public_html/includes/src/Mage_Core_Model_Resource_Setup.php(141): Mage_Core_Model_Resource->getConnection('core_setup')
#8 /home/public_html/includes/src/Mage_Core_Model_Resource_Setup.php(234): Mage_Core_Model_Resource_Setup->__construct('core_setup')
#9 /home/public_html/includes/src/__default.php(21370): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#10 /home/public_html/includes/src/__default.php(21296): Mage_Core_Model_App->_initModules()
#11 /home/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#12 /home/public_html/index.php(83): Mage::run('', 'store')
#13 {main}

Error log record number: 1120556696777

Magento is a trademark of Magento Inc. Copyright © 2017 Magento Inc.


texts: how to load customer/group into Mage_Catalog_Model_Product_Type_Price

texts:
I have changed the price scheme based on customer group by percentage. So here I do the trick for the product

if ($group->getCode() == "High ST. Shops") {

    $percent = 100 - $_product->getHighstshopPerc();
    $percent = "0." . $percent;
    $srrp = $_product->getPrice() * $percent;
    echo "Your Price £" . number_format($srrp, 2, '.', '');
}

Now I need getPrice() to come from price.php already with my new scheme so it adds to cart correctly. I tried the code below but i cant get getCode() to give me customer group so I can calculate/override getPrice

public function getPrice($product)
{
//$groupId    = Mage::getSingleton('customer/session')->getCustomerGroupId();
//$group      = Mage::getModel('customer/group')->load($groupId);

    //return $product->getData('price');
    //return $product->getTradePerc();
    //echo $product->getCode(); exit();
    if ($product->getCode() == "NOT LOGGED IN")
    return 1;
    else return 2;
}


texts: How can i insert values in custom table in Magento 2?

texts: I have created a custom table name as "my_topic" using InstallSchema now i want to insert data in this table. How can i do this please suggest your answers.


texts:
I Have two tax rates defined

Tax Identifier    Counry  state  postcode rate

Can-QC-PS        Canada   QC     *   9.975

Can-QC-GST   Canada   QC     *   5.00

$this->item('tax_percent') will result 14.975
But i want to display individually 9.975% and 5% in the front end

Please help me.


texts: How to limit text field length in Magento

texts:
How to set field limit using addAttribute function. I have:

$this->addAttribute(Mage_Catalog_Model_Product::ENTITY, 'magazine_test', array(
   'input'         => 'text',
   'type'          => 'text',
   'label'         => 'Test',
   'backend'       => '',
   'visible'       => true,
   'required'      => false,
   'user_defined'  => true,
   'visible_on_front' => true,
   'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,

));

Is there way to write: 'length' => 10


texts:
I added two button in order view it's working fine but i want to disable this button if order is complete and order is canceled time

My Abstract file

public function addOrderstatusAction($observer)
    {
        $block = $observer->getEvent()->getBlock();
        if ($block instanceof Mage_Adminhtml_Block_Sales_Order_View) {

            $message = Mage::helper('sales')->__('Are you sure you want to Change Status?');

            $block->addButton('rto',
                array( 'label' => Mage::helper('sales')->__('RTO'),
                    'onclick' => "confirmSetLocation('{$message}', '{$block->getUrl('orderstatus/adminhtml_index/rto')}')", 'class' => 'go' ));

           $block->addButton('in_shipment',
            array( 'label' => Mage::helper('sales')->__('In Shipement'),
                'onclick' => "confirmSetLocation('{$message}', '{$block->getUrl('orderstatus/adminhtml_index/in_shipment')}')", 'class' => 'go' ));
        }

    }


texts: How can I include product description in Magento order email?

texts:
I'm pretty new to Magento, so I ask if anyone of you has ever tried to include the product description in the order transactional email.

Is there a way to do it? I've Magento CE 1.9.2.4


texts: Load the cms content based on theme in cms editor

texts:
I have two different themes one for desktop and one for mobile. I added about-us page content in cms pages. Its working fine in desktop.

Now, the html is different for mobile theme. So, how can I place mobile theme code in the same editor? The content should load based on theme. How can I get frontend theme and write conditions in cms editor.

ex: if(theme = "desktop") {
    desktop about us page should render
} else {
    mobile about us page should render
}


texts:
I would like to use translations from my own extension. I've created helper and translation file in different locales. But Magento shown me translation from Mage_ locale
There is my code:

<global>
    <helpers>
        <myextension_base>
            <class>Myextension_Base_Helper</class>
        </myextension_base>
    </helpers>

under global in config.xml

<frontend>
    <translate>
        <modules>
            <Myextension_Base>
                <files>
                    <default>Myextension_Base.csv</default>
                </files>
            </Myextension_Base>
        </modules>
    </translate>
</frontend>

in template Mage::helper('myextension_base')->__('Cart')

I've created files in en_US and de_DE

Where I do something wrong?

UPD Looks like Mage_ translations has priority or my translation placed after Mage_ translations


texts: noNamespaceSchemaLocation full directory path vs urn

texts:
I'm trying to get into good habits off the bat with Magento 2. module development but I've come across something I can't find any writing on. Though this is probably as I'm unsure what to search for.

I've seen a lot of examples of Magento 2 modules with the following style syntax in their XML files

<config ... xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">

But I've been looking at the Magento github sample modules and they use the following style of noNamespaceSchemaLocation

<config ... xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

Both work but the code from the github repo seems a lot cleaner. Is there a reason for the 2 available methods? if one better than the other?