texts: Magento 1.9: Sort product listing first by "Manufacturer" then by "Name"

texts:
I got a question where I want to sort the product listings in category pages sorted by manufacturer by default then I would like it to be alphabetically by name.

Example:

Products list (Sorted by Manufacturer) - this is working

Product G     Product Z     Product A   Product R   Product Ab

Where it should be:

Products list (Sorted by Manufacturer) - this is working

Product A     Product Ab     Product G   Product R   Product Z

Same issue but it's not working for me: https://stackoverflow.com/questions/4167173/magento-sort-by-position-and-name

Regards


texts:
I noticed that my database size has been increasing a lot since moving over to Magento 2.
Looking at the table sizes, it all seems to be relating back to quotes. The largest tables are:

quote_address
quote
quote_id_mask

There appear to be a lot of empty rows being created with no items or totals.
Are there any known issues with empty quotes being created? Or, can anyone suggest where to start debugging this?
I would also like to purge empty quotes, but stopping them being created is the first priority.
Thanks in advance.


texts: Magento “Sort By filter ” is not displaying correct information

texts:
Magento My Sort By filter is not displaying correct information for example

My Sort By “sale” is bringing up items that aren’t on sale. Any idea?

Do I have to have a start and end date on each for them to work?


texts: Get User Details by Access Token From Admin

texts:
I have two servers which are written in yii2 and magento respectively. The yii2 application has file module and magento has commerce and user module. the current problem is whenever user needs to upload the file to yii2, user only sends the access token. How do i retrieve user details (id) from the magento using only access token?

Thanks


texts: Billdesk payment gateway integration in magento

texts:
I'm planning to integrate billdesk payment gateway in one of our magento projects does billdesk provide any module to integrate it?
We donot have much time to build it, are there any free modules?.


texts: Magento 2 : How to remove block from controller?

texts:
I've been trying to remove block from controller.

I can able to render from controller but i need to remove existing layout block when new one render.

  Vendor\Module\Controller\Grouprequest.php

<?php
 public function execute()
{
   $layout = $this->_view->loadLayout();
       $resultPage = $this->_resultPageFactory->create();
        $block = $resultPage->getLayout()
            ->createBlock('Inchoo\Helloworld\Block\AcceptedGroupRequest')
            ->setTemplate('Inchoo_Helloworld::acceptedGroupRequest.phtml')
            ->toHtml();
            $this->getResponse()->appendBody($block);
     }

Need to remove grouprequest block. Which is rendered when this controller executed.

Thanks in advance.


texts: How to add custom validation to checkout phone field

texts:
I have checkout_index_index.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="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="steps" xsi:type="array">
                                <item name="children" xsi:type="array">
                                    <item name="billing-step" xsi:type="array">
                                        <item name="component" xsi:type="string">uiComponent</item>
                                        <item name="children" xsi:type="array">
                                            <item name="payment" xsi:type="array">
                                                <item name="children" xsi:type="array">
                                                    <item name="payments-list" xsi:type="array">
                                                        <item name="children" xsi:type="array">
                                                            <item name="magedelight_cybersource-form" xsi:type="array" >
                                                                <item name="children" xsi:type="array">
                                                                    <item name="form-fields" xsi:type="array">
                                                                        <item name="children" xsi:type="array">
                                                                            <item name="telephone" xsi:type="array">
                                                                                <!--<item name="validation" xsi:type="array">-->
                                                                                <!--<item name="customPhoneValidation" xsi:type="string">true</item>-->
                                                                                <!--</item>-->
                                                                            </item>
                                                                        </item>
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </item>
            </argument>
        </arguments>
    </referenceBlock>
</body>

How to add custom validation to checkout phone fild?
I added the HTML file in this way
requirejs-config.js

map: {
    "*": {
        customPhoneValidation: "Tupperware_Party/js/model/customPhoneValidation"
    }
}

customPhoneValidation.js

requirejs([
'jquery',
'jquery/ui',
'jquery/validate',
'mage/translate'], function($){
'use strict';
$.validator.addMethod(
    "customPhoneValidation",
    function(value, element) {
        /*logic*/
        return false;
    },
    $.mage.__("Your validation message")
);

});

in form

<form data-mage-init='{"customPhoneValidation":{}}'>


texts: Magento2: Recoverable Error: Argument 1 passed to ::__construct() must implement interface

texts:
I am trying to make a shipping method based on percentage. Can someone explain to me whats wrong with the following?

I get this error message:

main.CRITICAL: Recoverable Error: Argument 1 passed to XXX\ShippingPercentage\Model\Carrier\opPercentage::__construct() must implement interface Magento\Framework\App\Config\ScopeConfigInterface, instance of Magento\Framework\ObjectManager\ObjectManager given, called in /vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in /app/code/XXX/ShippingPercentage/Model/Carrier/opPercentage.php on line 25 [] []

I think its connected to adding quoteFactory as someone mentioned this. However, it's probably in the wrong place. Can someone explain to me how to not get this problem the next time?

<?php
namespace XXX\ShippingPercentage\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;
use Magento\Quote\Model\QuoteFactory;

class opPercentage extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
\Magento\Shipping\Model\Carrier\CarrierInterface
{
/**
 * @var string
 */
protected $_code = 'oppercentage';

/**
 * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
 * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
 * @param \Psr\Log\LoggerInterface $logger
 * @param \Magento\Quote\Model\QuoteFactory $quoteFactory
 * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
 * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
 * @param array $data
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Quote\Model\QuoteFactory $quoteFactory,
    \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
    \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
    array $data = []
) {
    $this->quoteFactory = $quoteFactory;
    $this->_rateResultFactory = $rateResultFactory;
    $this->_rateMethodFactory = $rateMethodFactory;
    parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
}


texts: Get customer account details for invoice PDF

texts:
I need to get the account details of a registered customer and use them in the invoice PDF. The customer belongs to customer group "testgroup". By using the order details I can get the customer group and check if the customer belongs to "testgroup".

How do I get the customer ID and the rest of the account details?


texts: How to tell whether Magento 2 site is EE or CE

texts:
What is the easiest/fastest way to check if a Magento 2 site is on EE or CE?

Preferably via the admin if possible.


texts: Column 'increment_id' in where clause is ambiguous when adding a new column to orders grid

texts:
I'm trying to add a new column to orders grid; shipping_description in sales_order table, i can use instead, shipping_information in sales_order_grid (main table).
Here is my code
protected function _renderFiltersBefore()
{
    $joinTable = $this->getTable('sales_order');
    $joinTable_track = $this->getTable('sales_shipment_track');
    $this->getSelect()->joinLeft($joinTable, 'main_table.entity_id = sales_order.entity_id', ['shipping_description']);
    $this->getSelect()->joinLeft($joinTable_track, 'main_table.entity_id = sales_shipment_track.order_id', ['track_number']);
    parent::_renderFiltersBefore();
}

Is it possible to use shipping_information from sales_order_grid table without making a join?
Cause i'm getting this error
Integrity constraint violation: 1052 Column 'increment_id' in where clause is ambiguous, query was: SELECT COUNT(*) FROM `sales_order_grid` AS `main_table`

I added this function
protected function _initSelect()  {

  $this->addFilterToMap('increment_id', 'main_table.increment_id');
  $this->addFilterToMap('status', 'main_table.status');
  parent::_initSelect();
  return $this;

}

This fixed the issue but i don't like to add filter to map to all the fields.


texts: How to apply free shipping method for specific country?

texts:
I wants to make shpping free in country A and in country B I want to make free shipping above 1000 USD.

I had tried with shopping cart rules, but I am not getting better solution for this conditions.

Thanks in advanced,


texts: About Product Quantity drop down And add to cart button

texts:
Hi I would like to have two Add to cart buttons which add specified quantities for my products and remove the input field i want quantity drop down instead of this.

=

I'd like

One for Order Sample button for which by default quantity select 1.
And other for bulk order for which quantiy start from 25,50,75,100,125....and so on.
Wondering on the best way to do this, I would also like to implement this on the product view page

Thanks


texts: How to cache a product collection in Magento 2?

texts:
Currently i load a product collection under certain categories, for example:
$collection->addCategoriesFilter(array('in' => array('2','4')));
$collection
            ->addMinimalPrice()
            ->addFinalPrice();
        $collection->addFieldToFilter('e.attribute_set_id', $attributeSetId);
        $collection->getSelect()->where('e.attribute_set_id = "'.$attributeSetId.'" AND final_price > 0');

the problem with this collection, that it will  query like 3000++ product data, can i cache this collection ?


texts:
i've successfully create a top menu in magento 2 like this:

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
        <add id="Test::top_level" module="Namespace_Module" resource="Magento_Backend::content" sortOrder="40" title="Test"/>
    </menu>
</config>

the default menu image is octagon, how can i add my own image as my new top menu image


texts: Magento 2 change number of items per row

texts: I'm using Magento 2 with a custom theme , and I'm trying to change the number of items per row in the catalog. Now I'm having 3 items per row , and I'm trying to get 4.. what's the right file to edit to change that , as I have already changed from the admin panel - configuration - catalog - Products per page on list allowed to 6,12,16,22,26 , but there are still 3..


texts: Magento 2: How to avoid objectManager in Model?

texts:
I have achieved

Magento 2: How to change Weight field for DHL Shipping Method [SOLVED]

I tried to put

protected $_product;

public function __construct(\Magento\Catalog\Model\Product $product) {
    $this->_product = $product;
}

public function _getAllItems() {

    $allItems = $this->_request->getAllItems();
    $fullItems = [];

    foreach ($allItems as $item) {
        $this->_product->load($item->getProduct()->getId());
        $itemWeight =  $_product->getData('weight_with_package');
    }
}

It's not working :(


texts: Suggestion for setup of Multiple Store on Magento with a huge catalog

texts:
We want to start a new website on magento which will have 50+ addon domains setup each running a website and common products across all the websites.

It will contain more than 2 Lakhs of SKUs and  around about 8K categories.

Each website will be at separate domain and will be created on the same admin panel.

We need your suggestion for the below kind of development of magento about
Server Requirements
Problems may be faced
Space requirements and
What will be the optium solution.


texts: Update Minicart programatically in magento 2

texts:
I have create problematically adding number of products at a time in Magento 2 cart and there I can one see one first product in mini cart other products are also in mini-cart but not showing the count and price

here is the code that i tried to update mini-cart

  app/code/Multiple/Addtocart/etc/module.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Multiple_Addtocart" setup_version="2.1.1">
   </module>
   </config>

  app/code/Multiple/Addtocart/view/frontend/layout/default.xml

page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template" name="refresh.minicart" template="Multiple_Addtocart::refreshMinicart.phtml"  />
    </referenceContainer>
  </body>
</page>

  app/code/Multiple/Addtocart/view/frontend/templates/refreshMinicart.phtml

<?php
?>
<script>
  require([
    'Magento_Customer/js/customer-data'
  ], function (customerData) {
    var sections = ['cart'];
    customerData.invalidate(sections);
  });
</script>

But here i'm getting object not created error


texts:
the error code is :
Class Magento\Downloadable\Api\Data\SampleInterfaceFactory does not exist
I add the product, when I submit and save the product. I test it for many days, it still this error, does I configure it wrong?
the Class of the SampleInterface Factory does not exist?
who can give me the code on how to solve this error?


texts: Google Trusted Store Test Drive shows the error as - Javascript is not implemented on the page

texts:
We have used http://www.magentocommerce.com/magento-connect/google-trusted-stores.html to integrate Google Trusted Store with Magento 1.8.  While Test Drive shows the error as

Javascript is not implemented on the page
How to Fix: Implement the JavaScript code on this page of your website.

How to solve this error?


texts: Importing from Custom E-Commerce Platform to Magento 2 (MySQL to M2)

texts:
I need to import Products, Customers and Order History from a custom e-commerce platform into a new Magento 2 implementation. Ideally the extension or cloud service would allow us to connect directly to MySQL (source) on the custom platform and sync all products, customers and order history with Magento v2.3 (destination).

I've looked into Skyvia and FireBearStudio Improved Import which appear to offer the features closest to what I need. FireBearStudio hasn't officially released their direct MySQL support yet, so right now that doesn't seem to be a viable option.

If you have any personal knowledge of any other options that might fit my requirements, please let me know? Also, I would be interested in learning about your personal experience with Skyvia and FireBearStudio.


texts: How to add Custom JS and CSS file in Magento 2

texts: I want to add a JS and CSS file for my theme. How would i do that.


texts: Magento 2.4.1 Layered navigation with custom product collection

texts:
I want to override category product collection on the category product page in front-end. I want to show collection according to attribute set. After customize collection layered navigation product count is not updating.
I am using plugin for modified default category product collection. I am using getProductCollection(). After plugin category product collection filtered by attribute set id but layered navigation is still showing same count. The custom condition is not applied on the layered navigation
Here is my code:
app/code/Sunarc/ProductListpage/etc/frontend/di.xml
<type name="Magento\Catalog\Model\Layer">
    <plugin name="seedolabs-catalog-layer-model" type="Sunarc\ProductListPage\Plugin\Model\Layer"/>
</type>

app/code/Sunarc/ProductListpage/Plugin/Model/Layer.php
 public function afterGetProductCollection(\Magento\Catalog\Model\Layer $subject, $result){ $result->addAttributeToFilter('attribute_set_id',['eq'=>9]);
return $result;}

kindly help me
Screenshot for issue


texts:
I want to display list of country in my system.xml

<field id="country" translate="label" type="text" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Countries</label>
</field>

How we do this?


texts: Can't change the applied theme in 2.2.4 from admin

texts:
Here is a known bug in 2.2.4 version.

When you try to apply theme from backend content -> Design -> Configuration:

Appears the error: "Something went wrong while saving this configuration: Area is already set"

It will be fix in 2.2.5 version by magento guys.

Meanwhile here the solution:

You can refer this link from github they given solution to solve for 2.2.4 version.

https://github.com/magento/magento2/issues/14968#event-1630525002

Or change the core files from here they commited on github:

https://github.com/magento/magento2/commit/0ae1230c4bbe985f66929ed234835137e64664c9
https://github.com/magento/magento2/commit/3df51d4c294dda946d78ba25b9aef693cb813a0a
https://github.com/magento/magento2/commit/0dec988872e175e568c2bf4bb29548ab7a4698e5
https://github.com/magento/magento2/commit/d92b679e48da825813bfaff51e631236a2bbc73a

This will fix the issue.


texts: Setting a custom product option for a simple product in the cart

texts:
I have a simple product with a custom product option defined as a text field in the backend.

After adding the simple product to the cart, with no value set for the custom product option, I'd like to programmatically set the custom product option on the quote item.

It's important that the custom product option is stored exactly the same way as if it was added manually by the user on the product page, before adding the product to the cart.


texts: How do I change date picker format for admin date field

texts:
How can I change the date format to display as dd/mm/yyyy for admin date field?

Currently it is displaying as mm/dd/yyyy format. Can you please help me out?


texts: How can i send Company logo in custom email templates

texts:
how can i send company logo in custom email templates ?
 I know that it is placed on header.html
in vendor/magento/module-email/view/frontend/email


texts: Is the Authorize.net payment model in 1.7.0.2 compatible with post-Poodle changes?

texts: I recently received a notification that Authorize.net will no longer support SSL3 due to the Poodle vulnerability. I would assume that a version of Magento as new as 1.7.0.2 doesn't use SSL3 in its authorize payment module, but hav no way to verify that other than asking here. Is it correct that the Authorize.net module will continue to work without SSL3, or will I need to upgrade Magento?


texts: How to get all sub categories active and inactive

texts:
I want to know how I can get all active and inactive category children's

This code get me only the active childrens.

$parentCategory = Mage::getModel('catalog/category')->load($id);
$childCategory = Mage::getModel('catalog/category')->getCollection()
    ->addIdFilter($parentCategory->getChildren())
    ->addAttributeToFilter('name', $categoryName)
    ->getFirstItem()    // Assuming your category names are unique ??
;

Thanks


texts: Custom Code Mobile View Slider not working in iphone and well supported in Android

texts:
My Code :

QUICK LINKS -> 	&nbsp;&nbsp;&nbsp;&nbsp;
 MULTI-PURPOSE RACK 	&nbsp;&nbsp;&nbsp;&nbsp;
PUJA LAMPS	&nbsp;&nbsp;&nbsp;&nbsp;
 RETURN GIFTS 	&nbsp;&nbsp;&nbsp;&nbsp;
 SPECIAL POOJA PACKS 	&nbsp;&nbsp;&nbsp;&nbsp;
 GYA

Android Output:

iPhone Output:

How can i solve this UI Error?


texts: How to solve "The stock item was unable to be saved"?

texts:
I was using the Magento 2.3.2 normally, but since I updated to Magento 2.3.3 I'm not able to create a new product anymore. I'm receiving this message below.

  The stock item was unable to be saved. Please try again.

My exception.log is logging this message:

  [2019-11-06 17:30:42] main.CRITICAL: The stock item was unable to be saved. Please try again. {"exception":"[object] (Magento\Framework\Exception\CouldNotSaveException(code: 0): The stock item was unable to be saved. Please try again. at /Users/rafael/dev/mystoremagento/vendor/magento/module-catalog-inventory/Model/Stock/StockItemRepository.php:187, Magento\Framework\Exception\CouldNotSaveException(code: 0): Could not save Source Item at /Users/rafael/dev/mystoremagento/vendor/magento/module-inventory/Model/SourceItem/Command/Handler/SourceItemsSaveHandler.php:78, Zend_Db_Statement_Exception(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (mystoremagento.inventory_source_item, CONSTRAINT INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE FOREIGN KEY (source_code) REFERENCES inventory_source (source_code) ), query was: INSERT INTO inventory_source_item (source_code, sku, quantity, status) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE quantity = VALUES(quantity), status = VALUES(status) at /Users/rafael/dev/mystoremagento/vendor/magento/framework/DB/Statement/Pdo/Mysql.php:110, PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (mystoremagento.inventory_source_item, CONSTRAINT INVENTORY_SOURCE_ITEM_SOURCE_CODE_INVENTORY_SOURCE_SOURCE_CODE FOREIGN KEY (source_code) REFERENCES inventory_source (source_code) ) at /Users/rafael/dev/mystoremagento/vendor/magento/framework/DB/Statement/Pdo/Mysql.php:91)"} []

Even doing these tests it doesn't work:

Disabling all third-party module
Running the install process (using the same DB)
Exporting and importing the DB


texts: Problem: Attribute with the same code already exists

texts:
I used data-migration-tool to migrate my store from 1.9.2.2 to 2.1.14, but after the migration, I find I can't open "edit" page of any existing product. The following error message show up:

========================================================

  There has been an error processing your request.

  The configuration parameter "formElement" is a required for "" field.

  Error log record number: 1495859023951

(Yes, there is nothing in the second quote mark)

========================================================

Also, I tried to add new product, with new attribute set, but when I configured it and click "save", it shows:

========================================================

  Attribute with the same code already exists.

========================================================

Anyone knows how to solve it?


texts: Magefan blog - images not showing after update

texts:
I have updated the magefan extension and the images stop showing on blog lists page. When I click on the read more button and go to the post, the image is there, but the small thumbnail image in blog list mage is missing.

The inspector is giving me:

<img class="img-responsive" src=(unknown) alt="Image alt">

When I print the $img it does not returns me anything:

$img = $_helper->init($_post->getImage())->resize($_width,$_height);

In my error log i have error like this:

[Fri Aug 04 11:03:03.564586 2017] [:error] [pid 6922] [client
127.0.0.1:58264] PHP Fatal error:  Allowed memory size of 805306368
bytes exhausted (tried to allocate 400572416 bytes) in
/home/sasa/www/shopifit/app/design/frontend/Emthemes/
everything/default/Magefan_Blog/templates/post/list/item.phtml on line
25, referer: http://shopifit/
[Fri Aug 04 11:03:03.564784 2017] [:error] [pid 6922] [client
127.0.0.1:58264] PHP Fatal error:  Allowed memory size of 805306368
bytes exhausted (tried to allocate 400560128 bytes) in Unknown on line
0, referer: http://shopifit/

I tried php bin/magento setup:static-content:deploy and give all project sudo chmod -R 777 but nothing seems to work. If anyone have any idea please let me know.


texts:
In the store, each logged customer has own prices (depending on discounts he/she's got) for all products.
Therefore all prices are being pulled via AJAX call so that Full Page Caching is still available to use.
On product page it is simple as one AJAX call has to be performed to get product price.
How to achieve it on category page where you can find 30-60-90 products? Each product in the list needs to perform own AJAX call.

Please advice me on this. Thanks!


texts: How to get the total quantity of items ordered via Admin Panel

texts: I'm using Magento 1.7. In creating new order via admin panel, how do you get the total quantity of items ordered?


texts: Add class in price.phtml if product got special price

texts:
I want to add some class to the
, when the product got a special price.

NOTE: I only want to add this, if the product got a special price, not a catalog price rule.

How can I achieve that inside the price.phtml block ?

The code I want to edit is:

<?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 0)): // including ?>

                <?php echo $this->__('Regular Price:') ?>
                <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
                    <?php echo $_coreHelper->formatPrice($_regularPrice + $_originalWeeeTaxAmount, false) ?>

<?php endif; ?>


texts:
I've been consulting my cron jobs and they all have status pending, what do I have to do to perform these pending tasks?

Select * from cron_schedule


texts: Error 404 and redirect - Is it possible?

texts:
I have made a custom module to redirect an invalid url to a search of the incorrect url using the code below:
/app/code/ClickSavePrint/CustomNoRoute/App/Router
<?php
namespace ClickSavePrint\CustomnoRoute\App\Router;
class NoRouteHandler implements \Magento\Framework\App\Router\NoRouteHandlerInterface
{
    public function process(\Magento\Framework\App\RequestInterface $request)
    {
        $requestValue = ltrim($request->getPathInfo(), '/');
        $request->setParam('q', $requestValue);
        $request->setModuleName('catalogsearch')->setControllerName('result')->setActionName('index');
        return true;
    }
}

This module works great, but this still gives an HTTP Status code of 200 to search engines, is it possible to set the status of this page to a 404 or 410 and still have it redirect to the search page?
I have tried adding code like:
http_response_code(404);

and
$result->setStatusHeader(404, '1.1', 'Not Found');
$result->setHeader('Status', '404 File not found');

to that function but then i get an exception error.
I want users to still be able to get the best experience from my site if they stumble across an invalid product link, but still report an error 404 to the search engines so they will stop/not index that link.
I am using Magento 2.4.1 and PHP 7.4.


texts:
I've created my own CRUD module that contains an inline edit action similar to the one for CMS pages
Everything works OK, but when running phpsniffer with the EcgM2 standard I get this warning:

  Model LSD method save() detected in loop

How can I avoid this?
Note: The same warning appears if I "sniff" the core file linked above.
Here is my execute method in case someone needs it. But it's very similar to the one from the CMS page controller

public function execute()
{
    /** @var \Magento\Framework\Controller\Result\Json $resultJson */
    $resultJson = $this->jsonFactory->create();
    $error = false;
    $messages = [];

    $postItems = $this->getRequest()->getParam('items', []);
    if (!($this->getRequest()->getParam('isAjax') && count($postItems))) {
        return $resultJson->setData([
            'messages' => [__('Please correct the data sent.')],
            'error' => true,
        ]);
    }

    foreach (array_keys($postItems) as $authorId) {
        /** @var \Sample\News\Model\Author $author */
        $author = $this->authorRepository->getById((int)$authorId);
        try {
            $authorData = $this->filterData($postItems[$authorId]);
            $this->dataObjectHelper->populateWithArray($author, $authorData , AuthorInterface::class);
            $this->authorRepository->save($author);
        } catch (LocalizedException $e) {
            $messages[] = $this->getErrorWithAuthorId($author, $e->getMessage());
            $error = true;
        } catch (\RuntimeException $e) {
            $messages[] = $this->getErrorWithAuthorId($author, $e->getMessage());
            $error = true;
        } catch (\Exception $e) {
            $messages[] = $this->getErrorWithAuthorId(
                $author,
                __('Something went wrong while saving the author.')
            );
            $error = true;
        }
    }

    return $resultJson->setData([
        'messages' => $messages,
        'error' => $error
    ]);
}


texts: Magento 2 - read and write connection for custom query

texts:
I am using Magento 2.2.5 EE. I need to write some custom queries Select and Insert

I know how to write custom query, its simple:

Create new connection:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();

Apply select query through this:

$tableName = $resource->getTableName('employee'); //gives table name with prefix
//Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchAll($sql);

And Insert command using this:

//Insert Data into table
$sql = "Insert Into " . $tableName . " (emp_id, emp_name, emp_code, emp_salary) Values ('','XYZ','ABD20','50000')";
$connection->query($sql);

In magento 1.9, we just define "core_read" and "core_write" for our custom queries, it was that simple.

My question is, how Magento knows when to insert on master DB (write) and when to get data from read replica (read)? I mean the object for both commands is same.


texts:
As shown in the picture i have a category speakers having one item(product - Mini Car Speaker) and one category that is empty.

But when i try to access this from the front-end it does not show up. See:

and


texts:
I'm trying to re-index my Magento store and its stuck on re_index required, even after re-indexing..

The only thing I've done to it recently is add a filter extension by Aitoc.

It's also making the filter not work as intended too.

If anyone can give me some pointers I'd appreciate it,

Thanks


texts:
I'm not sure why on product pages the select dropdowns fire a change event on load, but I'm sure it's something to do with knockout.js.   Worse, there's no onchange event for knockout at all tied to the select, but when you change the select on a bundle page it magically adds summary.  How is it changing the page on a change event without having any change event on the select? :(

I need to set the select dropdowns to fire something on a change event but instead it fires it the second the page loads.


texts:
I am using magento 2.2.2

Frontend is working fine but admin is not working.

I have tried to deploy, upgrade, cache, compile etc but the admin is not working.

The admin url  is strange:

http://example.ca/admin/admin/admin/admin/index/index/key/16a571c82b097532a0b0a544997cf996979213e762894a777ddb798c5f476ad6/?SID=aiu8b9j92on4tv3m1thgsr8ub6

So normally admin keyword comes 2 times in the url but in my case it is coming 4 times.

I have check core_config_data table where custom_url and custom_path is set to 0.


texts:
I want to intercept sales_order_place_before event, so I created a new module named app\code\Giulio\CheckoutExtention, created aregistration.php` file where I put this code below:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Giulio_CheckoutExtension',
    __DIR__
);

a module.xml inside app\code\Giulio\CheckoutExtention\etcwhere I have declared my module like following:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd" >
    <module name="Giulio_CheckoutExtension" setup_version="0.0.1"/>
</config>

and then always inside \etc folder, an events.xmlwhere i declared my Observer like this.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="set_checkout_if_no_different_categories" instance="Giulio\CheckoutExtension\Observer\SetCheckout" />
    </event>
</config>

Then inside \Giulio\CheckoutExtension\Observer a SetCheckout.php file where I extended Monolog\Logger class for loggin some messages and implemented ObserverInterface like this:

<?php

namespace Giulio\CheckoutExtension\Observer;

use Magento\Framework\Event\Observer;
use Monolog\Logger;

class SetCheckout extends Logger implements \Magento\Framework\Event\ObserverInterface {

    public function execute(Observer $observer) {
        $order = $observer->getEvent()->getOrder();
        $order->setOrderId("CIAO");
        $this->warning("Ho creato un Log con l'observer");
    }
}

after executing

rm -rf var/di/* var/generation/* var/cache/* var/log/* var/page_cache/*

php bin/magento cache:clean

php bin/magento cache:flush

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento indexer:reindex

and tried to accessing Homepage for my store, the page wont load and it will be left blank.

Any suggestion?

Thanks you all anticipately!


texts: How do i control magento2 proxy setting?

texts:
I'm a Magento 2 beginner and not well English.

I have installed and used Magento 2 for a test in non-connecting internet PC.

Now, my Magento 2 need to connect to the proxy server when checkout is finished.

Because I can't finish checkout and reason of this problem is non-proxy.

How do I control magento2 proxy setting?


texts:
I have created a Block class as this

class Sb_AddressManager_Block_Address_Edit extends Mage_Customer_Block_Address_Edit {....}

and its path is

/www/abc/app/code/local/Sb/AddressManager/Block/Address/Edit.php

now I need its obj to use its functions in an other class
class Sb_Fs_Model_Order extends Mage_Sales_Model_Order {...}

whose  path is

/www/abc/app/code/local/Sb/Fs/Model/Order.php

How should I do this?


texts:
How do I link my cms pages to a main navigation bar at the top of the page on Magento 2?

If I want to eliminate the "home" link and only have the logo redirect to the store view homepage how do I do that?


texts: How to set default value to region(state) in checkout page magento 2.1..?

texts:
I need to set a default value for the region(state) in the checkout page.

tried it using jQuery. it's showing the value the field but it's not saving.

require([ 'jquery', 'jquery/ui'], function($){

    setInterval(function () {

        if($('input[name="city"]').val() != 'Perth')
        {

           $('input[name="city"]').val("Perth");
           $('input[name="city"]').attr('readonly',true);
           $('input[name="city"]').trigger('keyup');
           $('input[name="region"]').val("WA");
           $('input[name="region"]').attr('readonly',true);
           $('input[name="region"]').trigger('keyup');

        }

        },3000);

});

https://prnt.sc/i1jvx6

when I click save it not saving the region(state)

https://prnt.sc/i1jwgf

can anyone help me? it's urgent

Thanks in advance.


texts: How to optimize resources usage in Magento 1.9.2?

texts:
My website is showing the above error so many times. I contacted to server Hosting Technical support. they said, there is no available memory free to handle the new requests, that's why sometimes a 503 error is returned.

I want to optimize resource usage. how can i check the memory usage contains. which files & modules are using more memory & swap memory. how can i optimize them.


texts: Error programmatically rendering an invoice PDF

texts:
The error:

  Invalid template file: 'Magento_Payment::info/pdf/default.phtml' in module: 'Magento_Payment' block's name: 'info\instructions_0'

The class:

<?php
namespace Vendor\PDF\Response\Renderer;

use Magento\Framework\Webapi\Exception;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Sales\Api\InvoiceRepositoryInterface;
use Magento\Framework\Webapi\Rest\Response\RendererInterface;
use Magento\Sales\Model\Order\Pdf\Invoice as InvoicePdf;

class PdfRenderer implements RendererInterface
{
    private $request;
    private $invoiceRepository;
    private $invoicePdf;

    /**
     * Pdf constructor.
     * @param \Magento\Framework\Webapi\Rest\Request $request
     * @param \Magento\Sales\Api\InvoiceRepositoryInterface $invoiceRepository
     * @param \Magento\Sales\Model\Order\Pdf\Invoice $invoicePdf
     */
    public function __construct(
        Request $request,
        InvoiceRepositoryInterface $invoiceRepository,
        InvoicePdf $invoicePdf
    ) {
        $this->request = $request;
        $this->invoiceRepository = $invoiceRepository;
        $this->invoicePdf = $invoicePdf;
    }

    /**
     * Render content in a certain format.
     *
     * @param object|array|int|string|bool|float|null $data
     * @return string
     * @throws \Magento\Framework\Webapi\Exception
     */
    public function render($data)
    {
        if (!strstr($this->request->getPathInfo(), '/V1/invoices')) {
            throw new Exception(__('PDF rendering is not supported for this URI'));
        }

        if (isset($data['entity_id'])) {
            $invoice = $this->invoiceRepository->get($data['entity_id']);

            try {
                $pdf = $this->invoicePdf->getPdf([$invoice]);

            } catch (\Exception $e) {
                header("Content-type: application/json");
                exit(json_encode([
                    "operationPerformed" => false,
                    "message" => $e->getMessage()
                ]));
            }

            return $pdf->render();
        }

        throw new Exception(__('Invoice not found'));
    }

    /**
     * Get MIME type generated by renderer.
     *
     * @return string
     */
    public function getMimeType()
    {
        return 'application/pdf';
    }
}

The error happens when doing $this->invoicePdf->getPdf([$invoice]).

UPDATE:

Solved as suggested from the comments, by emulating the area code 'adminhtml'.
For reference, this is my code:

$this->appState->emulateAreaCode("adminhtml",
    function($invoice, &$pdf) {
        $pdf = $this->invoicePdf->getPdf([$invoice]);
    },
    [$invoice, &$pdf]
);


texts: Unable to change configuration of Magento2 Store

texts:
strong text

Hi, It seem write protected.  I am unable to change configuration of magento2 store. Can you please guide me how to enable sidebar settings.


texts: How to display manufacture image with product in categories page?

texts: I am working with magento 1.7. I added a manufacture image in my product and i wish to display it in the categories page with the list.


texts: What's SFTP utility? How can I get it & use it to upload images by CSV file?


texts: How to limit number of Customizable Options customer can select?

texts:
I have added multiple Customizable Options(e.g. Extra Buffalo Cheese,Extra Aioli,Extra Hollandaise,Extra Caesar Dressing) for products as shown in the image below. I want to restrict this option selection to a maximum to 2 only. basically, the user can select any 2 values for extra not more than two.
Is there a way to achieve this with CMS or through code as I have no idea here ? or Any other better way to do achieve the same.


texts:
What is the difference between?

$address->getAllNonNominalItems()

And

$address->getAllVisibleItems()

Please anyone can help me on this?


texts: Magento 2: PHP script exporting to csv will not export values for Backorders

texts:
I'm using Magento 2 as PIM for other shop solution. I need to export the backorders value once per hour until we have made an API.

The script below works fine, but values for 'backorders' are not exported. How can I fix that?

<?php
require './app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$_objectManager = $bootstrap->getObjectManager();
$state = $_objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$registry = $_objectManager->get('Magento\Framework\Registry');
$registry->register('isSecureArea', true);

//Store id of exported products, This is useful when we have multiple stores.
$store_id = 0;

$fp = fopen("export2.csv","w+");
$collection = $_objectManager-
>create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')
->create()->addStoreFilter($store_id)
->addAttributeToFilter('type_id', 'simple')
->addAttributeToSelect(array('updated_at','sku','status','backorders','price'));

foreach ($collection as $product)
{
$data = array();
$data[] = $product->getUpdated_at();
$data[] = $product->getSku();
$data[] = $product->getStatus();
$data[] = $product->getBackorders(); (doesn´t export value)
$data[] = $product->getPrice();

fputcsv($fp, $data);
}
fclose($fp);
?>


texts:
I need to always show calendar popup in div below input with datepicker.
There is my code

<div class="field date">
            <input type="text" name="datepicker" id="datepicker" value="" class="datepicker">
            <script>
                require(["jquery", "mage/calendar"], function($){
                    $("#datepicker").datepicker({
                        showMonthAfterYear: false,
                        dateFormat:'mm/dd/yy',
                        changeMonth: false,
                        changeYear: false,
                        firstDay: 0,
                        showsTime: false,
                        hideIfNoPrevNext: true,
                        minDate: new Date(),
                        yearRange: '2020:2025',
                    })
                });
            </script>
        </div>

How can i do this? Thanks


texts: Magento 2.0.7 "Urlkey for the store already exists" error while importing products

texts:
I am trying to import simple products, But it fails due to some validation error.
The error message i get is "Additional data: URL key for specified store already exists.".

I have checked the URL keys generated from the product names are all unique. but still i am having this annoying issue.

I am importing >10000 products.


texts:
I'm tryng to display categories and subcategories on a cms page

<?php
    $categories = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('*')
        ->addIsActiveFilter();
    foreach ($_categories->getStoreCategories() as     $_category) {
        $category = Mage::getModel('catalog/category');
        $category->load($_category->getId());
        $subcategories = explode(',', $category->getChildren());
?>

<?php echo $this->htmlEscape($_category->getName()); ?>

              <?php
                foreach ($subcategories as $subcategoryId) {
                  $category->load($subcategoryId);
                  echo '
getURL() . '">' . $category->getName() . '
';
                }
              ?>

    <?php
      }
    ?>

But this is returning me a fatal error Fatal error: Call to a member function getStoreCategories() on null on line 5


texts: Magento 2.2.4 : product image not display

texts:
After upgrade magento to version 2.2.4, There are one issue generated that in product page image not display.

One more thing, I have display error in console when image loading.

  SyntaxError : JSON.parse : unexpected character at line .. column .. of the JSON Data.

How can I solve this ?


texts: Magento install won't run due to version

texts:
I am trying to install magento, and i tried everything for what i can do, updating mysql, creating a .bash file in / with file bath to mysql.But all fail. When i run magento-check.php (a script to check if your upto date with all requirment for magento), it tell me your on mysql version 4.x. Whereas phpmyadmin mention something like 5.x version.
I tried installing bitnami magento but it came with magento 2, so not useful for me, as i am trying to run magento 1.9 and greater.
Can someone help me out, i am beyond frustrated. It never happened to be before.


texts: Get subscriber model based on e-mail address

texts:
I'm trying to read newsletter subscriber in Magento 1.9 from app\code\community\Salesmanago\Sso\Model\Observer.php with below code:
$subscriberRaw = Mage::getModel('Mage_Newsletter_Model_Subscriber')
                        ->getCollection()
                        ->addFilter('email',$subscriber['email']);

It gives me error:
There has been an error processing your request
Exception printing is disabled by default for security reasons.

Error log record number: 1500596311195

How to enable printing the errors? What's the proper way to get value from model with where clause.
Where can I find good guide for learning Magento?
Thank you! :)


texts: how to redirect reset password page to homepage

texts: If the registered user reset his password the page is redirecting to login page. Instead of that I want to redirect to homepage. How to achieve this task?


texts:
For product I have configurable attributes.
I want to get price of that product.
Price, Special price and final price.

I want to show this in invoice pdf.

I used

getPrice()
getSpecialPrice()
getFinalPrice()

to get price. But I am not getting price for configurable attributes.
Hope you understand.


texts: Magento 2 - sales-order-increment-prefix is not working

texts:
I want to add a prefix to sales order id. I install magento using "--sales-order-increment-prefix" as below:

php bin/magento setup:install --base-url=http://local.magento.com/ \
--db-host=127.0.0.1 --db-name=db1 --db-user=root --db-password=123456 \
--admin-firstname=Admin --admin-lastname=Admin --admin-email=abc@gmail.com \
--admin-user=admin --admin-password=1qaz2wsx --language=en_US \
--currency=HKD --timezone=Asia/Hong_Kong --use-rewrites=1 --backend-frontname=admin \
--sales-order-increment-prefix=abc

However, it is not working. And it results that the invoice id is always duplicated at PayPal side. Can anyone help?

Note: My Magento version is 2.0.8.


texts: Read csv and add image in category Magento 2

texts:
I tried this code but i could not upload image

<?php
use \Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');

ini_set('max_execution_time', 36000);
ini_set('post_max_size', '5000M');
ini_set("memory_limit","4046M");
ini_set('upload_max_filesize', '5000M');

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$obj->get('\Magento\Framework\App\State')->setAreaCode('frontend');
$storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

function readCSV($csvFile)
{
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) )
    {
        $line_of_text[] = fgetcsv($file_handle, 2024);
    }
    fclose($file_handle);
    return $line_of_text;
}

$csvFile = 'upload.csv';

$csv = readCSV($csvFile);
echo '<pre/>';
for($i=1;$i < (count($csv)-1);$i++)
{
    $category = $objectManager->create('Magento\Catalog\Model\Category')
                ->getCollection()
                ->addAttributeToSelect(array('*'))
                ->addFieldToFilter('name',array('eq' => $csv[$i][0]));
    $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
    $categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
    $categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

    $value =(array)$category->getData('entity_id');
    $category1 = $categoryFactory->create()->load($value[0]['entity_id']);

    $imagePath=$csv[$i][1];
    $mediaAttribute = array ('image', 'small_image', 'thumbnail');

    $category1->setImage($imagePath, $mediaAttribute, true, false);
    $category1->save();
}

I can get image path from csv but i could not upload that
CSV File Formate


texts: in magento controller file there is one get function is there "$mobile -> $model ->getphone();" where is that get phone method defined

texts: in magento custom module controller file there is one get function is there for getting a phone number "$mobile -> $model ->getphone();" where is that get phone method defined.


texts: Magento2 : Disable Pagination on certain condition from Category Page

texts:
I want to disable pagination and per page product which display on category page on some condition i.e. if I set cookies than on category page I want to disable pagination from category page otherwise it will show.

Thanks in advance for your help.


texts: could not found detail of the product using REST API

texts:
I tried to get all the product using REST API,i used this url
"http://localhost/magento2.1/rest/V1/products/?searchCriteria[pageSize]=100&searchCriteria[currentPage]=1"

Output of this url:

"item" : {
        "id" : 13,
        "sku" : "play game",
        "name" : "play game",
        "attribute_set_id" : 4,
        "price" : 59,
        "status" : 1,
        "visibility" : 4,
        "type_id" : "simple",
        "created_at" : "2018-05-10 11:59:37",
        "updated_at" : "2018-05-10 11:59:37",
        "weight" : 3,
        "extension_attributes" : [ ],
        "product_links" : [ ],
        "tier_prices" : [ ],
        "custom_attributes" : [
            {
                "attribute_code" : "description",
                "value" : "
high quality chip ,rom:4gb.
"
            },
            {
                "attribute_code" : "meta_title",
                "value" : "play game"
            },
            {
                "attribute_code" : "meta_keyword",
                "value" : "play game"
            },
            {
                "attribute_code" : "meta_description",
                "value" : "play game high quality chip ,rom:4gb."
            },
            {
                "attribute_code" : "news_from_date",
                "value" : "2018-05-01 00:00:00"
            },
            {
                "attribute_code" : "news_to_date",
                "value" : "2018-05-31 00:00:00"
            },
            {
                "attribute_code" : "options_container",
                "value" : "container2"
            },
            {
                "attribute_code" : "required_options",
                "value" : "0"
            },
            {
                "attribute_code" : "has_options",
                "value" : "0"
            },
            {
                "attribute_code" : "country_of_manufacture",
                "value" : "JP"
            },
            {
                "attribute_code" : "url_key",
                "value" : "play-game"
            },
            {
                "attribute_code" : "tax_class_id",
                "value" : "2"
            },
            {
                "attribute_code" : "gift_message_available",
                "value" : "2"
            }
        ]
    },

In this output it does not given detail of this field
"extension_attributes" : [ ],
"product_links" : [ ],
"tier_prices" : [ ],

How can i get the detail of this field.
can u provide the url or give detail so that i can get the detail of this field  in rest api .


texts: Change navbar and menu position in magento 2

texts:
hi my current behavior of theme is

And I want to do this like this

I tried to change it in admin area but could not find any option to preposition it. Its my first ever experience so dont know much about it .

EDIT

My default.xml is

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="header.panel">
            <block class="Magento\Framework\View\Element\Html\Links" name="header.links">
                <arguments>
                    <argument name="css_class" xsi:type="string">header links</argument>
                </arguments>
            </block>
        </referenceContainer>
        <referenceBlock name="logo">
            <arguments>
                <argument name="logo_img_width" xsi:type="number">10</argument>
                <argument name="logo_img_height" xsi:type="number">43</argument>
            </arguments>
        </referenceBlock>
        <referenceContainer name="footer">
            <block class="Magento\Store\Block\Switcher" name="store_switcher" as="store_switcher" after="footer_links" template="switch/stores.phtml"/>
        </referenceContainer>
        <referenceBlock name="report.bugs" remove="true"/>
        <move element="copyright" destination="before.body.end"/>
    </body>
</page>


texts: M2 backend and front end not working properly

texts:
I just installed M2 with all sample data. It was installed successfully but admin left panel links are not working. They all seems to be disabled.

My System:
1) Windows 7
2) Latest xampp (php 5.6.14)

Installation was successful but there is no sample data on front end either except few static page links like 'Privacy Policy' etc.

I guess there might be issue with windows 7 but i am not sure because installation was cool and success. What I am missing here?

  In short it was installed successfully but not working much on frontend and admin as well.

Added images of front and backend. All links of left panel are not working in admin.


texts: Set stock levels on the configurable products

texts:
As we all know when you have a configurable product such as a T-Shirt in blue and red, you would create 2 simple products and 1 configurable product and each simple product would have its own stock level as you have a certain number of red t-shirts and a certain number of blue t-shirts.

My issue is that I want to sell cans in either singles or multiple of 10's but deduct from the same stock. Therefore ideally I would like to set up a configurable product in the normal way but for the stock level to be set at the configurable product level rather than the simple product level. Does anyone know if this is possible?


texts:
We have no changes to core files.

I am trying to upgrade a remote development site from 1.9.2.2 to 1.9.2.4.

After making a backup of all files, I uploaded the contents of the magento folder in magento-1.9.2.4-2016-02-23-06-03-22.zip to the web root.

After the upload was complete, I loaded the front end home page URL, then checked the back end, and the version remained @ 1.9.2.2.

Nothing was broken, but wondering what final step I need to do to complete the upgrade?


texts:
I want to add some logic after place order using order_id. For this I tried sales_order_place_after event, but in this event I'm not getting order_id. And order_id is coming into event checkout_onepage_controller_success_action but this event only triggering on frontend.

I want to add some logic for both orders (frontend and backend).

Which event should I use so that I can add some logic stuff for backend orders as well?


texts:
I was trying to install a plugin and I removed var/generation and var/cache/*. I've checked the MAGE_MODE and I'm in developer but now when I access the front-end and the admin I get random errors saying mean things like:
Class Magento\Customer\Model\CustomerFactory does not exist

Class Magento\Sales\Model\ResourceModel\Report\OrderFactory does not exist

Some of the classes are being created, but not all. I've tried clearing cache again, and the generation folder but then I just get the same errors.

Any ideas?


texts: Magento 2: How to filter category by store id?

texts:
I want to filter category by store id. Used the following code, but it is not working.

$collection = $this->categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*')
        ->setStoreId(0);


texts: Knowing the store of the purchased product

texts:
I have a Magento 1.9 site with 2 stores. Both stores have different root categories.

Products of both categories are shared between both stores.

When a customer made a purchase, is there a way to know which store he bought the product from?

Thanks
Jaime


texts: Can I create Magento connect extension from angularJS code?

texts: I have a webwidget written in angularJS. I can load the webwidget in Magento site by embedding a small java script that loads the angularJS code that is deployed on a central CMS. Now I want to package this module into Magento connect extension and publish it Magento market place. Can this be done and how or do I need to write the entire module in PHP before creating it into extension archive?


texts: magento 1.9.1 database table mg_core_cache_tag went missing

texts:
We are running a ecommerce website on vps machine, Yesterday suddenly magento trowed an error saying mg_core_cache_tag table is missing from database.

It was very confusing about reason behind it occurrence. Mysql was running but database was not accessible from webmin but was able to access it from command line and came to know that it was available. what we did is dropped the table via command line and added a the table with reference from previous database backup and issue was fixed.

But what would have caused such an issue. we suspect the our server storage capacity was close to full. is it ok to add a table like that will it result in any future issues? what is the correct way to fix database error like this without restoring backup losing data?


texts: Where to search for the variable declared in magento core blocks?

texts:
Hi am just exploring magento files and trying to understand the code.
I came across the below code. This is piece of code from a file in block folder:

$pid = $this->getPid();
if ($products[$pid]->getData('list_swatch_attr_values')) {
    // check to see if product is using configurable swatches.
    // i.e. that is has values in list_swatch_attr_values array.
    $helper->attachGallerySetToCollection($products, $collection->getStoreId());
}

I understand a little logic here. But my doubt is where should I look for  list_swatch_attr_values whether in other block files or files in model or helper folder. Help me please.

Also there seems to be many methods in magento core files. Is everything user defined or is there predefined methods in PHP of magento core files?


texts: What's the best Dutch language pack for Magento 2

texts:
I currently working with a Magento 2.0 installation with sample data (LUMA template). Is there any dutch language pack available for all the strings?

https://github.com/Adwise/magento2-nl_NL-language\

This is the only language pack I've found but only 50% of the strings are translated.

It's also not a problem for me to pay for a language pack.


texts:
We have use magento 1.8. My problem is down the website every evening ~ 7 to 8 PM  (IST). Our hosting team checked in the server, they said 150% + CPU usage of index.php.
But we cant identify the issue.

We have optimized and speedup for below things
1. Enable the gzip
2. db optimization
3. Disable log
4. Disable unused modules
5. Enable the Keepalive in httacess
6. Image expiry date

But we not get any solution. Please help.


texts: Login and redirect customer to his website

texts:
In a mutistore-multiwebsite Magento, I'd like to force users to login to the same website they have registered. They might use any login form, in any website, but the form should check their credentials and redirect them to the correct website.

I tried to check the customer's website, and force him to login. It's not working quite good though. The user gets logged in to the current website, not the one he's registered.

In app/code/local/mage/Customer/Session.php

public function login($username, $password)
{
    /**************************************************/
    $customer = Mage::getModel("customer/customer");
    $customer_website = null;

    foreach (Mage::app()->getWebsites() as $website) {
        $customer->setWebsiteId($website->getId());
        $customer->loadByEmail($username);
        //check if user exists
        if($customer->getName()){
            $customer_website = $website->getId();
        }
    }
    /*************************************************/
    $customer = Mage::getModel('customer/customer')->setWebsiteId($customer_website);

    if ($customer->authenticate($username, $password)) {
        $this->setCustomerAsLoggedIn($customer);
        return true;
    }
    return false;
}

Any ideas?


texts: How to show other custom attribute instead of name customer in top link magento 2

texts: In my case, i have two type of customer: for local customer i will keep the firstname lastname in top link if it's connected else i want to display a custom attribute that i added in registration form so i will have instead this information and then the dropdown in top link so how to proceed  please any help ?


texts: Owl Carousel Magento 2 not Fully Responsive

texts:
I would like to use Owl Carousel in a new Magento 2 install, but I am having issues when resizing the browser window. I have a clean and working install of Magento 2. I have created a very simple theme that extends the standard Magento Blank theme. My custom them just loads the required css and javascript stuff for the Owl Carousel , nothing more. I have followed the steps in this tutorial (http://www.boolfly.com/magento-2-slider-with-owl-carousel), using my custom theme, and I can confirm that the Owl Carousel works and preforms as expected.

The issue happens when I resize the browser to ensure it works in a responsive way. When the browser reaches 768px, the carousel goes full width (off the page with browser scroll bars). I have tried a simple dummy web page (not Magento) and the carousel works perfectly.

As such I can only assume it has something to do with the css of the Magento/Blank theme or a simple schoolboy error on my part. Do you guys have any ideas?

-- Edit --

When using a theme that inherits the Magento/Blank theme, the issue happens at 767px and below. To test my theory that the mobile only style was the issue, I removed the mobile only style and set up the desktop style (css/styles-l.css) to have no media options. When the page was reloaded, the resizing issue did not occur. I also tried removing css/styles-l.css and only using css/styles-m.css to see if the would have the sizing issue, and it does.

So for some reason, Owl Carousel and the Magento/Blank theme dos not play nicley together below 767px. I haven't had the time to really look into the mobile style as of yet but I will do. Does any CSS people have any idea of where this issue might be found or what area I might look at first?


texts: Magento 2 getting issue in time interval?

texts:
I am using amasty one step checkout extension in which delivery date option available. It has delivery time range option only in admin. When I enabled this option then delivery date and time are showing on checkout page fine.

Time interval is of 1 hour. I want to change it to 2 hour.

  for example:

  9-11

  11-13

  13-15

I have tried but not getting success.

delivery date and time code is:

public function __construct(
        ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    public function getDeliveryDays()
    {
        $days = $this->scopeConfig->getValue(
            'amasty_checkout/delivery_date/available_days', ScopeInterface::SCOPE_STORE
        );

        if (!$days)
            return [];

        $days = explode(',', $days);

        foreach ($days as &$day) {
            $day = (int)$day;
        }

        return $days;
    }

    public function getDeliveryHours()
    {
        $hoursSetting = trim($this->scopeConfig->getValue(
            'amasty_checkout/delivery_date/available_hours', ScopeInterface::SCOPE_STORE
        ));

        $hours = [];

        $intervals = preg_split('#\s*,\s*#', $hoursSetting, -1, PREG_SPLIT_NO_EMPTY);

        foreach ($intervals as $interval) {
            if (preg_match('#(?P<lower>\d+)(\s*-\s*(?P<upper>\d+))?#', $interval, $matches)) {
                $lower = (int)$matches['lower'];
                if ($lower > 23) {
                    continue;
                }

                if (isset($matches['upper'])) {
                    $upper = (int)$matches['upper'];
                    if ($upper > 24) {
                        continue;
                    }

                    $upper--;

                    if ($lower > $upper) {
                        continue;
                    }
                } else {
                    $upper = $lower;
                }

                $hours = array_merge($hours, range($lower, $upper));
            }
        }

        if (!$hours) {
            $hours = range(0, 23);
        }
        else {
            $hours = array_unique($hours);
            asort($hours);
        }

        $options = [[
                        'value' => '-1',
                        'label' => ' ',
                    ]];

        foreach ($hours as $hour) {
            $options [] = [
                'value' => $hour,
                'label' => $hour . ':00 - ' . (($hour) + 1) . ':00',
            ];
        }

        return $options;
    }


texts: Email sending error: magento 2 Warning: Illegal string offset 'frontend_name' in vendor/magento/module-email/Model/AbstractTemplate.php on line 465

texts:
I am sending an email in custom event, it was working fine in Magento 2.3.1 but after upgrade to Magento version 2.4.0, It's showing me an error when I sending an email from custom code. Below is the code sample.
 $templateOptions = array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $options[$customer->getWebsiteId()]);

        $templateVars = array(
            'store' => $store->getWebsite($customer->getWebsiteId())->getName(),
            'email' => $customer->getEmail(),
            'name' => $customer->getFirstname() . ' ' . $customer->getLastname(),
            'newGroup' => $newGroupName,
            'oldGroup' => $oldGroupName,
            'logo_alt' => $logo['logo_alt'],
            'logo_width' => $logo['logo_width'],
            'logo_height' => $logo['logo_height'],
            'support_email' => $sender['email'],
            'support_phone' => $phone,
            'logo_url' => $store->getStore()->getBaseUrl(
                    \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                ) . 'email/logo/' . $logo['logo'],
        );

        $from = array('email' => $storeEmail, 'name' => $storeName);
        $to = array($customer->getEmail());

        $transport = $transportBuilder->setTemplateIdentifier('customer_change_group_email_template')
            ->setTemplateOptions($templateOptions)
            ->setTemplateVars($templateVars)
            ->setFrom($from)
            ->addTo($to)
            ->getTransport();
        $transport->sendMessage();

Below is the Magento 2 Warning:
Illegal string offset 'frontend_name' in /var/www/html/vendor/magento/module-email/Model/AbstractTemplate.php on line 465

I checked the above file for error and found below the line on 465, if I commented then it's working
if (!isset($variables['store']['frontend_name'])) {
            $variables['store']['frontend_name'] = $store->getFrontendName();
        }

I don't know what is use of this code in email sending.


texts:
Multiple addresses checkout setting wrong shipping rate in the overview (review my order) page. In this particular case I am sending 3 items to one address and 1 item to another address.

this image shows my 3 items shipping to 1 US address. I previously selected the $15.00 flat rate shipping. The total amount is correct but the shipping amount displayed is wrong. It should be $15.00

Is this a known magento bug? am I setting something wrong?

Thanks


texts: Magento 2.3.4 Emails have 2 content type headers

texts:
I am getting a few rejected emails undelivered from my Magento 2 install with the following error message or similar, but only about 1% at most of all customers (1000's), this problem does not occur with google/yahoo/outlook/aol or mainstream email customers receiving emails, only certain customers who must have very strict email client/server settings on a personal or business domain address:

  550 Messages should have one or no Content-Type headers, not 2.

All of my other email settings are fine (spf etc), but I am struggling with the above. I noticed in the emails being sent out, looking at the email code there are indeed two content-Type headers, one before the head and then one in the head itself, an extract from a recent email is below:

...
Date: Thu, 30 Jan 2020 06:42:17 +0000
MIME-Version: 1.0
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Subject: Your Order Confirmation
To: Some One <someone@someone.com>
From: Magento Store <magento@magentostore.com>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org=
/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns=3D"http://www.w3.org/1999/xhtml" style=3D"font-size: 62.5%; -we=
bkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; font-size-adjust: =
100%; background-color: #fff;">
<head>
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8">
<meta name=3D"viewport" content=3D"initial-scale=3D1.0, width=3Ddevice-widt=
h">
<meta http-equiv=3D"X-UA-Compatible" content=3D"IE=3Dedge">
<style type=3D"text/css">
...

If you are familiar with Magento's Market place, you will find that the emails from the Magento market place also have the two content-type headers after inspecting those emails, so is this problem of concern or is there a solution? Any thoughts!

I use Magento 2.3.4, and Magento's default email templates.


texts: Magento 2 - Add custom attribute to layout container

texts:
I try to add a new container to my layout. The container needs the attribute data-block='minicart'

<container name="minicart-wrapper" htmlTag="div" htmlClass="minicart-wrapper" data-block='minicart'/>

If I try this I get

  Element 'container', attribute 'data-block': The attribute 'data-block' is not allowed.

More Code:

<referenceContainer name="header-wrapper">
    <container name="header-row" label="Header Bootstrap" as="header-row" htmlTag="div" htmlClass="row">

        <container name="header-row-col-a" htmlTag="div" htmlClass="col-2"/>
        <container name="header-row-col-b" htmlTag="div" htmlClass="col-7"/>
        <container name="header-row-col-c" htmlTag="div" htmlClass="col-3">

            <container name="minicart-row" label="Wrapper" htmlTag="div" htmlClass="row no-gutters minicart-wrapper">  <--- Need data-block="minicart" here

                <container name="mini-wk" label="Top" htmlTag="div" htmlClass="col-9 offset-3 mini-wk">

                    <container name="mini-wk-top" label="Top" htmlTag="div" htmlClass="mini-wk-top">
                        <container name="mini-wk-top-row" label="Top Row" htmlTag="div" htmlClass="row no-gutters">

                            <container name="mini-wk-top-row-col-a" label="Benutzerkonto" htmlTag="div" htmlClass="col-6"/>
                            <container name="mini-wk-top-row-col-b" label="Anmelden/Abmelden" htmlTag="div" htmlClass="col-6"/>
                        </container>
                    </container>

                    <container name="mini-wk-content" label="Minicart-Main" htmlTag="div" htmlClass="mini-wk-content row no-gutters"/>
                </container>
            </container>
        </container>
    </container>
</referenceContainer>


texts: Forcing a Sorting Direction? dir=asc&order=popularity

texts:
I want to disable a sorting direction for sort field. "Relevance" is a good example. Ordering by least-relevant results gives the most horrible results. Basically I want to disable that option.

The reason is because Sort Direction somewhat sticky in the user experience and I don't want users viewing our most relevant results and thinking, "wow - this is bad search".

Where would I disable "ASC" or rewrite as "DESC" when order=relevance

Something like this maybe?? Just don't know where.

if($order == 'relevance') { $dir = "DESC"; }


texts: Magento filter search result by custom text

texts:
I have created one module Popular Search. In this module I am adding custom popular keywords like,

Shirt
Jeans
Dress

Now on search result page, I want to filter the result with these keyword. I have added Popular Search on left column for search result page only.

Logic behind filtering product is, when I click on any Popular keyword, it will check product title and list the product with matching.

Let say, I have 10 products on search result page www.demo.com/catalogsearch/result/?q=women. Now when I will click on dress, there is only 2 product that contain dress keyword in product title. So it will only list 2 product. I have added following code, but not getting how to filter with custom text.

<?php
$query = strtolower($_GET['q']);
if($this->getRequest()->getControllerName()=='result' && Mage::app()->getFrontController()->getAction()->getFullActionName()=='catalogsearch_result_index') {
    if($query != ""){
        $filteredList = $this->getLayout()
                ->getBlockSingleton('catalog/product_list')
                ->getLoadedProductCollection();
        foreach ($filteredList as $pro){
            $productNameArray[] = strtolower($pro->getName());
        }

        $collection = Mage::getModel('popularsearch/popularsearch')->getCollection();
        $collection->addFieldToFilter( 'status', '1' );
        if($collection->getSize()){
            foreach ($collection as $item) {
                $keywordName = strtolower($item->getKeyword());
                $keywordArray[] = $keywordName;

                foreach ($productNameArray as $proArray){
                    if( strpos( strtolower($proArray), $keywordName ) !== false ) {
                        $matchedKeywordList[] = strtolower($item->getKeyword());
                    }
                }
            }

            $matchedKeywordList = array_unique($matchedKeywordList);
            $finalLinkarray = array_merge(array_diff($matchedKeywordList, array($query)));
        }
    }
}
?>
<?php if($finalLinkarray):?>

Popular Searches

            <?php foreach ($finalLinkarray as $link):?>
            <?php
                $newlink = $this->getBaseurl()."catalogsearch/result/?".$link;
            ?>

<a href="<?php echo $link;?>"><?php echo ucfirst($link);?>

            <?php endforeach;?>

<?php endif;?>

any help will be appreciated.


texts: Cancel order with Magento's Free Payment Method

texts:
I have a few orders in the system which were placed using Magento's Free ( No Payment Required ) method but I want to try cancel them.

How do you go about cancelling an order with this payment method? There is no option in the backend and you can't credit memo something with R0 value.

Any ideas?


texts: Magento 2 - Multiple prices on one product

texts:
I am wondering if there is any basic idea on how to achieve multiple prices on one product (configurable product with multiple downloadable products) as you know it from a typical ticket sale.

Example, Ticket for event 1:
A ticket for a specific event can be configured and has multiple prices for:

Adults, 100€
Children, 80€
Children (younger than 6), 0,00€
...

Example, Ticket for event 2:
A ticket for a specific event can be configured and has multiple prices for:

Adults, 150€
Children, 75€
Children (younger than 6), 0,00€
...

As you can see the difference between the prices is not always the same. On the product detail page, you should be able to see the different groups and to increase/decrease the number of people, each increase/decrease would update the price.

I couldn't find any plugin or general approach how to achieve that and would probably go for setting up different prices fields for each "buyer group" (adults, children,...).


texts:
I am trying to generate a token which i need to create a WEB SERVICE for which i am using following code but i am not able to get a token.

Can any one please suggest me the proper way to generate a token.

<?php
$adminUrl='http://magento2-dev.local/index.php/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "admin", "password" => "password");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token=  json_decode($token);
echo '<pre>';
print_r($token);
exit;
?>


texts:
I got this .phtml file:

How can I make it work?
Thanks!


texts: Magento2 get email templates dropdown in stores configuration

texts:
How to get Email Templates in stores configuration in custom Tab. Please find the below link
http://prntscr.com/fvi0og

can anyone help me on this.
thanks


texts:
How can we implement insert on duplicate update using non-primary key or non-key field using Magento's function insertOnDuplicate?
Or is there any other way then please suggest.


texts: Fatal error when replacing fuction output with a string using plugin

texts:
I'm, learning magento development and trying to create a custom module in Magento 2.3.6 with page at localhost/magento236/lesson3/Page/view
The template file at Lesson3/Module/view/frontend/templates/homepage.phtml calls ViewModel function to output a friend's name from database
<?php
$viewModel = $this->getData('view_model');
$viewModel2 = $block->getViewModel();
echo ($viewModel->getFriendName(1));
?>

ViewModel is located at Lesson3/Module/ViewModel/Lesson3ViewModel.php
Part of ViewModel with function to change looks like this
   public function getFriendName($id)
    {
        return $this->getFriendModel($id)->getData('name');
    }

It works fine, shows a name from database with specified ID.
I need to output instead of friend's name any string. So I try to do this with magento plugin interceptor.
Created di.xml at Lesson3/Module/etc/frontend/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">
    <type name="Lesson3\Module\ViewModel\Lesson3ViewModel">
        <plugin name="Lesson3_Module" type="Lesson3\Module\Model\Plugin"
     sortOrder="1" />
    </type>
</config>

Created plugin class at Lesson3/Module/Model/Plugin.php
<?php
namespace Lesson3\Module\Model;
class Plugin
{
    public function aftergetFriendName(
        Lesson3\Module\ViewModel\Lesson3ViewModel $product, $name
    ) {
        $name = "TEXT";
        return $name;
    }
}

Executed php bin/magento set:di:compile, ran php bin/magento setup:upgrade anf flushed cache php bin/magento cache:flush.
When accessing the page there is Fatal error: Uncaught TypeError: Argument 1 passed to Lesson3\Module\Model\Plugin::aftergetFriendName() must be an instance of Lesson3\Module\Model\Lesson3\Module\ViewModel\Lesson3ViewModel
Please specify to me what should I have done to make it work


texts: How to change the "SHOP BY Shopping options" price ranges when viewing a category on the front page?

texts:
When I click on any category - it shows the SHOP BY Shopping Options box on the left and gives several Price range options like:

$0.00 - $99.99 (46)
$100.00 and above (14)

How can I customize it? I want to setup something like this:

$0.00 - $50
$50 - $100
$100 and above

Thanks for any suggestions! ;-)


texts: Exclude some items from minimum order rule

texts:
Is possible to exclude some SKUs from minimum order amount?

For example: Our limit for minimum order is 30$ and we don't want to include items #1, #2 and #3 into this limit because they are only bonus for customers..

Thank you in advance.


texts: Magento2 admin after login redirect back to admin login?

texts: In my magento2.1 installation when put user name and password and submit, the page redirect back to login page. Cleared cache, re indexed, and deployed the static contents as well. But nothing works. Project folder has 777 permissions. Any suggestion on how to solve this?


texts: Discount on products if selected from "Category A" but not from "Category B"

texts:
We have 8 products in "Category A" and same 8 products in "Category B". We want a functionality where when customer selects same product from CatB, they should get discount and not when they select from CatA.

If we make a rule with "Category is 10", then that is always try because this works on product level.


texts: Make 'New Address' as selected when 'Same as Shipping Address' is unchecked

texts:
I want to make 'New Address' as the selected option by default when we uncheck the 'Same as Shipping Address' option during checkout, instead of selecting the saved addresses in profile.

Thanks,
Vishnu


texts: Exceptions after changing to developer mode

texts:
After I changed to developer mode, I can't view the main page, and get the following exception (Magento 2.1.2)

Invalid XML in file x.com/app/code/Ves/ImageSlider/etc/widget.xml:
Element 'description': This element is not expected. Expected is ( value ).

The issue is labelled to be at this area of the xml file

<parameter name="autoplay_timeout" xsi:type="text" visible="true">
    Autoplay Timeout
    <depends><parameter name="autoplay" value="1" /></depends>
    <description translate="true"><![CDATA[Default: 3000]]></description>
    <value>3000</value>
</parameter>
<parameter name="autoplay_speed" xsi:type="text" visible="true">
    Autoplay Speed
    <depends><parameter name="autoplay" value="1" /></depends>
    <description translate="true"><![CDATA[Default: 800]]></description>
    <value>800</value>
</parameter>


texts: Magento 2 run a specific Cron without cron:run CLI command?

texts:
To make a long story short xdebug will not reliably stop on the breakpoints in my cron files when using the typical:

php bin/magento cron:run

Xdebug is all setup properly and sometimes it will work but 85% of the time it will not and just hang in CLI until I turn off listen for connections in phpstorm.

Is there a way to run just one cron file somehow? I had to actually copy and paste the contents of my cron file to a separate console command to test it properly in xdebug which is not ideal.

In Magento 1.x I used to use the AOE Scheduler for testing cron jobs with Xdebug by going to the admin, checkboxing the one I wanted, and choosing run from the dropdown and it worked fine.

I'm looking to use something like:

php bin/magento modulename:cronjob

which should always run the cron even if it is not scheduled.


texts:
Is there a way to mass disable (status) of all products within the Magento admin dashboard without using SQL or being able to access the back end of the system? We have over 4000 products and it would be very resource intensive to do so.

Also, if I do that, are you still able to place orders against those products? I only want to disable them for the front end customer interface BUT not the admin side and still place orders against those products.


texts: Magento 2 : How to overwrite file Magento Review controller

texts:
My requirement is to send an email to admin when a customer adds a product review. For that, I want to overwrite controller Magento\Review\Controller\Product\Post.php

Can someone help me with this?


texts: How to add an attribute to custom collection in admin grid?

texts:
I have a 3rd party extension which provides a grid. Now I want to extend the grid with a simple Magento attribute. It looks so easy but I can't get it to work!
I modified the function _prepareCollection() and wanted to add an attribute to the selection. Unfortunately all attempts failed.

That is my most promising solution (added before "setCollection") but it doesn't work either:

    $collection->getSelect()->join( array( '_atr'=>'eav_attribute'), "_atr.attribute_code = 'second_sku'", array());
    // $collection->addAttributeToSelect('second_sku');

Thats the (original) full function:

    protected function _prepareCollection() {
    $orderId = $this->getOrder()->getid();

    $collection = mage::getResourceModel('Purchase/OrderProduct_collection')
                    ->addFieldToFilter('pop_order_num', $orderId);

    //only products not supplied
    $collection->getSelect()->where('(pop_qty - pop_supplied_qty)  >0');

    //add image picture
    $smallImageTableName = mage::getModel('Purchase/Constant')->getTablePrefix() . 'catalog_product_entity_varchar';
    $collection->getSelect()->joinLeft($smallImageTableName,
            'pop_product_id=`' . $smallImageTableName . '`.entity_id and `' . $smallImageTableName . '`.store_id = 0 and `' . $smallImageTableName . '`.attribute_id = ' . mage::getModel('Purchase/Constant')->GetProductSmallImageAttributeId(),
            array('small_image' => 'value'));

    //join with product
    $productTableName = mage::getModel('Purchase/Constant')->getTablePrefix() . 'catalog_product_entity';
    $collection->getSelect()->joinLeft($productTableName,
            'pop_product_id=`' . $productTableName . '`.entity_id',
            array('sku' => 'sku'));

    $this->setCollection($collection);
    return parent::_prepareCollection();
}

Any help will be much appreciated! Thank you!

EDIT:
If I add my code to the original function I'll get following select:

SELECT `main_table`.*, `catalog_product_entity_varchar`.`value` AS `small_image`, `catalog_product_entity`.`sku` FROM `purchase_order_product` AS `main_table` LEFT JOIN `catalog_product_entity_varchar` ON pop_product_id=`catalog_product_entity_varchar`.entity_id and `catalog_product_entity_varchar`.store_id = 0 and `catalog_product_entity_varchar`.attribute_id = 109 LEFT JOIN `catalog_product_entity` ON pop_product_id=`catalog_product_entity`.entity_id INNER JOIN `eav_attribute` AS `_atr` ON _atr.attribute_code = 'second_sku' WHERE (pop_order_num = '1') AND ((pop_qty - pop_supplied_qty) >0);

As you see the select "works" but the attribute is not part of the selection. I already tried addAttributeToSelect and addFieldToSelect but both throw an error.


texts: Get custom attribute from product in ToOrderItem convert method

texts:
I'm implementing a plugin for Magento\Quote\Model\Quote\Item\ToOrderItem

    public function aroundConvert(\Magento\Quote\Model\Quote\Item\ToOrderItem $subject,
        \Closure $proceed,
        \Magento\Quote\Model\Quote\Item\AbstractItem $item,
        $additional = []) {
    $orderItem = $proceed($item, $additional);

    $product = $this->productFactory->create();
    $product->load($item->getProductId());

    $unitPv = 0;
    if ($product->getCustomAttribute('pv') != null) {
        $unitPv = $product->getCustomAttribute('pv')->getValue();
    }

    $pv = $unitPv;
    $qty = $orderItem->getQty();

    // ???
    $orderItem->setData('pv', $pv);
    $orderItem->setData('total_pv', $qty * $pv);
    return $orderItem;
}

This method to supposed to copy over a custom attribute (PV) from my products over to the sales order item field (PV and total PV) which I added directly to the sales_order_item table.

My code above is able to retrieve the PV from the products but for some reason is unable to assign the values to the ordered item. Is my syntax to assign the PV and total_pv to order_sales_item correct?


texts:
A product has a base price of $30 and a special price of $25. Tiered price discount for this product is $20 for 5 products and there's also a catalog rule active of 25% discount for this product. What will the product price shown on product detail page?

A. $15

B. $22.5

C. $25

D. $18.75

How do you guys think what is the right answer to this question?

Any ideas?


texts: redirect to a specific url upon account registration

texts:
I have a observer file that I am using to be able to assign a customer to a specific customer group if a specific checkbox is clicked. all is working great.

However what I want it when this registration observer is used to have the customer redirected to a different page instead of just bringing them to the account dashboard which is where all other registered users go upon registering.

Below is the code I am using in my observer.

namespace Impressmanicure\RegistartionObeserver\Observer\Customer;
use Magento\Framework\Event\ObserverInterface;
class RegisterSuccess implements \Magento\Framework\Event\ObserverInterface
{

/**
 * Execute observer
 *
 * @param \Magento\Framework\Event\Observer $observer
 * @return void
 */

const CUSTOMER_GROUP_ID = 3;

protected $_customerRepositoryInterface;

public function __construct( \Magento\Framework\App\RequestInterface $request, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface)
{
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
    $this->_request = $request;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{

    $customer = $observer->getEvent()->getCustomer();
    $postedData = $this->_request->getPost();

    if ($postedData['group_id'] == 3)
    {
        $customer->setGroupId(self::CUSTOMER_GROUP_ID);
        $this->_customerRepositoryInterface->save($customer);
        $this->response->setRedirect('./././vip-success');
    }
 }
}

the line

$this->response->setRedirect('./././vip-success');

is what I added in hoping it would overwrite the url redirect url that is used for the customer registration function however its not working what happens is now when you register an account the customer stays on the signup page and gets an error message saying We can't save the customer. even though the account does get created. ??


texts: Magento 2 how to display shipping methods sort order by price?

texts:
Hi we would like to sort and display the shipping methods by price Low to High on checkout page.
For example:
$31.72  Express Saver Federal Express
$37.50  2 DayFederal Express
$80.47  Standard Overnight Federal Express
$87.77  Priority Overnight Federal Express
$5.00   Fixed Flat Rate
$5.00   Media Mail Select Shipping Method
$10.00  FedEx Home Delivery Select Shipping Method

Referring this plugin concept trying to change my output using plugin.
Magento 2: Hide other shipping methods when free shipping is available
<?php
namespace Demo\Test\Plugin\Model;
use Magento\Framework\Session\Generic;

class ShippingMethodManagement {

    /**
     * @var Generic
    */
    private $coreSession;

    /**
     * @param \Magento\Framework\Session\Generic $sessionManager
    */
    public function __construct(
        Generic $sessionManager
    ) {
        $this->coreSession = $sessionManager;
    }

    public function afterEstimateByExtendedAddress($shippingMethodManagement, $output)
    {
        return $this->filterOutput($output);
    }
    public function afterEstimateByAddress($shippingMethodManagement, $output)
    {
        return $this->filterOutput($output);
    }
    public function afterEstimateByAddressId($shippingMethodManagement, $output)
    {
        return $this->filterOutput($output);
    }
    private function filterOutput($output)
    {
       //Here i would like to sort shipping methods by shipping amount

        $all = [];

            foreach ($output as $shippingMethod) {

                $all[] = $shippingMethod;
            }

            return $all;
        }
    }
}


texts: How to get timestamp from DB in magento 2

texts:
I have created admin grid and ui form.
If I add a item, created and updated timings are automatically saved in DB. I had fetched the Timings of created and modified. But it shows the date accurately.But failed to fetch the timing accurately (It shows six hours difference from the created or updated).Actual created timing is Nov 22, 2017 11:16:41 AM But it shows 2017-11-22 05:46:41.Please provide me a solution.

DataBase

I have got output like below.

AdditionalInfo.php

<?php

namespace xxX\HomeSlider\Block\Adminhtml\Edit\Tab\View;

use Magento\Framework\Exception\NoSuchEntityException;
use XXx\HomeSlider\Model\Post;

class AdditionalInfo extends \Magento\Backend\Block\Template
{

    /**
     * Interval in minutes that shows how long customer will be marked 'Online'
     * since his last activity. Used only if it's impossible to get such setting
     * from configuration.
     */
    const DEFAULT_ONLINE_MINUTES_INTERVAL = 15;

    protected $dateTime;
    protected $_coreRegistry;
    protected $authSession;

    public function __construct(
    \Magento\Backend\Block\Template\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Stdlib\DateTime\DateTime $datetime, \Magento\Backend\Model\Auth\Session $authSession, array $data = []
    )
    {
        $this->_coreRegistry = $registry;
        $this->authSession = $authSession;
        $this->datetime = $datetime;
        parent::__construct($context, $data);
    }

    public function getCurrentUser()
    {
        return $this->authSession->getUser()->getUsername();
    }

    public function getCreatedAt()
    {

        $postModel = $this->_coreRegistry->registry('homepageslider_post')->getCreatedAt();

        return $postModel;
    }

    public function getUpdatedAt()
    {

        $postModel = $this->_coreRegistry->registry('homepageslider_post')->getUpdatedAt();

        return $postModel;
    }

    public function getUpdatedUser()
    {
        return $this->authSession->getUser()->getUsername();
    }

}

additional_info.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
// @codingStandardsIgnoreFile

/** @var \OX\HomeSlider\Block\Adminhtml\Edit\Tab\View\AdditionalInfo $block */
$adminName = $block->getCurrentUser();
$createdAt = $block->getCreatedAt();
$updatedAt = $block->getUpdatedAt();
$updatedBy = $block->getUpdatedUser();
?>

        <?= $block->escapeHtml(__('Additional Information')) ?>

            <?= $block->getChildHtml() ?>

                <?= $block->escapeHtml(__('Created By:')) ?>
                <?= $block->escapeHtml($adminName) ?>

                <?= $block->escapeHtml(__('Created At:')) ?>
                <?= $block->escapeHtml($createdAt) ?>

                <?= $block->escapeHtml(__('Updated At:')) ?>
                <?= $block->escapeHtml($updatedAt) ?>

                <?= $block->escapeHtml(__('Updated By:')) ?>
                <?= $block->escapeHtml($updatedBy) ?>

<?php


texts: Magento 1.9.2.1 Cron not working for Order confirmation emails

texts:
I am experiencing very weird issues since this morning (up until then everything seemed to work fine). I made no changes to any code or settings.

All transactional emails are being sent (newsletter subscription, new customer confirmation etc), but not order confirmations. If I go to the backend and click "Send Email", nothing happens.

Exception and system logs are empty.

I have AOE Scheduler installed and it always says "no heartbeat task found". I configured cron as recommended by AOE:

* * * * * ! test -e /home/m1machining/public_html/maintenance.flag && /bin/bash /home/m1machining/public_html/scheduler_cron.sh --mode always
* * * * * ! test -e /home/m1machining/public_html/maintenance.flag && /bin/bash /home/m1machining/public_html/scheduler_cron.sh --mode default

Cron schedule table is not empty, shows that tasks were scheduled, but not executed.

If I "Run Now" with AOE, let's say scheduled emails task, in the database it shows that they've been executed, yet none of the emails being delivered.

If I truncate the cron schedule table, then it seems that it's not being repopulated.

What am I missing?

EDIT:

Fixed cron. AOE is working, all the tasks are displayed green, yet order confirmations still not sending. If I go to the backend and click on "Send Mail" for an order - nothing happens, in fact, it doesn't even being put in database email queue (not sure if it supposed to happen, but assume so).


texts:
I am trying to create a grouped product, but when I add simple produts to grouped, Magento says The value of attribute "nombre_mascota" must be set. If I create the grouped product but I don't add simple products, I can create a grouped product, but If I add simples, Magento doesn't allow saving this !

The attribute set hasn't "nombre_mascota"


texts: I have recently install magento 2.3, the app/design/frontend/magento/ is empty

texts: I have recently install Magento 2.3. The app/design/frontend/magento/  is empty. I want to modify the product detail page and catalog detail pages. I am new to Magento can anybody help me in this