Magento 2 Certified Developer(MCAD+MCPD)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

what script code is inserted to module's di.xml to create a virtualtype in Magento 2.?

#/etc/di.xml <config> <!-- ... --> <virtualType name="ourVirtualTypeName" type="My\Mod\Model\Virtualtype"> </virtualType> </config>

How to Initialization on an element Prompt Widget?

$('#prompt_init').prompt({ title: 'Prompt title', actions: { confirm: function(){}, //callback on 'Ok' button click cancel: function(){}, //callback on 'Cancel' button click always: function(){} } });

How to create object manager getting product options in Magento 2?

$_objectManager =\Magento\Framework\App\ObjectManager::getInstance();

How to /Load Configurable Product use $objectManager?

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);

Display product collection in phtml file?

$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { print_r($product->getData()); }

Configurable Options getting product options in Magento 2?

$productTypeInstance = $_objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable'); $productAttributeOptions = $productTypeInstance->getConfigurableAttributesAsArray($product);

How to getting configurable options product?

$productTypeInstance = $_objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable'); $productAttributeOptions = $productTypeInstance->getConfigurableAttributesAsArray($product);

How to get quote information by using quote id using external file?

$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote()->load($quoteId); print_r($quote->getOrigData());

How Programmatically get quoteFactory in Magento 2?

$quoteFactory = $objectManager->get('\Magento\Quote\Model\QuoteFactory')->create();

What are different ways of enhancing performance of Magento?

Disable any unused modules Enable Magento caching Optimize images Disable Magento log Combine external CSS/JS into a single file MySQL query caching Enable gzip compression

How to add custom options to Simple product programmatically?

// Adding Custom option to product $options = array( array("sort_order" => 1,"title" => "Custom Option 1","price_type" => "fixed","price" => "10", "type" => "field","is_require" => 0 ), array( "sort_order" => 2,"title" => "Custom Option 2","price_type" => "fixed","price" => "20","type" => "field","is_require" => 0 ) ); foreach ($options as $arrayOption) { $product->setHasOptions(1); $product->getResource()->save($product); $option = $objectManager->create('\Magento\Catalog\Model\Product\Option') ->setProductId($product->getId()) ->setStoreId($product->getStoreId()) ->addData($arrayOption); $option->save(); $product->addOption($option); }

How to Add an image to Simple product programmatically?

// Adding Image to product $imagePath = "sample.jpg"; // path of image $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false); $product->save();

Write step To Create Admin Admin ACL?

1: Create ACL rule 2: Flush Magento cache 3: Check ACL rule

Write Step of Overview of creating indexer?

1: Create Indexer configuration 2: Create Mview configuration 3: Create Indexer class 4: Run a test

How to Create System.xml Configuration?

1: Create System.xml 2: Set default value 3: Flush Magento cache 4: Get value from configuration

Step of creating CMS Page programmatically?

1: Create UpgradeData.php file 2: Insert UpgradeData class 3: Setup module version 4: Run upgrade script

Write step Overview of using cookie in Magento 2?

1: Create a controller to read cookie, 2: Create a controller to delete cookie

How to create simple shipping method in Magento 2

1: Create config.xml file 2: Create shipping model 3: Create configuration file 4: Enable module

How to Adding Category Attribute Programmatically in Magento 2?

1: Create file InstallData.php 2: Define install() method 3: Create category attribute 4: Display category attribute

Write Step of Adding Product Attribute Programmatically?

1: Create file InstallData.php 2: Define install() method 3: Create custom attribute

How to add a new input form to checkout in Magento 2?

1: Create form UI component. 2: Create template of form. 3: Register form in checkout page layout.

Write basic step to create admin menu in Magento 2?

1: Create menu.xml 2: Add Admin menu item 3: Flush Magento cache

Write step To Create Admin Menu in Magento 2?

1: Create menu.xml 2: Add Admin menu item 3: Flush Magento cache

Write step of Adding Customer Attribute Programmatically?

1: Create setup file InstallData.php 2: Define install() method 3: Create custom attribute

What Step custom validations before order placement Magento 2?

1: Create validator. 2: Add validator to validators pool. 3: Declare validation in checkout layout. 4: Test new validator.

How Magento 2 create Payment Method?

1: Create || module 2: Declare || module 3: Display || in checkout page

Write Step list of creating invoice programmatically in Magento 2?

1: Declare event sales_order_invoice_pay 2: Setup observer class

How to get related, upsell & crosssell products in Magento 2?

1: Declare in My_Mod 2: Get related products 3: Get upsell products 4: Get crosssell products

Step Overview of getting product collection in Magento 2?

1: Declare in My_Mod Block 2: Display product collection in phtml

Write basic step to Create a Custom Widget?

1: Declare widget 2: Create a widget template file 3: Create widget Block class 4: Flush cache & posts

Write step of Overview of creating events in Magento 2?

1: Dispatch event 2: Create a event file: events.xml 3: Create Observer class 4: Flush cache & check result

How to Add New Total to Email in Magento 2?

1: Generate :sales_email_order_items.xml 2: Create block new.order.totals

How to add custom fields in Product Edit pages?

1: Generate UI Component 2: Insert Manage Notes section in Product form (product_form.xml)

What step Overview of creating a new product type in Magento 2?

1: Generate registration.php 2: Enter code My\HelloWorld\Model\Product\Type\NewProductType model 3: Enter My\HelloWorld\Model\Product\Price model Step 4: Public new Magento 2 Product type

Write basic step of joining data between 2 tables?

1: Set a Collection class that extends 2: Set own function to get data 3: Get collection & call to filterOrder function above 4: Save

Write step overview of sending order email to a custom email address?

1: Set a form of email, 2: Set a controller file

How to Package Module in Magento 2?

1: Setup Composer file (composer.json) 2: Register component using registration.php 3: Package & generate component 4: View sample composer.json

how To create Model in Magento 2?

1: Setup Script 2: Create Model 3: Create Resource Model 4: Create Resource Model Collection 5: Factory Object

How to add custom shipping validations Magento 2?

1: Understand TableRate validators. 2: Add our custom rules/validator. 2.1 || Shipping rate validation rules 2.2: || Shipping Rates Validator 2.3: Registering our validator 2.4 || validation to checkout layout 3: Flush cache & test result

Where Dispatch event Magento 2 Create Events - Observer?

Now want to dispatch an magento 2 event list which allow other module can change word displayed. We will change controller like this: File:app/code/My/Mod/Controller/Index/Test.php

What is location of modules in Magento 2?

modules are located at vndor/magento directory.

Which Magento 2 core class need to use in implements ObserverInterface ?

namespace Cloudways\EventsObservers\Observer\Product; use Magento\Framework\Event\Observer; || \ObserverInterface;

Resource Model Collection - Get Model Collection content ?

namespace My/Mod\Model\ResourceModel\Topic; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection{ protected function _construct(){ $this->_init('My\Mod\Model\Topic', 'My\Mod\Model\ResourceModel\Topic'); } }

What magento 2 vendor need to use Dispatching events?

namespace MyCompany\MyModule; use Magento\Framework\Event\ObserverInterface;

How to add a UI Bookmark storageConfig option Component?

storageConfig: { saveUrl: 'path/to/save', deleteUrl: 'path/to/delete', namespace: 'namespace' }

Where can I find UI library?

stored under docs directory: lib/web/css/docs/source/README.md: Describes Magento UI library structure, naming conventions &code style. lib/web/css/docs: Contains a set of .html files with detailed information about library mixins.

Why use Magento 2?

stripped down & rebuilt from scratch now a quicker, easier & safer M2 1.very fast better than m1 2.New File Structure 3.New, more modern front-end codebas 4.Reduced number of conflicts (between modules trying to customize same functionality) 5.New Layout Elements 6.CSS Pre-processing 7.Magento UI Library 8.Improved performance & scalability 9.Reducing upgrade efforts & costs

How to add a UI Bookmark Component?

template option, component option

How to add a UI Bookmark template option Component?

templates: { view: { component: 'Magento_Ui/js/grid/controls/bookmarks/view' template: 'path/to/template' }, newView: { label: 'New View', index: '${ Date.now() }' } }

What are requited files for theme? What they are for? Describe each of them?

theme.xml: Contains basic meta-information, name & parent name, inherited from an existing theme used by system to recognise. composer.json: provides dependency information if theme is a composer package, dependencies & some meta information registration.php: Declares as a system component

Prompt Widget Options title?

title of prompt window. Type: String. Default value: ''

Magento 2 Indexing & Reindex?

transforms data such as products, categories so on to improve performance of storefront. As data changes, transformed data must be updated—or reindexed. sophisticated architecture that stores lots of merchant data (including catalog data, prices, users, stores, & so on) in many database tables. To optimize storefront performance, accumulates data into special tables using indexers. (ex suppose change price of an item from $8.99 to $6.99. M2 must reindex price change to display it on storefront.)

How to set a controller file path email to a custom email address?

Add file MyMod\Controller\Order\Email that is based on class \Magento\Framework\App\Action\Action. take submit action from above form, but firstly,

Create Mview configuration file?

<view id="my_mod_indexer" class="MyMod\Model\Indexer\Test" group="indexer"> <subscriptions> <table name="catalog_product_entity" entity_column="entity_id" /> </subscriptions> </view> </config>

Which class Magento 2 helper extend?

\Magento\Framework\App\Helper\AbstractHelper

How to get Logo url, Image Url, Alt text, Logo size in Magento 2?

echo $block->getLogoSrc(); || ->getLogoAlt(); || ->getLogoWidth(); || ->getLogoHeight()';

What is API content File: Api/PostManagementInterface.php?

namespace My\Mod\Api; interface PostManagementInterface { public function getPost($param); }

Write name product entry model?

\Magento\Catalog\Model\Product::ENTITY,

Where cart instance found?

\Magento\Checkout\Model\Cart

Where is $customerRepository?

\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository

Magento 2 Registry & Register?

\Magento\Framework\Registry accepts settings & registry of restored data create/use custom registry & to retrieve global M2 registry objects like current product, category, cms page, cms block, etc. Mage::register() & Mage::registry() in M1, but now in M2 platform difference in running registry.

Where found $fileUploaderFactory?

\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,

What is location of UrlRewriteFactory?

\Magento\UrlRewrite\Model\UrlRewriteFactory

Describe less files in Magento 2?

\web\css\source\_theme.less: (Overwrite existed variables & parent _theme.less) || \_extend.less: (extends parent theme simplest option add styles) ||\_variables.less:with all custom variables ||\_xxx_extend.less: extend xxx components styles-m.less: gathers UI Lib & everything (above & compiles results into plain CSS, all general & mobile styles) styles-l.less: as styles-m.less (except considers only specific styles for desktop)

How to change height & width for different media images?

_ROOT/vendor/magento/theme-frontend-luma/etc/view.xml, change height & width for different media images.

Where do add your custom variables?

_variables.less

In which directory we can write our own custom module?

app/code

What Magento Module composer.json files?

app/code/<vendor-name>/<module-name>/composer.json vendor/<vendor-name>/<module-name>/composer.json Name: <vendor-name>/<package-name> Type: magento2-module composer.json file for a module extension declares external dependencies that it needs to function.

where create controller to delete cookie?

app/code/Mageplaza/HelloWorld/Controller/Cookie

Where are module's base definition?

app/code/Module/etc/module.xml.

In which directory we write our own custom module?

app/code/VendorName/moduleName. e.g : app/code/Letsknowit/Hello_world

Where stored static files & folders?

app/design/<area>/mageplaza/ultimate/ ├── web/ │ ├── css/ │ │ ├── source/ │ ├── fonts/ │ ├── images/ │ ├── js/

Where to add new js file?

app/design/frontend/Vendor/example/web

Which file is responsible for keeping database credentials?

app/etc/env.php

What is EAV Attribute in Magento 2?

auto-extending models instead of there is an intervention into database.

are trying to determine why a product is not appearing in a category.What table does Magento on frontend to locate relationship between a category & its products?

catalog_category_product

How to display category attribute?

category UI Component is rendered with configuration from category_form.xml merged together add a field by creating a category_form.xml in ModulePath/view/adminhtml/ui_component/ directory. (Here is a full example of adding a field under "general" group. It is important to note that mp_new_attribute should match ID of attribute that created in install script)

Which method a controller loads by default?

execute method public function execute() { }

Is Magento 2 PSR-0 & PSR-4 compliant?

True

How to extends VirtualType?

class OurVirtualTypeName extends \MymodulePath\Model\Virtualtype{ }

Retrieve size of product image?

$_product = $block->getProductById($id); $_product = $block->getProductBySku($sku); echo $block->getImageOriginalWidth($_product, 'product_small_image'); || ->getImageOriginalHeight($_product, 'product_small_image');

How to Get product id & sku in template file?

$_product = $block->getProductById($id); ||->getProductBySku($sku); echo $_product->getEntityId(); ||->getName();

How to load product id & sku in template file?

$_productStock = $block->getStockItem('123'); (//print_r($_productStock->getData()); ) echo $_productStock->getQty(); echo '<br />'; ||->getMinQty(); ||->getMinSaleQty(); ||->getMaxSaleQty(); ||->getIsInStock();

How to get List Of Active Shipping Methods Using Object Manager?

$activeCarriers = $objectManager->create('\Magento\Shipping\Model\Config')->getActiveCarriers($store); $shippingMethodsArray = array(); foreach ($activeCarriers as $shippigCode => $shippingModel) { $shippingTitle = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface')->getValue('carriers/'.$shippigCode.'/title'); $shippingMethodsArray[$shippigCode] = array( 'label' => $shippingTitle, 'value' => $shippigCode); } print_r($shippingMethodsArray);

How to get List Of active shipping Methods Using Model?

$activeShippingMethods = $block->getActiveCarriers(); echo '<pre>'; print_r($activeShippingMethods);

Magento 2: Get List Of All Payment Methods Using Model?

$allPaymentMethods = $block->getAllPaymentMethods(); echo '<pre>'; print_r($allPaymentMethods); $activePaymentMethods = $block->getActivePaymentMethods(); echo '<pre>'; print_r(array_keys($activePaymentMethods));

Magento 2: Get List Of All shipping Methods Using Model?

$allShippingMethods = $block->getAllCarriers(); print_r($allShippingMethods);

How to Catalog sessions set from .phtml?

$block->getCatalogSession()->setMyName('MyMod'); echo $block->getCatalogSession()->getMyName() . '<br />'; // output: MyMod

Is possible to unset Catalog, Customer & Checkout sessions from .phtml?

$block->getCatalogSession()->unsMyName(); $block->getCheckoutSession()->unsTestData(); $block->getCustomerSession()->unsTestHello();

How to Customer sessions set from .phtml?

$block->getCheckoutSession()->setTestData('Hello World'); echo $block->getCheckoutSession()->getTestData() . '<br />'; // output: Hello World

How to Checkout sessions set from .phtml?

$block->getCheckoutSession()->setTestHello('Test Hello Value'); echo $block->getCheckoutSession()->getTestHello() . '<br />'; // output: Test Hello Value

How to Get number of items in cart & total quantity in cart.?

$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $totalItems = $cart->getQuote()->getItemsCount(); $totalQuantity = $cart->getQuote()->getItemsQty();

How to Get chosen billing & shipping addresses?

$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $billingAddress = $cart->getQuote()->getBillingAddress(); print_r($billingAddress->getData()); $shippingAddress = $cart->getQuote()->getShippingAddress(); print_r($shippingAddress->getData());

How to get base total & grand total price of items in cart.?

$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $subTotal = $cart->getQuote()->getSubtotal(); $grandTotal = $cart->getQuote()->getGrandTotal();

How to Get all needed information in your cart.?

$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); ($itemsCollection = $cart->getQuote()->getItemsCollection();) $itemsVisible = $cart->getQuote()->getAllVisibleItems(); $items = $cart->getQuote()->getAllItems(); foreach($items as $item) { echo 'ID: '.$item->getProductId().'Name: '.$item->getName(). 'Sku: '.$item->getSku().'Quantity: '.$item->getQty().'Price: '.$item->getPrice(); }

Get collection & call to filterOrder function joining data between 2 tables?

$collection = $this->YourCollectionFactory->create(); $collection->filterOrder("checkmo"); foreach ($collection as $item) { //do what want with data here. }

How to Initialize order shipment object?

$convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order'); $shipment=$convertOrder->toShipment($order);

How to get related products?

$currentProduct = $myBlock->getCurrentProduct(); $relatedProducts = $currentProduct->getRelatedProducts(); foreach ($relatedProducts as $relatedProduct) { echo $relatedProduct->getName(); (//getSku(),getPrice();getData() etc) }

Custom options getting product options in Magento 2?

$customOptions = $_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);

How Programmatically check whether email address is already registered or not in Magento 2?

$customer = $customerFactory->setWebsiteId($websiteId)->loadByEmail($email);

How to get customer information by using customer id external file?

$customer = $obj->get('\Magento\Customer\Model\CustomerFactory')->create()->load($customerId); print_r($customer->getData());

How to update customer info by email/ID by Using Object Manager?

$customer->setFirstname('Matin'); || ->setLastname('Rahman'); || ->setEmail('[email protected]'); || ->setCustomAttribute('abc', 'attribute value'); || ->save($customer);

How Programmatically get customerFactory in Magento 2?

$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();

How to Code to get customer default billing address in Magento 2 Using Object Manager?

$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customer = $customerFactory->load(5); $billingAddressId = $customer->getDefaultBilling(); $address = $objectManager->get('Magento\Customer\Model\AddressFactory')->create()->load($billingAddressId); print_r($address->getData()):

How to get product information by using product id using external file?

$product = $obj->get('Magento\Catalog\Model\ProductRepository')->getById($productId); echo '<pre>'; print_r($product->getData());echo '</pre>';

How to Code to get customer default shipping address in Magento 2 Using Object Manager?

$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customer = $customerFactory->load(5); $shippingAddressId = $customer->getDefaultShipping(); $address = $objectManager->get('Magento\Customer\Model\AddressFactory')->create()->load($shippingAddressId); print_r($address->getData());

How to Get Customer Information By Id in Magento 2 Using Object Manager?

$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customer = $customerFactory->load(5); echo $customer->getFirstname() . '<br>'; echo $customer->getLastname() . '<br>'; echo $customer->getEmail() . '<br>';

Magento 2 Create Customer Programmatically Run code snippet?

$customerSetupFactory = $objectManager->create('Magento\Customer\Setup\CustomerSetupFactory'); $setupInterface = $objectManager->create('Magento\Framework\Setup\ModuleDataSetupInterface'); $customerSetup = $customerSetupFactory->create(['setup' => $setupInterface]); $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer'); $attributeSetId = $customerEntity->getDefaultAttributeSetId(); $attributeSetFactory = $objectManager->create('Magento\Eav\Model\Entity\Attribute\SetFactory'); $attributeSet = $attributeSetFactory->create(); $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId); $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'attribute_code', [ 'type' => 'varchar', 'label' => 'Attribute Title', 'input' => 'text', 'required' => false, 'visible' => true, 'user_defined' => true, 'sort_order' => 1000, 'position' => 1000, 'system' => 0, ]); $attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'attribute_code') ->addData([ 'attribute_set_id' => $attributeSetId, 'attribute_group_id' => $attributeGroupId, 'used_in_forms' => ['adminhtml_customer'], ]); $attribute->save();

Add EAV attribute in Magento 2?

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

How to remove an eav attribute for product in Magento 2?

$entityTypeId = 4; // Find these in eav_entity_type table $eavSetup->removeAttribute($entityTypeId, 'is_featured');

How to get related products getInstance?

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('My\Mod\Block\HelloWorld');

Get upsell products?

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('My\Mod\Block\MyMod'); $currentProduct = $myBlock->getCurrentProduct(); if ($currentProduct = $myBlock->getCurrentProduct()) { $upSellProducts = $currentProduct->getUpSellProducts(); if (!empty($upSellProducts)) { echo '<h3>UpSell Products</h3>'; foreach ($upSellProducts as $upSellProduct) { echo $upSellProduct->getSku(); } } }

Get crosssell products?

$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('My\Mod\Block\MyMod'); $currentProduct = $myBlock->getCurrentProduct(); if ($currentProduct = $myBlock->getCurrentProduct()) { $crossSellProducts = $currentProduct->getCrossSellProducts(); if (!empty($crossSellProduct)) { echo 'CrossSell Products <br />'; foreach ($crossSellProducts as $crossSellProduct) { echo $crossSellProduct->getSku() ; } } }

How to Use $objectManager?

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

How to Get Order Items Information Using Object Manager?

$order = $objectManager->create('\Magento\Sales\Model\OrderRepository')->get($orderId); foreach ($order->getAllItems() as $item){ echo $item->getId(). $item->getName(). $item->getProductType(). $item->getQtyOrdered(). $item->getPrice(); }

How to Get Order Payment Information in Using Object Manager?

$order = $objectManager->create('\Magento\Sales\Model\OrderRepository')->get($orderId); print_r($order->getPayment()->getData()); echo $order->getPayment()->getAmountPaid(); || ->getMethod(); || ->getAdditionalInformation('method_title');

How to Get Order Billing Information in Magento 2 Using Object Manager?

$order = $objectManager->create('\Magento\Sales\Model\OrderRepository')->get($orderId); print_r($order->getBillingAddress()->getData()); echo $order->getBillingAddress()->getCity(); (/getRegionId();/getCountryId();)

How to Get Order Information From Order ID in Magento 2 Using Object Manager?

$order = $objectManager->create('\Magento\Sales\Model\OrderRepository')->get($orderId);) print_r($order->getData()); echo $order->getIncrementId(); || ->getGrandTotal(); || ->getSubtotal(); || ->getCustomerId(); || ->getCustomerEmail(); || ->getCustomerFirstname(); || ->getCustomerLastname();

How Programmatically Create Order From Quote in Magento 2?

$order = $objectManager->get('\Magento\Quote\Model\QuoteManagement')->submit($quoteFactory); $order->setEmailSent(0); echo 'Order Id:' . $order->getRealOrderId();

How load order by orderID ?

$order = $this->_objectManager->create('Magento\Sales\Model\Order')->load('1');

How to Load order increment ID?

$order = $this->_objectManager->create('Magento\Sales\Model\Order')->loadByIncrementID($incrementid);

Magento 2: Get List Of All Payment Methods Using Object Manager?

$paymentHelper = $objectManager->get('Magento\Payment\Helper\Data'); $allPaymentMethods = $paymentHelper->getPaymentMethods(); print_r($allPaymentMethods); $paymentConfig = $objectManager->get('Magento\Payment\Model\Config'); $activePaymentMethods = $paymentConfig->getActiveMethods(); print_r(array_keys($activePaymentMethods));

How to get Collection stock item from Resource Model?

$resource = $objectManager->create('Magento\CatalogInventory\Model\ResourceModel\Stock\Item'); $select = $resource->getConnection()->select()->from($resource->getMainTable()); $stockItems = $resource->getConnection()->fetchAll($select); foreach($stockItems as $_item){var_dump($_item->getData());}

How to update data from database table, through $objectManager Without Using Model ?

$resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $con = $resource->getConnection(); $tableName = $resource->getTableName('mytable'); $sql = ("UPDATE " . $tableName . " SET name = 'Matin', email = '[email protected]', website_url = 'http://www.url.com' WHERE id = " . $id); $con->query($sql);

How to insert data on database table through $objectManager Without Using Model ?

$resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $tableName = $resource->getTableName('mytable'); $name = 'Thomas Raj'; $email = '[email protected]'; $website_url = 'http://www.example.com'; $sql = "INSERT INTO " . $tableName . " (id, name, email, website_url) VALUES ('', '$name', '$email', '$website_url')"; $connection->query($sql);

How to fetch data from database table, through $objectManager Without Using Model ?

$resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $tableName = $resource->getTableName('mytable'); $sql = "SELECT * FROM " . $tableName; $result = $connection->fetchAll($sql); echo '<pre>'; print_r($result);

How to delete data from database table, through $objectManager Without Using Model ?

$resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $tableName = $resource->getTableName('mytable'); $sql = "DELETE FROM " . $tableName . " WHERE id = " . $id; $connection->query($sql);

How to add shipment item to shipment?

$shipment->addItem($shipmentItem);

How to Register shipment ?

$shipment->register(); $shipment->getOrder()->setIsInProcess(true); try { // Save created shipment & order,Send email } catch (\Exception $e) { }

How to save created shipment & order?

$shipment->save(); $shipment->getOrder()->save();

How to // Create shipment item with qty?

$shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

How Programmatically Collect Rates & Set Shipping & Payment Method?

$shippingAddress = $quoteFactory->getShippingAddress(); $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate'); $quoteFactory->setPaymentMethod('checkmo'); //payment method $quoteFactory->setInventoryProcessed(false); $quoteFactory->save();

Ma2: Get List Of All Shipping Methods Using Object Manager?

$store = $objectManager->create('\Magento\Store\Model\StoreManagerInterface')->getStore();) $allCarriers = $objectManager->create('\Magento\Shipping\Model\Config')->getAllCarriers($store); $shippingMethodsArray = array(); foreach ($allCarriers as $shippigCode => $shippingModel) { $shippingTitle = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface')->getValue('carriers/'.$shippigCode.'/title'); $shippingMethodsArray[$shippigCode] = array( 'label' => $shippingTitle,'value' => $shippigCode); } (echo '<pre>'; print_r($shippingMethodsArray);)

Get Base URL, Store URL & Current URL Using Object Manager?

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $store = $storeManager->getStore(); echo $store->getBaseUrl(); ||->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK); ||->getBaseUrl( || ::URL_TYPE_MEDIA); || ->getBaseUrl( || ::URL_TYPE_STATIC); ||->getCurrentUrl(); || ->getUrl('faq/index');

How Bundle selection getting product options in Magento 2?

$store_id = $_storeManager->getStore()->getId(); $options = $_objectManager->get('Magento\Bundle\Model\Option')->getResourceCollection()->setProductIdFilter($product->getId())->setPositionOrder(); $options->joinValues($store_id); $typeInstance = $_objectManager->get('Magento\Bundle\Model\Product\Type'); $selections = $typeInstance->getSelectionsCollection($typeInstance->getOptionsIds($product), $product);

How to create order programmatically Magento 2?

$tempOrder=[ 'currency_id' => 'BDT', 'email' => '[email protected]', ('shipping_address' =>[ 'firstname' => 'Matin', 'lastname' => 'Rah', 'street' => '123 Demo','city' => 'Dhaka', 'country_id' => 'BD', 'region' => 'xxx','postcode' => '10019', 'telephone' => '0123456789', 'fax' => '32423', 'save_in_address_book' => 1) ], 'items'=> [ ['product_id'=>'1','qty'=>1],['product_id'=>'2','qty'=>2] ] ];

How to Send email shipment & order?

$this->_objectManager->create('Magento\Shipping\Model\ShipmentNotifier')->notify($shipment); $shipment->save();

How to getting Grouped Childs product options in Magento 2?

$typeInstance = $_objectManager->get('Magento\GroupedProduct\Model\Product\Type\Grouped'); $childs = $typeInstance->getAssociatedProducts($product);

How URL Rewrite Insert custom URL rewrite in execute method?

$urlRewriteModel = $this->_urlRewriteFactory->create() $urlRewriteModel->setStoreId(1); $urlRewriteModel->setIsSystem(0); $urlRewriteModel->setIdPath(rand(1, 100000)); $urlRewriteModel->setTargetPath("www.url.com/customModule/customController/customAction"); $urlRewriteModel->setRequestPath("www.example.com/xyz"); $urlRewriteModel->save();

How to load load customer info by email/ID by Using Object Manager?

$websiteId = $storeManager->getStore()->getWebsiteId(); $customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface'); (// load customer info by email) $customer = $customerRepository->get('[email protected]', $websiteId); (// load customer info by id 0) $customer = $customerRepository->getById(12);

How to assign associated configurable product programmatically?

($attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');) ($position = 0;) ($attributes = array(134, 135);) (// Super Attribute Ids Used To Create Configurable Product) ($associatedProductIds = array(2,4,5,6); )(//Product Ids Of Associated Products) foreach ($attributes as $attributeId) { $data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position); $position++; $attributeModel->setData($data)->save(); } $product->setTypeId("configurable"); (// Setting Product Type As Configurable) $product->setAffectConfigurableProductAttributes(4); $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product); ($product->setNewVariationsAttributeSetId(4);) (// Setting Attribute Set Id) ($product->setAssociatedProductIds($associatedProductIds);)(// Setting Associated Products) ($product->setCanSaveConfigurableAttributes(true);) $product->save();

Get custom options of products present in shopping cart?

($cart = $objectManager->get('\Magento\Checkout\Model\Cart'); ) ($items = $cart->getItems();) foreach ($items as $item) { $options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()); $customOptions = $options['options']; if (!empty($customOptions)) { foreach ($customOptions as $option) { $optionTitle = $option['label']; $optionId = $option['option_id']; $optionType = $option['type']; $optionValue = $option['value']; } } }

Retrieve custom options of products present any order?

($orderObject = $objectManager->get('\Magento\Sales\Model\Order'); ) ($order = $orderObject->load($orderId);) ($order = $orderObject->loadByIncrementId($incrementId);) ($items = $order->getAllVisibleItems();) (get all items aren't marked as deleted & that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched) (// Order items can also be fetched with following functions) $items = $order->getAllItems();( // get all items that are not marked as deleted) $items = $order->getItems(); (// get all items) foreach ($items as $item) { $options = $item->getProductOptions(); if (isset($options['options']) && !empty($options['options'])) { foreach ($options['options'] as $option) { echo 'Title: ' . $option['label']. 'ID: ' . $option['option_id']. 'Type: ' . $option['option_type'].'Value: ' . $option['option_value'];} } }

How to create Simple product programmatically?

($product = $objectManager->create('\Magento\Catalog\Model\Product'); $product->setSku('my-sku'); (// Set your sku here) $product->setName('Sample Simple Product'); (// Name of Product) $product->setAttributeSetId(4); (// Attribute set id) $product->setStatus(1); (// Status on product enabled/ disabled 1/0) $product->setWeight(10); (// weight of product) $product->setVisibility(4); (// visibilty of product catalog / search / catalog, search / Not visible individually) $product->setTaxClassId(0); (// Tax class id) $product->setTypeId('simple'); (// type of product simple/virtual/downloadable/configurable) $product->setPrice(100); (// price of product) $product->setStockData( array('use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, 'qty' => 999999999)); $product->save();

Using Plugin Block Override file di.xml content?

(<?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="Magento\Catalog\Block\Product\View"> <plugin name="My-Mod-product-block" type="MyMod\Plugin\ProductPlugin" sortOrder="5" /> </type> </config>

UpgradeData.php of creating CMS Page programmatically?

(@codeCoverageIgnore) (class UpgradeData implements UpgradeDataInterface{) (@var \Magento\Cms\Model\PageFactory) ( protected $_pageFactory;) ( Construct @param \Magento\Cms\Model\PageFactory $pageFactory) public function __construct( \Magento\Cms\Model\PageFactory $pageFactory ) {($this->_pageFactory = $pageFactory;) } ( @param ModuleDataSetupInterface $setup @param ModuleContextInterface $context) public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $setup->startSetup(); if (version_compare($context->getVersion(), '1.1') < 0) { $page = $this->_pageFactory->create(); $page->setTitle('Example CMS page') ->setIdentifier('example-cms-page') ->setIsActive(true) ->setPageLayout('1column') ->setStores(array(0)) ->setContent('Lorem ipsum .') ->save(); } $setup->endSetup(); } }

Add a specific new file getting value of custom attribute via rest api?

(Because Magento 2 does not support for a new field in response on Rest API, so must add a file \app\code\Mageplaza\HelloWorld\etc\extension_attributes.xml in extension folder with content:) (<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">) <extension_attributes for="Magento\Sales\Api\Data\OrderInterface"> <attribute code="mageplaza_helloworld_custom_attribute" type="string" /> </extension_attributes> </config>

How to call instance in events.xml on <event> tag ?

(Cloudways/EventsObservers/etc/frontend/events.xml ) <event name="catalog_controller_product_view"> <observer name="CloudwaysProductData" instance="Cloudways\EventsObservers\Observer\Product\Data" /> </event>

How Defining an overriding controller class?

(Create:/OverrideController/Controller/Product/View.php) namespace My\Mod\OverrideController\Controller\Product; class View extends \Magento\Catalog\Controller\Product\View{ public function execute(){ (// Do something here) $this->messageManager->addSuccess('Message From OverrideController.'); return parent::execute(); } }

What do mean by Dispatching events?

(Events can be dispatched using Magento\Framework\Event\Manager class. This class can be obtained through dependency injection by defining dependency in your constructor.) To dispatch an event, call dispatch function of event manager class & provide it with name of event want to dispatch along with an array of data wish to provide to observers.

Configure catalog product images?

(Go to app/design/<area>/mageplaza/ultimate/ & create a folder etc & file view.xml can copy view.xml file in parent theme such as Blank theme app/design/frontend/Magento/blank/etc/view.xml) <image id="category_page_grid" type="small_image"> <width>250</width><height>250</height> </image>

How to create new address in Magento 2?

(If want to create a new address for a customer & set it as default shipping or billing address, only need to create a new address object from factory:) $address = $this->_addressFactory->create(); (A set its data. Depending on its type need to set it as default shipping or default billing. can also set both, so that a customer has only one address:) if($type == "shipping") $address->setIsDefaultShipping('1'); if($type == "billing") $address->setIsDefaultBilling('1');

Why Unit Test?

(Magento 2 Unit Test allows auto-defining some errors before launching software instead of that developers have to do it by themselves. Due to that, more powerful unit testing process, better management of project managers & functional managers. unit test plays a role in improving manageability like:) Tests Reduce Bugs in New Features || Reduce Bugs in Existing Features || Are Good Documentation || Reduce Cost of Change || Allow Refactoring || Constrain Features || Defend Against Other Programmers || Makes Development Faster (Thus, generating a unit test is important first step for high quality of new class. Don't forget that can find unit test in app/code/[Vendor]/[ModuleName]/Test/Unit.)

What do mean by Module dependencies require & conflict field?

(Require field in composer.json file of each module while conflicts are announced in conflict field, dependencies among modules still try to enable & disable without rule, error message will be shown & inform dependency graph.) A->B means Module A depends on Module B. A->B->C means Module A depends Module B while Module B depends on Module C.

How set a form of email to a custom email address in Magento 2?

(Set form of email with input field line as following:) <form id="send-order-email" action="<?php $block->getUrl('helloworld/order/sendemail'); ?>"> <label>Email Address</label> <input type="text" class="input-text" id="email"> </form>

Add an observe getting value of custom attribute via rest api?

(To inject custom attribute into extension_attributes.xml, it is compulsory to add an observe for event ``sales_order_load_after via \app\code\My\Mod\etc\events.xml`.) <event name="sales_order_load_after"> <observer name="sales_order_load_helloworld_custom_attribute" instance="MyMod\Observer\Sales\OrderLoadAfter" /> </event> </config>

Add/modify default.xml file adding top link in Magento 2?

(add: app/code/My/Mod/view/frontend/layout/default.xml) <referenceBlock name="header.links"> <block class="My\Mod\Block\Link" name="add-new-header-link"> <arguments> <argument name="label" xsi:type="string" translate="true">NewLink</argument> <argument name="path" xsi:type="string" translate="true">new-link</argument> (</arguments> </block> </referenceBlock>)

How to get Customer session?

(allows collecting customer information like customer name & email.) if ($block->getCustomerSession()->isLoggedIn()) { $customerId = $block->getCustomerSession()->getCustomerId(); $customerData = $block->getCustomerSession()->getCustomer(); echo $customerId; echo $customerData->getFirstname() . $customerData->getLastname(); echo $customerData->getEmail(); print_r($block->getCustomerSession()->getCustomer()->getData()); }

What is content of file InstallData.php?

(namespace My\Mod\Setup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface;) class InstallData implements InstallDataInterface{ private $eavSetupFactory; public function __construct(EavSetupFactory $eavSetupFactory){ $this->eavSetupFactory = $eavSetupFactory; } }

Create custom route on admin routes structure & url example?

(url of admin page is same structure with frontend page, but) admin_area name will be added before route_frontName to recognize this is a admin router. (http://url.com/index.php/admin/my_mod/controller/action) controller action for admin page will be added inside of folder Controller/Adminhtml. For example for above url:{namespace}/{module} /Controller/Adminhtml/ {Controller}/{Action}.php

How to Use code in external file/script in Magento 2?

(use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $params = $_SERVER;) $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $quote = $obj->get('Magento\Checkout\Model\Session') ->getQuote()->load($quoteId); echo '<pre>';print_r($quote->getOrigData());echo '</pre>'; $product = $obj->get('Magento\Catalog\Model\ProductRepository') ->getById($productId); echo '<pre>';print_r($product->getData()); echo '</pre>';

How to clean folder to activate function getting value of custom attribute via rest api?

(var\generation need to be eliminate if want to activate functionsetHelloWorldCustomAttribute() & getHelloWorldCustomAttribute in file var\generation\Magento\Sales\Api\Data\OrderExtension.php which is be auto-built.) public function getHelloWorldCustomAttribute(){ return $this->_get('helloworld_custom_attribute'); } public function setHelloWorldAttribute($helloWorldCustomAttribute){ $this->setData ('helloworld_custom_attribute', $helloWorldCustomAttribute); return $this; }

following graph shows what it consists of:?

* * * * * command to be executed | | | | | | | | | +----- Day of week (0 - 7) (Sunday=0 or 7) | | | +------- Month (1 - 12) | | +--------- Day of month (1 - 31) | +----------- Hour (0 - 23) +------------- Minute (0 - 59)

DESCRIBE MAGENTO'S MODULE-BASED ARCHITECTURE?

**Five areas: adminhtml, frontend, base, webapi_rest, webapi_soap & cron. cron used when running cron jobs. **Three necessary files: to bootstrap a module registration.php, etc/module.xml & composer.json.

What is UI Bookmark Component structure?

*Collection:\Magento\Ui\view\base\web\js\grid\controls\bookmarks\bookmarks.js Template:\Magento\Ui\view\base\web\templates\grid\controls\bookmarks\bookmarks.html *Child:\Magento\Ui\view\base\web\js\grid\controls\bookmarks\view.js Template:\Magento\Ui\view\base\web\templates\grid\controls\bookmarks\view.html

How to add Index to table column using Magento 2?

->addIndex($installer->getIdxName('table_name', ['table_field']),['table_field'] ) (using InstallSchema or UpgradeSchema.php)

How to Get Order Shipping Information in Using Object Manager?

// Fetch whole shipping information print_r($order->getShippingAddress()->getData()); // Fetch specific shipping information echo $order->getShippingAddress()->getCity(); || ->getRegionId(); || ->getCountryId();

How to Update customer info customer info by email/ID is $customerRepository?

// Update customer info $customer->setFirstname('Roni'); $customer->setLastname('Cost'); $customer->setEmail('[email protected]'); $customer->setCustomAttribute('abc', 'attribute value'); $this->customerRepository->save($customer);

How to load load customer info by email/ID BY $customerRepository?

// load customer info by email $customer = $this->customerRepository->get('[email protected]', $websiteId); // load customer info by id $customer = $this->customerRepository->getById(12);

How to Get current category in template phtml ?

// print current category data if ($currentCategory = $myBlock->getCurrentCategory()) { echo $currentCategory->getName(); ||->getUrl(); }

Step of Magento 2 URL Rewrite programmatically?

1 : Generate constructor file 2 : Insert custom URL rewrite in execute method

How to enable persistent cart in Magento 2?

1. Admin>Stores>Configuration>Customers>Persistent Shopping Cart. 2. Leave check box Use system value empty 3.Choose "Yes" 4.Set time 5.Enable Remember Me 6.optional default option "Remember Me" 7.Set "No" option for Clear Persistence on Sign Out to ensure 8. Save to enable (In Persist Shopping Cart field, select "Yes" if want to keep persistent cookie when session cookie expires)

How to override controller in Magento2

1. Create MyMod/etc/di.xml (<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">) <preference for="Magento\Catalog\Controller\Product\View" type="MyMod\Controller\Rewrite\Product\View" /> </config> 2. create controller (MyMod\Controller\Rewrite\Product\view.php ) (namespace MyMod\Controller\Rewrite\Product;) class View extends \Magento\Catalog\Controller\Product\View{ public function execute(){ //Do here return parent::execute();} }

What are important new features in Magento 2.3?

1. PWA-Progressive( Web App), 2. Asynchronous( web API) , 3.Message (Queue), 4.GraphQL , 5.RabbitMQ , 6.Libsodium , 7.Klarna Integration, 8.Declarative (Database Scheme), 9.Cache Management ACL, 10.Google reCAPTCHA, 11.Multi stock (inventory) 12.Business Friendly (page builder) 13.Two factor (authentication) 14.Support elastic search 15.Amazon (3rd party sales)

Prompt Widget Options?

1. actions 2. autoOpen 3. clickableOverlay 4. content 5. focus 6. title

Which situations of Magento 2 components including composer.json ?

1. to install via composer as well Component Manager can update/uninstall/enable/disable component. 2. if includes composer.json file but doesn't need to install via composer such as customization of written codes by a developer, Component Manager can still enable/disable component.

What is responsibility etc/module.xml?

1.Adds static list of components in \Magento\Framework\Component\ComponentRegistrar. Once it is there, Magento will look for etc/module.xml 2.Specifies setup version & loading sequence for module 3.Sequence tells Magento (vendor/magento/framework/Module/ModuleList/Loader.php) in which order to load modules

need to add Google Tag Manager (GTM) to every page. What three steps do take to accomplish this in MyCompany_MyModule?

1.Create view/frontend/layout/default.xml. 2.Add into view/frontend/layout/default.xml. 3.Create view/frontend/templates/script.phtml & add GTM code.

What Benefits allows for a module developer Interception plugin?

1.Forwarding any method (call object manager controlled object & taken programmatic action) 2.Modifying return value of any method (call object manager controlled object). 3.Modifying arguments of any method (call object manager controlled object). 4.Proceeding similarly when other modules in progress of same method in same/predictable way.

Explain enable or disable module which has dependencies on another module?

1.If Module A depends on B: 1.1 Required to disable Module A before disabling B. 1.2 Required to enable Module B before enabling A if both are unavailable. 2.If Module A conflicts with B, can disable both of them or do that individually, but cannot enable both at same time.

If module A depends on module B: ?

1.required to disable module A before disabling module B. 2. required to enable module B before enabling module A if both are unavailable.

How to Convert Custom Field From Quote Item to Order Item?

1: Add a di.xml file 2: Identify a code, a plugin 3: Add a class to your module, then identify a function

Write step Overview of getting value of custom attribute via rest api?

1: Add column & set value for existing order 2: Add a specific new file 3: Add an observe 4: Add a file to handle event 5: Clear folder to activate function

How to change product price with Plugin step only?

1: Add di.xml file 2: Change product price 3: Flush Cache & Test

What step of getting product options in Magento 2?

1: Add object manager 2: Generate product 3: Custom options 4: Configurable Options 5: Grouped Childs 6: Bundle selection

What step of adding top link in Magento 2?

1: Add/modify default.xml 2: Add Link.php 3: Flush cache & test Top link result

Write step of Upgrade Magento 2?

1: Backup your store 2: Turn on maintenance mode 3: Upgrade to Magento 2 4: Check current version

What steps are Overview of getting stock items list in Magento 2?

1: Collection stock item from Resource Model 2: Take Resource Model of StockItem 3: Set select query

What step of calling children in Magento 2 template knockout?

1: Create 2 children: child_a & child_b in layout of template 2: Declare all children in list.html

How to customize a checkout step in Magento 2?

1: Understand example from Devdocs document 2: Add new Newsletter Register component 2.1: Create a js file 2.2: Create template html file 2.3: Add component to checkout page's layout 2.4: Disable newsletter register component 2.5: Remove component

Write step of retrieving size of product image?

1: Upload product 2: Get size of product image

Write step of Create API with samples file Magento 2 ?

1: etc/webapi.xml 2: etc/di.xml 3: Model/PostManagement.php 4: Api/PostManagementInterface.php

Magento 2: How to add a new step in Checkout page?

1:Create .js implementing view model 2:|| .html template component 3:Add step to Checkout layout

How many arguments receive Dispatch event code in Magento 2 Create Events - Observer in Magento 2?

2 arguments: an unique event name & an array data.add data object to event & call it back to display text.

How many divide layer in Magento 2 MVVM?

3, Model: Logic of data management & a description of fundamental data, necessary for operation of application. View: Graphical interface ( e.g. windows, buttons, etc. ) View Model:Abstraction of view exposing public properties & commands. (Contains a Model that is converted to a View & also contains commands that View can use to influence Model.)

How steps to creating a widget in Magento 2?

4 ; 1: Declare widget 2: Create a widget template file 3: Create widget Block class 4: Flush cache & posts

How many layers split according to official documentation Magento 2?

4 Layers: 1.Presentation: upper layer contains all View elements (including layouts, blocks, templates, css, js & controllers.) 2.Service : interlayer between presentation layer & domain layer. 3.Domain: responsible for business logic 4.Persistence: describes resource model, which is responsible for extracting & modifying data in db using CRUD requests.

How many Steps to create configurable product programmatically?

4, 1: To create Simple product programmatically 2: Add an image to product 3: Add custom options to product 4: How to assign associated products

How many directory consists on App ?

4: Design,code ,etc ,i18n

Magento 2 7 Basic directories?

7: app, bin, dev, lib, pub, var, vendor

How Declare widget?

:etc/widget.xml <widget class="My\Mod\Block\Widget\Posts" id="my_mod_posts"> <label>Blog Posts</label><description>Posts</description> <parameters><parameter name="posts" sort_order="10" visible="true" xsi:type="text"> <label>Custom Posts Label</label></parameter> </parameters> </widget> </widgets>

Declare all children in file list.html calling children in Magento 2 template knockout?

<!- ko foreach: elems() -> <!- ko template: getTemplate() -><!- /ko -> <!- /ko -> (Or do for "child a" & "child b" separately as following: Declare "child a" in file list.html via code snippet:) <div data-bind="scope: requestChild('child_a')"> <!-- ko template: getTemplate() --><!-- /ko --> </div> (Then, declare "child b" via displayArea in file list.html by command below:) <!- ko foreach: getRegion('child_b') -> <!- ko template: getTemplate() -><!- /ko -> <!- /ko ->

How to Create payment method module registration.php?

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

How registration.php file should look like?

<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::THEME, 'frontend/mageplaza/ultimate', __DIR__ );

add new class Product.php code change product price with Plugin in Magento 2?

<?php namespace My\Mod\Plugin; class Product{ public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result){ return $result + 100; } }

Get base URL & current URL in template file?

<?php echo $block->getUrl('hello/test').$block->getBaseUrl(); ?>

What are two methods in component Root directory location?

<M2>/app, <M2>/vendor

Where All modules status are available? what happen when enable/disable modules?

<Root >/app/etc/config.php enable/disable modules, module status will be updated in this file. ( Status: 1 => Enabled, 0 => Disabled ).

How to create simple shipping method config.xml file?

<carriers><simpleshipping><active>1</active><sallowspecific>0</sallowspecific> <model>Mageplaza\Simpleshipping\Model\Carrier\Shipping</model> <name>Sample Shipping Method</name><price>10.00</price> <title>Sample Shipping Method</title> <specificerrmsg>This shipping method is not available..</specificerrmsg> <handling_type>F</handling_type></simpleshipping></carriers> </default> </config>

How Sticky is applied for display of grid with configuration code?

<container name="sticky"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <||="component" xsi:type="string"> (Magento_Ui/js/grid/sticky/sticky)</||> <||="toolbarProvider" xsi:type="string">...</||> <||="listingProvider" xsi:type="string">...</||> </||> </argument> </container>

What content code events.xml of Create Events - Observer in Magento 2?

<event name="my_mod_display_text"> <observer name="mp_display_text" instance="My\Mod\Observer\ChangeDisplayText" /> </event> </config>

What structure category attribute category_form.xml ?

<fieldset name="general"> <||="mp_new_attribute"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <||="required" xsi:type="boolean">false</item> <||="validation" xsi:type="array"> <||="required-entry" xsi:type="boolean">false</item> </item> <||="sortOrder" xsi:type="number">333</item> <||="dataType" xsi:type="string">string</item> <||="formElement" xsi:type="string">input</item> <||="label" translate="true" xsi:type="string">Mageplaza new attribute</item> </item> </argument> </field> </fieldset> </form>

How To Validate Form create a test form code in Magento 2?

<form class="form" id="custom-form" method="post" autocomplete="off"> <fieldset class="fieldset"> <legend class="legend"><span><?php echo __('Personal Information') ?></span></legend><br> <div class="field required"> <label for="email_address" class="label"><span><?php echo __('Email') ?></span></label> <div class="control"> <input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}"> </div> </div> </fieldset> <div class="actions-toolbar"> <div class="primary"> <button type="submit" class="action submit primary" title="<?php echo __('Submit') ?>"><span><?php echo __('Submit') ?></span></button> </div> </div> </form>

What is crontab.xml Content would be?

<group id="default"> <job instance="MyMod\Cron\Test" method="execute" name="my_mod_cron"> <schedule>* * * * *</schedule> </job> </group> </config>

How Declare payment method module etc/payment.xml?

<groups><group id="offline"> <label>Offline Payment Methods</label></group> </groups> <methods><method name="simple"> <allow_multiple_address>1</allow_multiple_address></method> </methods> </payment>

Create Indexer configuration file?

<indexer id="my_mod_indexer" view_id="my_mod_indexer" class="My\Mod\Model\Indexer\Test">) <title translate="true"> My Mod Indexer</title> <description translate="true"> MyMod of custom indexer </description> </indexer> </config>

Where create simple shipping method configuration/system.xml?

Now create system.xml file at app/code/My/Simpleshipping/etc/adminhtml/system.xml

How to Create payment method module Declare module.xml file?

<module name="Mageplaza_Payment" setup_version="0.1.0"> <sequence> <module name="Magento_Sales"/> <module name="Magento_Payment"/> <module name="Magento_Checkout"/> <module name="Magento_Directory" /> <module name="Magento_Config" /> </sequence> </module> </config>

How declare payment method module etc/config.xml?

<payment> <simple> <active>1</active> <model>Mageplaza\Payment\Model\Payment\Simple</model> <order_status>pending</order_status> <title>Simple</title> <allowspecific>0</allowspecific> <group>Offline</group> </simple> </payment> </default> </config>

Write controller/action file di.xml & add code?

<preference for="Magento\Customer\Controller\Account\Create" type="MyMod\Controller\Account\Create" /> </config>

What is API content File: etc/di.xml?

<preference for="My\Mod\Api\PostManagementInterface" type="My\Mod\Model\PostManagement"/> </config>

How Generate file: sales_email_order_items.xml?

<referenceBlock name="order_totals"> <block class="My\Mod\Block\Order\Totals" name="new.order.totals" /> </referenceBlock> </body> </page> <referenceBlock name="order_totals"> <block class="My\Mod\Block\Order\Totals" name="new.order.totals" /> </referenceBlock> </body> </page>

How to Call CMS Static Block in Phtml File via Display CMS Static Block In XML?

<referenceContainer name="content"> <block class="Magento\Cms\Block\Block" name="block_identifier"> <arguments> <argument name="block_id" xsi:type="string">block_identifier</argument> </arguments> </block> </referenceContainer>

How to declare a route & layout handle for this action?

<route frontName="helloworld" id="helloworld"> url:example.com/helloworld/controller/action LayoutAction:helloworld_controller_action.xml ActionClass:{namespace}/{module}/Controller/{Controller}/{Action}.php

What is API content File: etc/webapi.xml?

<route method="GET" url="/V1/my-mod/post"> <service class="My\Mod\Api\PostManagementInterface" method="getPost"/> <resources> <resource ref="anonymous"/> </resources> </route> </routes>

How to create custom route on admin routes.xml content?

<router id="admin"> <route id="my_mod" frontName="my_mod"> (// module which this route match to) <module name="My_Mod"/> </route> </router> </config>

Create custom route on frontend Routes.xml file content?

<router id="standard"> <route frontName="helloworld" id="helloworld"> <module name="Mageplaza_HelloWorld"/> </route> </router> </config>

block of code inside <config> tag rewrite controller in Magento 2?

<router id="standard"> <route id="mageplaza" frontName="hello"> <module name="Mageplaza_HelloWorld" before="Magento_Customer" /> </route> </router> </config>

How theme.xml file should look like?

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../lib/internal/ Magento/Framework/Config/etc/theme.xsd"> <title>Session Default</title> <parent>Magento/blank</parent> </theme>

Define command in di.xml?

<type name="Magento\Framework\Console\CommandList"> <arguments> <argument name="commands" xsi:type="array"> <item name="exampleSayHello" xsi:type= "object"> MyMod\Console\Sayhello </item> </argument> </arguments> </type> </config>

How to add a custom Zipcode validator in checkout page Magento 2?

<zip countryCode="NL"><codes> <code id="pattern_1" active="true" example="1234 AB">^[0-9]{4}\s[a-zA-Z]{2}$</code> <code id="pattern_2" active="true" example="1234AB">^[0-9]{4}\s?[a-zA-Z]{2}$</code> </codes></zip> </config>

You're tasked with investigating a custom page layout declared in MyCompany/MyModule that isn't loading. You've determined that this is result of your XML configuration. Which 2 files do investigate to locate issue?

A.My/Mod/view/frontend/layouts.xml B.|| /page_layout/custom.xml

What do mean by HTTP Error 403?

Access denied. Constant: Magento\Framework\Webapi\Exception::HTTP_FORBIDDEN

How to add class Product change product price with Plugin in Magento 2?

Add class "MyMod\Plugin\Product.php. put prefix "after" before one of two ways to change product price: Edit values reported by an original method Call some behaviors once an original method is called. And result when original method getPrice() finishes is declared by $result. (For example, will adjust product price by multiply it with 2.)

How to add js file to Magento 2?

Add javascript file name in Theme/requirejs-config.js , declare file requirejs-config.js

How to add custom js file in require js file magento 2 custom modules?

Add name in "mymodule/requirejs-config.js" file in module at path "app/code/Webkul/Test/view/frontend".

Add new column & set value for existing order getting value of custom attribute via rest api?

Add new column & set value for existing order To get a custom attribute, first thing is inserting a new column that is called as my-mod-custom_attribute in table sales_order & setting value for existing orders

From where in admin panel we can enable/disable cache?

Admin->System->Tools->Cache Management

How many different areas to create configuration files for events?

Admin: MyMod/etc/adminhtml/events.xml Frontend: MyMod/etc/frontend/events.xml Global:MyMod/etc/events.xml

Understand Catching & handling a event file path?

Admin:My/Mod/etc/adminhtml/events.xml Frontend:My/Mod/etc/frontend/events.xml Global:My/Mod/etc/events.xml

How to create a Magento 2 Backup from admin?

Admin=>System=>Tools section=>Backups=>System Backup/Database & Media Backup/ Database Backup, tap button for type of backup want to create

Prompt Widget Options focus?

Allow focusing on selector of element if prompt window opens. In case focusoption is not specificed or empty, focus is on close button & if focus is optional, please set focus to none. Type: String. Default value: ''

Sticky Header Component in Magento 2?

Allows keeping Header on fixed top during scrolling , supported by Sticky, one of popular effect can set for header in website. With sticky header component, it is easier for better tracking. Specifically, as go to product management workplace, will see sticky header component

Waht do mean by HTTP Error 401?

Authorization Failed. Constant: Magento\Framework\Webapi\Exception::HTTP_UNAUTHORIZED

Prompt Widget Options autoOpen?

Automatically open prompt window when widget is initialized. Type: Boolean Default value: false

What is BEM?

BEM style naming methodology which allows effectively scopes your CSS so only use cascade then actually want to. .block {} .block__element {} .block--modifier {}.site-search {} (// Block ) .site-search__field {} (//Element ) .site-search--full {} (// Modifier ) (.block represents higher level of an abstraction or component. .block__element represents a descendent of .block that helps form .block as a whole. .block-modifier represents a different state or version of .block. It is a smart way of naming your CSS classes to give them more transparency & meaning to other developers. They are far more strict & informative, which makes BEM naming convention ideal for teams of developers on larger projects that might last a while. <form class="site-search site-search--full"> <input type="text" class="site-search__field"> <input type="Submit" value ="Search" class="site-search__button"> </form>)

How would implement icons in Magento 2?

Based on fonts as Magento recommend or svg files

A merchant would like to manually specify order of products per category. How is this done?

There is a position field on category management page which allows to define order of a product in category.

Describe Module Sequence Cases?

Case 1: Files-Loaded from various components while sequence information in each component's module.xml. Case 2: To load a list of layout files with name default.xml & component designates component B in <sequence>,(load order: 2.1: component X /view/frontend/layout/default.xml — Either we don't care about when component X loads or perhaps component B requires it to be loaded before it. 2.2: component B /view/frontend/layout/default.xml 2.3: component A /view/frontend/layout/default.xml —Loads after component B because component B is listed in component A's tag 2.4: component Z /view/frontend/layout/default.xml — Either we don't care about sequence for component Z or perhaps component Z requires component A files to be loaded before it.)

Object manager - Dependency Injection Container?

Class contains & handle dependencies between objects, Class construction injects appropriate dependency as defined in di.xml. (Object Manager/Dependency Injection Container: )

How to Prompt Widget Options clickableOverlay?

Close prompt window when a user clicks on overlay. Type: Boolean Default value: true

Set a Collection class joining data between 2 tables in Magento 2?

Collection class extends: \M\F\Model\ResourceModel\Db\Collection\AbstractCollection class Collection extends:\M\F\Model\ResourceModel\Db\Collection\AbstractCollection

Describe layout file processing in Magento 2.

Collects all layout from modules by modules order in module list from app\etc\config.php, Determines sequence of inherited themes( [<parent_theme>, ..., <parent1_theme>] <current_theme>) Iterates sequence of themes from last ancestor to current theme: Adds all extending theme layout to list. Replaces overridden layout in list. Merges all layout from list.

What is UI component in Magento2?

Combination of: 1. XML declaration: specifies component's configuration settings & inner structure. 2. JavaScript class inherited from one of Magento JavaScript framework UI components base classes (such as UIElement, UIClass or UICollection). 3. Related template(s)

Where is Magento 2 modules contained?

Completely contained within module's directory (ie. app/code/My/Mod).

What do mean Magento 2 is PSR-0 compliant?

Composer still uses this idea to assist in autoloading classes. In /composer.json (in root folder), there should be a "psr-0" node.

What does "minification" do?

Compresses files by removing whitespace, comments & such. Most used for CSS- & JS-files.

Resource Model Collection - Get Model Collection?

Considered a resource model which allow us to filter & fetch a collection table data. placed in: MyMod\Model\ResourceModel\Topic\Collection.php

What directory consists on App/code ?

Contains installed modules (installing via composer files will be located /vendor).

new Magento 2 module including?

Controllers Models Blocks Template files Plug in Observer Console scripts Product attribute.

controller & action in your module must have same name with rewrite controller/action file location?

Create My/HelloWorld/etc/di.xml & add code below.

Where Create Observer class in Magento 2?

Create a class to execute above event. File:app/code/My/Mod/Observer/ChangeDisplayText.php

When need to Create Customer Programmatically Magento 2 ?

Create a huge number of new customers coming from multiple addresses (city, state/ province, country) & send them to different customer groups at same time, given to developers to work directly with code.(Fill full of information into registration form in backend )

How to Create widget Block class?

Create block file: Block/Widget/Posts.php <?php namespace My\Mod\Block\Widget; use Magento\Framework\View\Element\Template; use Magento\Widget\Block\BlockInterface; class Posts extends Template implements BlockInterface { protected $_template = "widget/posts.phtml"; }

How to Create cron job?

Create crontab.xml: mod/etc/crontab.xml

need to control access to a custom controller action.How do tell Magento about this new control option?

Create etc/acl.xml & add <resource id="MyCompany_MyModule::customAction" ... />

What is Database & Media Backup?

Creates a backup of database & media folder.

What is Database Backup?

Creates a backup of database.

What is System Backup?

Creates a complete backup of database & file system. During process can choose to include media folder in backup by marking Include Media folder to System Backup checkbox

What is a Cron Job Magento 2?

Cron configuration is very important to set schedule for many system activities such as reindexing, auto-update of currency rates, emails, etc. Only when configuration is correct, cron job is active. In case of making an error, this means M2 won't function as expected.

What is Magento 2 Routing?

Define name for a module which can use in url to find module & execute controller action.

Declaring a plugin in Magento 2?

Defined at app/code/{namespace}/{module}/etc/di.xml. <config> <type name="{ObservedType}"> <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false"/> </type> </config>

How do different modules interact with each other?

Dependency injection (di.xml) & layout files (/view/frontend/layout, /view/adminhtml/layout), depend on other modules if use their logic.

Overview of Magento 2 Composer?

Dependency management for PHP. gathering components & product editions. no requirement of storing all code of each component, only need to create composer.json file & declare needed components in that file instead that will auto-define & take corresponding data of those components to run project.

How easily can upgrade Magento 2 ?

Dependency management tool call Composer to handle this.

What is EAV in Magento?

Entity Attribute Value technique which allows to add unlimited columns to table virtually as object attribute value model & open schema. Entity (E): Entity actually refers to data item.( For example we can consider it as customer, category or product.) Attribute (A):Attribute refers to different attributes of Entity.( Like for example product have different attributes like color, size, price, etc.) Value (V):Value refers to actual value of attribute of entity. (Like color has value red, price has value $25, etc.)

Talk about Magento 2 Events?

Events driven architecture which will help too much to extend functionality, as a kind of flag that rises when a specific situation happens

What side effects can come from interaction?

Fallout can happen (Any time are working with a system where any installed module can extend core functionality)

Magento 2 can execute single numbers of observers for a single event trigger.(True/False)

False ( multiple numbers)

<sequence> tag can mention any valid component without any limitation & besides, also no need component is declared in require section of composer.json file. (True/False)

False(sure component is declared in require section of composer.json)

What task done by events.xml of Create Events - Observer in Magento 2?

File under config element, define event element with name is event name which was dispatch class which will execute this event will be define in observer element by instance attribute. name of observer is used to identify this with other observers of this event. events.xml file, will execute class (My\Mod\Observer\ChangeDisplayText whenever dispatch method of this event was called on frontend area. Please note that, we place events.xml in frontend area, so if dispatch that event in admin area like admin controller, it will not run.)

Where Create a event file to Create Events - Observer?

File: MyModPath/etc/frontend/events.xml

How Create a widget template file?

File:view/frontend/templates/widget/posts.phtml <?php if($block->getData('posts')): ?> <h2 class='posts'><?php echo $block->getData('posts'); ?></h2> <p>This is sample widget. Perform code here.</p> <?php endif; ?>

How would overwrite colour of button or link in Magento 2?

Find certain variable & overwrite it in _theme.less

Have ever worked with Flexbox? What is this? How it is related to Magento 2?

Flexbox (Flexible Box Layout Module):Control size, order & alignment of elements by several axes, as well as distribute free space between elements & do many other things. (Magento 2 doesn't come with a grid system like Twitter Bootstrap. A lot of elements does not have a template used as a wrapper instead they are wrapped using a container in xml, for example header & footer. There are some different approaches on how to work without grid systems but a lot of current projects are using flexbox for parts of layout .Grid systems are implemented by third party modules.)

How many Step to enabling/ disabling Magento 2 module?

Four: 1:Login to Magento File System 2:Run Magento commands 3:Enable/Disable module 4:Update database enabled module

Add a file to handle event getting value of custom attribute via rest api?

Generate a file app\code\Mageplaza\HelloWorld\Observer\Sales\OrderLoadAfter.php that to mange event sales_order_load_after in previous step.

How to generate product getting product options in Magento 2?

Generate product that need to be assigned custom options. $product = $_objectManager-> get('\Magento\Catalog\Model\Product')->load($id);

What version control systems used?

Git, Subversion, Mercurial & so on

How to Flush cache & posts?

Go to admin panel > Content > Pages > Home page > Edit In Content tab, click on Insert Widget icon

Where create template of form?

HTML template custom-checkout-form.html for form component under ModulePath/view/frontend/web/template

What do means Create API Magento 2 ?

Helping online retailers generate set of routines, protocols & other tools to design software applications. Required element to connect among data any program/service from other websites, easily get all building blocks to initiate a program successfully.

phtml: echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('block_identifier')->toHtml(); CMS Block: {{block class="Magento\Cms\Block\Block" block_id="block_identifier"}}

How to show cms static block from template phtml?

What is side effects from interaction between modules?

If modules use Dependency injection, can load in wrong order or try to redefine already redefined functionality of module. To solve this problem, should use sequence in module.xml.

How many folder module-based architecture keeps that module's files?

In One Folder

Where cron test script create?

In crontab.xml, defined job instance: MyMod\Cron\Test.php

How to add new js file to Magento 2 theme?

In root of theme add requirejs-config.js & then declare new javascript file in requirejs-config.js

What is responsibility registration.php?

Included by Composer autoloader (app/etc/NonComposerComponentRegistration.php)

What does following code mean? //@magento_import 'source/_module.less'; // Theme modules //@magento_import 'source/_widgets.less'; // Theme widgets

Includes all _module.less & _widgets.less from all modules into less file. @magento_import is a Magento-specific less directive that enables to include multiple files by a name pattern, include files with same name from different locations;

What will be effect of following overwriting template: vendor/magento/module-review/view/frontend/templates/helper/summary_short.phtml -> /app/design/frontend/Vendor/example/module-review/{view/frontend/}templates/helper/summary_short.phtml

It will not work. need to replace module-review with Magento_Review & we have to cut off /view/frontend/ part

Module components explanation?

Items Model allows creating, editing or deleting module items. Cron Model allows implementing multiple cron options. Block & Controller Adminhtml/Items allows showing parts of Item collection in Admin Panel.

Which function refers action in any controller file?

Its execute() function.

Which file stores vendor path?

Its vendor_path.php situated at app/etc/ folder.

Describe important differences in layout xml between Magento 1 & Magento 2

Layout files are merged in M2 no local.xml in themes in M2. In some cases layout files need to be overridden, this can be done by adding an override folder inside layout Files in web or templates are not merged - additional answer

What is UI Bookmark Component?

Listing/Grid Secondary Component UI Bookmark Component charge of storing all active & changed states of data grids, cover some of data including state of filters, columns position, applied sorting, pagination & so on.

What is Magento 2 Plugin - Interceptor?

Little extension allows editing behavior of any public class or method by intercepting a function call & running code either before/after/around function call. Also can modify behavior of a class while there is no need to change class directly.

What will be happen Without indexing ?

Loading price for a product would take a long time, possibly resulting in cart abandonment. calculate price of every product on fly—taking into account shopping cart price rules, bundle pricing, discounts, tier pricing, & so on.

What Magento Language Package composer.json files?

Location: app/i18n/<vendor-name>/<language-code>/composer.json Name: <vendor-name>/<package-name> Type: magento2-language For language packages must use correct ISO code for language code in composer.json

What Magento Commerce project composer.json files?

Location: composer.json Name: magento/product-enterprise-edition Type: metapackage (Magento system integrators use this composer.json file to deploy Magento Commerce product & its dependencies.)

What Magento Open Source project composer.json files?

Location: composer.json Name: magento/project-community-edition Type: project (Magento system integrators use this composer.json file to deploy Magento Open Source product & its dependencies.)

What Magento Framework composer.json files?

Location:lib/internal/Magento/Framework/composer.json Name:magento/framework Type:magento2-library application uses this composer.json file for its framework packages.

What Magento Theme composer.json files?

Locations:app/design/frontend/<My>/<Them>/composer.json app/design/adminhtml/My/Them>/composer.json Name: <vendor-name>/<package-name> Type: magento2-theme: composer.json file for a theme component contains parent theme dependencies extension needs to inherit.

Describe differences between M1 & M2 theme files?

M1: app/design skin, layout css, template images, locale js M2: Vendor/themename (or vendor/vaimo/theme-name),Vendor_Modules (eg Magento_Catalog), etc, web, i18n, theme.xml, registration.php

What directory consists on bin?

M2 (CLI) executable files are located;

How works new Magento 2 module ?

M2 Module Creator online tool that provides functionality for generating a new module easily. Start creating a new Module with Create Module button. Fill out module, company name both of which are required fields. Add extra information of module if need.( Click onGenerate to complete creation.can Save & Download to use module then install it on your site.)

What is a different between declaring variables in templates in Magento 1 & Magento 2?

M2's variables used in template shouldn't have underscore "_" in name what is a different comparing to M1.

What are name of different composer.json?

Magento Root || Open Source project || Commerce project || Framework || Module || Theme || Language Package

Where is cms PageFactory?

Magento\Cms\Model\PageFactory $pageFactory

UninstallInterface vendor location?

Magento\Framework\Setup\UninstallInterface;

building an extension that will be sold on Magento marketplace. This mextension depends on Magento_Catalog.How is a Magento database upgrade performed?

Manually on CLI

Write step Overview of rewriting block, model, controller, helper?

Method 1: Using Plugin Block Override Model Override Controller Override Helper Override Method 2: Using Preference Block Override Model Override Controller Override Helper Override

Where knockout.js is used in Magento 2?

Mostly for checkout related functionality: Header cart (minicart) Checkout

Where create simple shipping method shipping model?

MyModPath/Model/Carrier/Shipping.php

Does Magento 2 include Mage?

No, Magento 2 does not include Mage "god" class like its earlier counterpart.

If it is disabled, Is it functional?

No. Keep in mind that disabling a module does not automatically remove its tables or entries in database

What is <sequence> tag?

Notifying what components to loaded before current component is loaded. Especially when implement loading of different types of file such as configuration files, view files (including CSS, LESS & template files,or setup classes).if need to load regular classes (non-setup classes), there is no influence of <sequence> tag on that implementation.

Magento 2 plugin's restriction What options Magento 2 Interception plugin doesn't work with?

Objects that are instantiated before Magento\Framework\Interception is bootstrapped Final methods Final classes Any class that contains at least one final public method Non-public methods Class methods (such as static methods) __construct Virtual types

What is Magento2?

Open source large ecommerce system is Model View View Model (MVVM) architecture. While being closely related to its sibling Model View Controller (MVC), MVVM architecture provides a more robust separation between Model & View layers

Where I can find knockout.js files? How to overwrite them?

Overriding a knockout template is not that different from overriding a template file. Example of overriding shipping template in checkout: Original file: module-checkout/view/frontend/web/template/shipping.html Theme version: <theme_location>/Magento_Checkout/web/template/shipping.html

What is URL Redirect?

Popular term in SEO & used for navigating visitors to any link store owners expect. Two main type of redirect: 301 redirect & 302 redirect.

What is Prompt Widget in Magento 2?

Prompt Widget allows showing a modal pop-up window with an input field & a cancel & confirmation button & it also extends modal widget. origin of prompt widget is <Magento_Ui_module_dir>/view/base/web/js/modal/prompt.js.

How create custom route on frontend Routes.xml file location?

Register a frontend route create a routes.xml, File:MyMod/etc/frontend/routes.xml

Magento 2 Dependency injection?

Replace M1.x Mage class when convert to work with M2 design pattern creates an external environment where can inject dependencies into object no longer to create objects manually. object A calls object or value B, this means B is a dependency of A.

What do mean by HTTP Error 400?

Request Data Invalid. Constant: Magento\Framework\Webapi\Exception::HTTP_BAD_REQUEST

What do mean by HTTP Error 406?

Requested resource doesn't accept request. Constant: Magento\Framework\Webapi\Exception::HTTP_NOT_ACCEPTABLE

What do mean by HTTP Error 500?

Resource Internal Error. Constant: Magento\Framework\Webapi\Exception::HTTP_INTERNAL_ERROR

What do mean by HTTP Error 404?

Resource Not Found Constant: Magento\Framework\Webapi\Exception::HTTP_NOT_FOUND

What is resource attribute for admin menu item?

Resource attribute defines ACL rule, that a user must have in order to access this Menu Item

What do mean by HTTP Error 405?

Resource does not support method/not implemented yet. Constant: Magento\Framework\Webapi\Exception::HTTP_METHOD_NOT_ALLOWED

Magento 2 Dependency Inversion Principle?

Restrict direct working between high & low level classes, interaction will implement via an interface of low level classes as an abstract layer. di.xml mapping an interface dependency to a preferred implementation class. dependency of coding will be reduced significantly due to abstract layer.

What Magento Root composer.json files?

Root: composer.json Name: magento/magento2ce Type: project main composer.json used as a template for every root composer.json to call dependencies on third-party components.

Sale order resource model joining data between 2 tables in Magento 2?

Sale order resource model from Magento sales module protected function _construct(){ $this->_init('Mageplaza\HelloWorld\Model\YourModel', 'Magento\Sales\Model\ResourceModel\Order'); }

Magento 2 Module load order position?

Sequence - load order position is topic to point right load order in component's module.xml. If want to understand dependencies among components using component's composer.json, it is obviously that really need to know correct load order in component's module.xml using <sequence> tag.

How to resolve: "An error has happened during application run. See exception log for details"?

SetEnv MAGE_MODE developer (open .htaccess from root & comment out first line:)

What do mean Magento 2 is PSR-4 compliant?

Standard declares that namespace path will match file path to class. (PSR-4 describes a specification for autoloading classes from file paths."class" refers to classes, interfaces, traits & other similar structures.)

Step Overview of getting store information in Magento 2?

Step 1: Declare in My_HelloWorld Step 2: Get store information in phtml file

How to Create Admin Grid in Magento 2?

Step1: Create database schema Step2: || routes admin Step3: || admin menu Step4: || Controller Step5: || Admin Grid using Component Step6: || Admin Grid using Layout

When there is valid reason to overwrite layout xml?

Suppressing method invocation.( Overriding is not necessary if a block has a method that cancels effect of originally invoked method. In this case, can customize layout by adding a layout file where canceling method is invoked.) Modifying method arguments. Canceling block/container removal using remove directive. Setting XML attributes of blocks & containers.( Certain attributes, such as htmlClass & htmlId label attributes, can be changed in extending layouts.) Removing block arguments.Modifying & suppressing handles inclusion. Removing all handle instructions (by declaring an overriding layout file with an empty handle.)

How To Creat Magento 2 Theme Ultimate?

Theme structure Theme Folder structure Creating a Magento theme folder Declare your theme Composer package registration.php file Creating static files, folders Configure catalog product images Declare Theme Logo Basic layout elements Layout files types & conventions

How to rewrite controller in Magento 2?

To rewrite controller, can do it by using preference. It mean that need to put a rule in router config using before attribute. Open My/Mod/etc/routes.xml insert following block of code inside <config> tag rewrite controller in Magento 2

CRUD collection class must extends from \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection & call _init() method to init model, resource model in _construct() function (true/false)

True (Resource Model Collection)

To run your project fluently, should use composer.json & <sequence> in module.xml file if ensuring that your needed component's logic rely upon another component. (true/false)

True(composer.json & <sequence>)

allowed to rewrite getProduct() function of class Magento\Catalog\Helper\Data (t/f)

True(getProduct() function )

How can get or set values in Magento 2?

Two methods: 1.\Magento\Framework\App\Config\Storage\WriteInterface write config values to database, 2.|| \ScopeConfigInterface read config values from database

How many Places Modules live in Magento2x?

Two places: 1.app/code/CompanyName/ModuleName 2.vendor/vendor-name/module-name

How many required files to initiate a module of Magento2x?

Two: 1.registration.php 2.etc/module.xml

What are Cookies?

Type of document that is used to save all information on browser. when a user visits website & leaves some personal info, cookies allows showing those data if back in next time confident to enhance customer shopping experience.

Prompt Widget Options content?

Type: String.

As are scanning folder in vendor/module-catalog directory, see a directory that is named Ui. What is this folder's purpose?

UI component data providers & component information.

Where is mixin stored?

UI library source files are stored under source/ directory.

How to Reset Magento Admin Password Via phpMyAdmin?

UPDATE admin_user SET password = CONCAT(SHA2('xxxxxxxYourNewPassword', 256), ':xxxxxxx:1') WHERE username = 'admin'; (In above query, xxxxxxx character sequence is a cryptographic salt, it is saved in app\etc\env.php file.)

Which functions involve Functional module>

Update Version Create Frontend Page Create Backend Page Create data module, (Create a 'Backend Model Manager' for add delete) change search this data module. Add new category attribute || customer attribute || product attribute || customer address attribute || sales attribute Run sql in M database || installing php code in M system Add Sales Order Status || Magento Event Collocate M System Configuration Add New Shipping Method || M Widget || M Cron Job || New Order Total (fee or discount) || M Api Configuration Rewrite M Class (Helper , Block , Model & Controller)

How to reset admin password in Magento 2?

Using 3 methods: 1: From user Interface 2: To reset admin password from PhpMyAdmin/Mysql interface 3:Command line interface(CLI)

How do implement validation in Magento 2?

Using predefined classes

How To Validate Form in Magento 2?

Validating a new form is a crucial checking step before do submitation to your local. validation.js file will be used to allowed for inject new validation into that file. Actually, there are many different ways to validate form in Magento 2 with validation.js file.

Write naming conventions of component in Composer?

When creating composer compulsory to use format of namespace: <vendor-name>/<package-name>. Thus, in this part, learn conventions of vendor-name & package-name.

What is Magento 2 Virtual Type?

When running an virtual store , di.xml supports for two types of node which are a node type & a node virtualtype, meanwhile virtualtype is considered as a perfect method instead of type, allows inserting different dependencies into existing classes but not making any change to other classes.

Prompt Widget Options actions?

Widget callbacks. Type: Object. Default value: actions: { confirm: function(){},cancel: function(){}, always: function(){} }

What is widget in Magento 2?

Widget is a greater tool to insert or edit content into a CMS Page Block or Page,

we all will access of Widget in Magento 2.?

Widgets are powerful functionalities in Magento 2 configuration. As a store admin, can take advantage of widget to improve storefront under lively interface. widgets allow showing static information or dynamic content marketing. I want to illustrate some of implementations of Magento widgets such as: Dynamic product data Dynamic lists of recently viewed products Promotional banners Interactive navigation elements & action blocks Dynamic flash elements that are inserted in content pages

Catalog/Customer/Checkout Sessions, it is possible to set them from .phtml?

Yes.

How to create Observer Magento 2 Events?

class ChangeDisplayText implements \Magento\Framework\Event\ObserverInterface{ public function execute(\Magento\Framework\Event\Observer $observer){ $displayText = $observer->getData('mp_text'); echo $displayText->getText() . " - Event </br>"; $displayText->setText('Execute event successfully.'); return $this; } }

How to class implements ObserverInterface ?

class Data implements ObserverInterface{ public function execute(Observer $observer){ $product = $observer->getProduct(); $originalName = $product->getName(); $modifiedName = $originalName . ' - Modified by Magento 2 Events & Observers'; $product->setName($modifiedName); } }

where Create a controller to delete cookie content?

class Deletecookie extends \Magento\Framework\App\Action\Action{ protected $_cookieManager; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager ){ $this->_cookieManager = $cookieManager; parent::__construct($context); } public function execute(){ $this->_cookieManager->deleteCookie( \My\Mod\Controller\Cookie\Addcookie::COOKIE_NAME); echo('DELETED'); } }

How to around - aroundDispatch() methods in Plugin?

class ExamplePlugin{ public function afterGetTitle (\MyMod\Controller\Index\Example $subject, $result){ echo __METHOD__ . "</br>";return '<h1>'. $result . 'Mageplaza.com' .'</h1>';} }

What is before - beforeDispatch() methods in Plugin?

class ExamplePlugin{ public function beforeSetTitle (\MyMod\Controller\Index\Example $subject, $title) { $title=$title." to "; echo __METHOD__ . "</br>";return [$title];} }

Write lines code of InstallSchema.php to create product attribute programmically?

class InstallData implements InstallDataInterface{ private $eavSetupFactory; public function __construct(EavSetupFactory $eavSetupFactory){ $this->eavSetupFactory = $eavSetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'sample_attribute',[ 'type' => 'text', 'backend' => '', 'frontend' => '', 'label' => 'Sample Atrribute', 'input' => 'text', 'class' => '', 'source' => '', 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL, 'visible' => true, 'required' => true, 'user_defined' => false, 'default' => '', 'searchable' => false, 'filterable' => false, 'comparable' => false, 'visible_on_front' => false, 'used_in_product_listing' => true, 'unique' => false, 'apply_to' => '' ] ); } }

Create Category Attribute Programmatically?

class InstallData implements InstallDataInterface{ private $eavSetupFactory; public function __construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory = $eavSetupFactory; } public function install( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) { $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Category::ENTITY, 'mp_new_attribute', [ 'type' => 'varchar', 'label' => 'Mageplaza Attribute', 'input' => 'text', 'sort_order' => 100, 'source' => '', 'global' => 1, 'visible' => true, 'required' => false, 'user_defined' => false, 'default' => null, 'group' => '', 'backend' => '' ] ); } }

Add Link.php file adding top link in Magento 2?

class Link extends \Magento\Framework\View\Element\Html\Link{ protected function _toHtml(){ if (false != $this->getTemplate()) { return parent::_toHtml();} return '<li><a ' . $this->getLinkAttributes() . ' >' . $this->escapeHtml($this->getLabel()) . '</a></li>'; } }

Write class magento 2 Dispatching events?

class MyClass{ private $eventManager; public function __construct(\Magento\Framework\Event\Manager $eventManager) { $this->eventManager = $eventManager; } public function something() { } }

How to add a file to handle event class getting value of custom attribute via rest api?

class OrderLoadAfter implements ObserverInterface{ public function execute(\Magento\Framework\Event\Observer $observer){$order = $observer->getOrder(); $extensionAttributes = $order->getExtensionAttributes(); if ($extensionAttributes === null) { $extensionAttributes = $this->getOrderExtensionDependency(); } $attr = $order->getData('mod_custom_attribute'); $extensionAttributes->setMyModCustomAttribute($attr); $order->setExtensionAttributes($extensionAttributes); } private function getOrderExtensionDependency() { $orderExtension = \Magento\Framework\App\ObjectManager::getInstance()-> get('\Magento\Sales\Api\Data\OrderExtension'); return $orderExtension; } }

What is API content File: Model/PostManagement.php ?

class PostManagement { public function getPost($param){ return 'api GET return $param ' . $param; } }

Where from Readcookie extends?

class Readcookie extends \Magento\Framework\App\Action\Action

Where content Observer/SalesOrderInvoicePay.php creating invoice programmatically in Magento 2?

class SalesOrderInvoicePay implements ObserverInterface{ public function execute(EventObserver $observer){ $invoice = $observer->getEvent()->getInvoice(); $order = $invoice->getOrder(); $order->setTotalPaid($order->getTotalPaid() - $invoice->getGrandTotal()); $order->setBaseTotalPaid($order->getBaseTotalPaid() - $invoice->getBaseGrandTotal()); } }

Create command class?

class Sayhello extends Command{ protected function configure(){ $this->setName('example:sayhello'); $this->setDescription('Demo command line'); parent::configure(); } protected function execute(InputInterface $input, OutputInterface $output){ $output->writeln("Hello World"); } }

How Dispatch event Magento 2 Events?

class Test extends \Magento\Framework\App\Action\Action{ public function execute(){ $textDisplay = new \Magento\Framework\DataObject(array('text' => 'Mageplaza')); $this->_eventManager->dispatch('mageplaza_helloworld_display_text', ['mp_text' => $textDisplay]); echo $textDisplay->getText(); exit; } }

Create Indexer class?

class Test implements \Magento\Framework\Indexer\ActionInterface, \Magento\Framework\Mview\ActionInterface{ public function execute($ids){ //code here! } public function executeFull(){ //code here! } public function executeList(array $ids){ //code here! } public function executeRow($id){ //code here! } }

Where Totals extends from new ordarTotal?

class Totals extends \Magento\Framework\View\Element\AbstractBlock

What is mixin?

class contains a combination of methods from other classes.

What is JavaScript mixins?

class whose methods are added or mixed in with another class. A base class includes methods from a mixin instead of inheriting from it, allows to add to or augment behavior of base class by adding different mixins to it.

How using Plugin rewriting block, model, controller, helper?

clever choice to rewrite block, model, controller, helper in M2. With Plugin, can execute code before, after & around code/target class's function. Without replacing just inserting some code before/after core code & then observe core/target class's function & run code in-between core/target class's function. it is possible to plugins from multiple modules to insert their own code before/after/around same core/target class's function.

How to Pull package?

composer require magento/product-community-edition 2.2.1 --no-update composer update

How controller work?

controller is folder inside Controller folder. action is a class with execute method to process request. One of important in Magento system is frontController (Magento\Framework\App\FrontController), it alway receives request then route controller, action by route_name ex: foreach ($this->_routerList as $router) { try { $actionInstance = $router->match($request); ... } (http://example.com/route_name/controller/action route_name is a unique name which is set in routes.xml.)

What is a Cron Job?

create a command or a script that is appropriate with task want to do. Instead of manual working, cronjob allows running automatically in exact time & date. (Due to its automation, cron jobs is perfect choice for repeated projects every date or every week.)

Creating VirtualType in Magento 2?

creating a sub-class for an existing class. All are available to help create virtualtype in Magento 2.

What is Unit Test in Magento 2?

crucial operation, a set of smallest testable parts of an application, which are called as units in development of a software ensure that codes wrote running correctly as well as raise software's quality created before process is separate & completely automatic without any manual handling.

Where Create form UI component?

custom-checkout-form in MyMod/view/frontend/web/js/view directory.

How can get customer collection in Magento 2?

customerCollection = $customer->getCollection();

what directory consists on App/design ?

design is used for themes of webstore;

What directory consists on dev?

dev is a directory for test Magento scripts

Magento 2: Get Base URL, Store URL & Current URL?

echo $block->getBaseUrl(); (// to get base URL) || ->getLinkUrl(); (// to get link URL) || ->getMediaUrl(); ( // to get media URL) || ->getStaticUrl(); (// to get static URL) || ->getCurrentUrl(); (// to get current URL) || ->getBaseMediaDir(); (// to get media directory path) || ->getBaseStaticDir(); (// to get static directory path)

How Checkout session will show quote information?

echo $block->getCheckoutSession()->getQuoteId(); print_r($block->getCheckoutSession()->getQuote()->getData());

Get output of currency data in phtml file?

echo $block->getCurrentCurrencySymbol(); || ->getCurrentCurrencyCode(); || ->getBaseCurrencyCode(); || ->getDefaultCurrencyCode(); || ->getCurrentCurrencyRate(); print_r($block->getAvailableCurrencyCodes()); print_r($block->getAllowedCurrencies());

How to Call CMS Static Block in Phtml ?

echo $block->getLayout()-> createBlock('Magento\Cms\Block\Block')-> setBlockId('block_identifier')-> toHtml();

How to Get store information in .phtml file?

echo $block->getStoreId(); || ->getStoreCode(); || ->getWebsiteId(); ||->getStoreName(); ||->getStoreUrl(); ||->isStoreActive();

How to Get Customer Information By Id in Magento 2 using model?

echo $customer->getFirstname() .$customer->getLastname() .$customer->getEmail(); $billingAddressId = $customer->getDefaultBilling(); $address = $block->getCustomerAddressById($billingAddressId); print_r($address->getData()); $shippingAddressId = $customer->getDefaultShipping(); $address = $block->getCustomerAddressById($shippingAddressId); print_r($address->getData());

How to Get Order Information By Order Id in Magento 2 Via model?

echo $order->getIncrementId(); ||->getGrandTotal();||->getSubtotal(); echo $order->getCustomerId(); ||->getCustomerEmail(); || ->getCustomerFirstname(); ||->getCustomerLastname(); foreach ($order->getAllItems() as $item){ echo $item->getId(); || ->getProductType(); || ->getQtyOrdered(); || ->getPrice(); }

How to get a block from template file phtml in Magento 2?

echo $this->getLayout()->createBlock('MyMod\Block\MyMod')->setTemplate('My_Mod::mymod.phtml')->toHtml(); block class="MyMod\Block\MyMod" name="block_name" template="My_Mod::mymod.phtml"

what directory consists on App/etc ?

etc contains environment settings for Magento;

Explain area of Catching & handling a event?

etc/: configuration used in both admin & frontend. ||/frontend: || frontend area. ||/adminhtml: || admin area.

Defining methods plugin in Magento 2?

expand or edit a public method's behavior by using code before, after or around method.get object that provides permission to all public methods of observed method's class. 3 methods in Plugin: before - beforeDispatch() around - aroundDispatch() after - afterDispatch()

What abstract class extends Every CRUD resource model?

extends abstract class \Magento\Framework\Model\ResourceModel\Db\AbstractDb which contain functions for fetching information from db.

How to create loop through order items on shipment ?

foreach ($order->getAllItems() AS $orderItem) { if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue;} $qtyShipped = $orderItem->getQtyToShip();

Magento 2 request flow of url.com/front_name/controller/action?

front_name use to find module. router define name for each module by define in routes.xml which will see more detail bellow. When make a request follow this flow to find controller/action: index.php → HTTP app → FrontController → Routing → Controller processing → etc. FrontController will be call in Http class to routing request which will find controller/action match. (File:vendor/magento/framework/App/FrontController.php)

What is crontab.xml syntax meaning ?

group id: cron group name can run only cron for single group at a time. job instance: class to be instantiated (classpath). job method:job instance to call. job name: Unique ID for this cron job. schedule: cron format.

what directory consists on App/i18n ?

i18n is used to install language packs.

How to Check if order can be shipped or has already shipped?

if (! $order->canShip()) { throw new \Magento\Framework\Exception\LocalizedException(__('can\'t create an shipment.') ); }

How to get current product in template phtml file?

if ($currentProduct = $myBlock->getCurrentProduct()) { echo $currentProduct->getName(); || ->getSku(); || ->getFinalPrice(); || ->getProductUrl(); print_r ($currentProduct->getCategoryIds()); }

Where to Using Plugin Block Override file location?

in MyMod/etc/di.xml

How to Override via MyModule Template File in Magento 2?

in view/frontend/layout/catalog_category_view.xml <referenceBlock name="category.products.list"> <action method="setTemplate"> <argument name="template" xsi:type="string"> My_Mod::catalog/product/list.phtml</argument> </action> </referenceBlock> </body> </page> (In above code, category.products.list blocks name, whose template file want to override.Then, copy list.phtml file into following file path, view/frontend/templates/catalog/product/list.phtml)

How easier for to run project composer.json ?

it is easier for to run project smoothly when component's root directory is added composer.json.

What is knockout in Magento 2?

knockout considered as a javascript library that supports for Model-View-View-Model (MVVM) design pattern on frontend of store Knockout in on every page & particularly, Knockout is used mostly on checkout page. knockout allows auto-updating user interface quickly & easily when there is any change.

How to Override via MyTheme Template File in Magento 2?

list.phtml: app/vendor/magento/module-catalog/view/frontend/templates/product/list.phtml CopyTo:app/design/frontend/MyCompany/MyTheme/Magento_Catalog/templates/product/list.phtml, here can modify code as wish. Structure:MyCompany => Namespace,MyTheme => Theme name

vendor-name Naming conventions of component in Magento 2 Composer?

lowercase as following format for M2 extensions: magento2/*,to submit extension to M2 Marketplace, use name have registered account there. That name is injected into composer.json file as vendor-name part of extension name

What is Resource Model &Content for file?

model file contain overall database logic, it do not execute sql queries resource model will do that. create Resource Model for this table: My\Mod\Model\ResourceModel\Topic

How to overwrite layout & extend layout xml?

modify what want to change M2 system, only need to create an extending layout that contains changes to Create an extending layout file that contains changes, instead of creating & modifying many files. (For example, to customize layout defined in /app/code/Magento/Catalog/view/frontend/layout/catalog_product_view.xml, add a layout file with same name in custom theme, such as: app/design/frontend/<Vendor>/<theme>/Magento_Catalog/layout/catalog_product_view.xml)

Create Resource Model - Get Model Collection Content for file?

namespace MyMod\Model\ResourceModel; class Topic extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb{ protected function _construct(){ $this->_init('mageplaza_topic', 'topic_id'); } }

Write custom log in your module class content?

namespace MyMod\Post; class Post extends \Magento\Framework\View\Element\Template{ protected $_logger; public function __construct( \Magento\Backend\Block\Template\Context $context, \Psr\Log\LoggerInterface $logger, array $data = []){ $this->_logger = $logger; parent::__construct($context, $data); } public function testLogging() { $this->_logger->debug('debug1234'); (//Output: [2017-02-22 04:48:44] main.DEBUG: debug1234 {"is_exception":false} []) $this->_logger->info('info1234'); (// Write to default log file: var/log/system.log //Output: [2017-02-22 04:52:56] main.INFO: info1234 [] []) $this->_logger->alert('alert1234'); (// Write to default log file: var/log/system.log //Output: [2017-02-22 04:52:56] main.ALERT: alert1234 [] []) $this->_logger->notice('notice1234'); (// Write to default log file: var/log/system.log //Output: [2017-02-22 04:52:56] main.NOTICE: notice1234 [] [] // Write to default log file: var/log/system.log) $this->_logger->error('error1234'); (//Output: [2017-02-22 04:52:56] main.ERROR: error1234 [] [] // Write to default log file: var/log/system.log) $this->_logger->critical('critical1234'); (//Output: [2017-02-22 04:52:56] main.CRITICAL: critical1234 [] [] // Adds a log record at an arbitrary level) $level = 'DEBUG'; (// saved in var/log/debug.log) $this->_logger->log($level,'debuglog1234', array('msg'=>'123', 'new' => '456')); (//Output: [2017-02-22 04:52:56] main.DEBUG: debuglog1234) {"msg":"123","new":"456","is_exception":false} [] (// Write to default log file: var/log/system.log) $level = 'ERROR'; $this->_logger->log($level,'errorlog1234', array( array('test1'=>'123', 'test2' => '456'), array('a'=>'b') )); (//Output: [2017-02-22 04:52:56] main.ERROR: errorlog1234 [{"test1":"123","test2":"456"},{"a":"b"}] [] ) } }

Where Dispatch event Content in Create Events - Observer?

namespace My\Mod\Controller\Index; class Test extends \Magento\Framework\App\Action\Action{ public function execute(){ $textDisplay = new \Magento\Framework\DataObject(array('text' => 'Mageplaza')); $this->_eventManager->dispatch('my_mod_display_text', ['mp_text' => $textDisplay]); echo $textDisplay->getText();exit; } }

Where cron test script Test.php?

namespace My\Mod\Cron; class Test{ public function execute(){ $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/cron.log'); $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); $logger->info(__METHOD__); return $this; } }

What content code of Observer/ChangeDisplayText.php Observer class?

namespace My\Mod\Observer; class ChangeDisplayText implements \Magento\Framework\Event\ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer){ $displayText = $observer->getData('mp_text'); echo $displayText->getText() . " - Event </br>"; $displayText->setText('Execute event successfully.'); return $this; } }

Where Register form in checkout page layout?

onestepcheckout.phtml is parent of all children template in One Step Checkout extension: (<script type="text/x-magento-init">){ "#checkout": { "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?> } }

What do mean by persistent cart?

online customers will never have a final decision to buy although they are interested in products. At that time, select way to keep those items in their shopping cart. With persistent shopping cart, incomplete checkout will continue without searching & interruption when buyer come back. (Especially, don't care about what device is used to checkout, persistent shopping cart follows user id & update exactly their carts. Therefore, regardless of device as tablet or mobile, transactions are always on hold to enhance their shopping experience with this continuance)

package-name Naming conventions of component in Magento 2 Composer?

package-name: contains lowercase with multiple words, Composer asks for separating them by dash as following convention: magento2/<type-prefix>-<suffix>[-<suffix>]... Type-prefix is a type of component & suffix is a thing to realize which component it is within that type. (pay attention when creating a composer.json in M2. follow carefully & make yourself more comfortable with composer.json when running projects.)

Where Readcookie __construct?

protected $_cookieManager; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager ){ $this->_cookieManager = $cookieManager; parent::__construct($context); }

How to Get Customer Groups in Magento 2?

protected $_customerGroup; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroup, array $data = [] ) { $this->_customerGroup = $customerGroup; parent::__construct($context, $data); } public function getCustomerGroups() { $customerGroups = $this->_customerGroup->toOptionArray(); array_unshift($customerGroups, array('value'=>'', 'label'=>'Any')); return $customerGroups; }

Set your own function to get data joining data between 2 tables in Magento 2?

protected function filterOrder($payment_method){ $this->sales_order_table = "main_table"; $this->sales_order_payment_table = $this->getTable("sales_order_payment"); $this->getSelect() ->join(array('payment' =>$this->sales_order_payment_table), $this->sales_order_table . '.entity_id= payment.parent_id', array('payment_method' => 'payment.method', 'order_id' => $this->sales_order_table.'.entity_id') ); $this->getSelect()->where("payment_method=".$payment_method); }

Write code URL Rewrite Generate constructor file?

public function __construct(Context $context,\Magento\UrlRewrite\Model\UrlRewriteFactory $urlRewriteFactory) { $this->_urlRewriteFactory = $urlRewriteFactory; parent::__construct($context ); }

Add a class to your module, then identify a function Convert Custom Field From Quote Item to Order Item in Magento 2?

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

How to Implement after - afterDispatch()methods in Plugin?

public function aroundGetTitle( \MyMod\Controller\Index\Example $subject, callable $proceed){ echo __METHOD__ . " - Before proceed() </br>"; $result = $proceed();echo __METHOD__ . " - After proceed() </br>"; return $result; }

How to function execute read cookie content?

public function execute(){ $cookieValue = $this->_cookieManager->getCookie(\MymPath\Controller\Cookie\Addcookie::COOKIE_NAME); echo($cookieValue); }

How to set a controller file email to a custom email address?

public function execute(){ $email = $this->getRequest()->getParam('email'); $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load(1); // this is entity id $order->setCustomerEmail($email); if ($order) { try { $this->_objectManager->create('\Magento\Sales\Model\OrderNotifier') ->notify($order); $this->messageManager->addSuccess(__('sent order email.')); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t send email order now.')); $this->_objectManager->create('Magento\Sales\Model\OrderNotifier')->critical($e); } } }

How to upload product image function execute in Magento 2?

public function execute(){ $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA) ->getAbsolutePath('images/'); $uploader->save($path); }

How to upload product image in Magento 2?

public function execute(){ $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']); $||->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $||->setAllowRenameFiles(false); $||->setFilesDispersion(false); $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('images/'); $uploader->save($path); }

Write function start calling Catalog/Customer/Checkout sessions through following code?

public function getCatalogSession() {return $this->_catalogSession;} || getCustomerSession(){ return $this->_customerSession;} || getCheckoutSession(){ return $this->_checkoutSession;}

How to get registry of current Product, Category, CMS Page?

public function getProduct(){ return $this->_registry->registry('current_product'); } public function getCurrentCategory(){ return $this->_registry->registry('current_category'); } public function getCurrentCategory(){ return $this->_registry->registry('current_cms_page'); }

How to Create block new.order.totals?

public function initTotals(){ $orderTotalsBlock = $this->getParentBlock(); $order = $orderTotalsBlock->getOrder(); if ($order->getNewTotalAmount() > 0) { $orderTotalsBlock->addTotal(new \Magento\Framework\DataObject([ 'code' => 'new_total','label' => __('New Total'),'value' => $order->getNewTotalAmount(),'base_value' => $order->getNewTotalBaseAmount(), ]), 'subtotal'); } } (Create: My \HelloWorld\Block\Order\Totals.php)

InstallData install function?

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $data = [ 'name' => "How to Create SQL", 'post_content' => "In this article, ..", 'url_key' => '/sql-setup-script.html', 'tags' => ' helloworld','status' => 1 ]; $post = $this->_postFactory->create(); $post->addData($data)->save(); }

Write class of InstallSchema.php to create product attribute programmically?

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'sample_attribute',[ 'type' => 'text', 'backend' => '', 'frontend' => '', 'label' => 'Sample Atrribute', 'input' => 'text', 'class' => '', 'source' => '', 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL, 'visible' => true, 'required' => true, 'user_defined' => false, 'default' => '', 'searchable' => false, 'filterable' => false, 'comparable' => false, 'visible_on_front' => false, 'used_in_product_listing' => true, 'unique' => false, 'apply_to' => ''] ); }

How Create custom attribute InstallData.php class?

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Customer\Model\Customer::ENTITY, 'sample_attribute', [ 'type' => 'varchar', 'label' => 'Sample Attribute', 'input' => 'text', 'required' => false, 'visible' => true, 'user_defined' => true, 'position' => 999, 'system' => 0,] ); $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'sample_attribute'); (// more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']) $sampleAttribute->setData( 'used_in_forms',['adminhtml_customer'] ); $sampleAttribute->save(); }

How Create custom attribute InstallData.php script?

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Customer\Model\Customer::ENTITY, 'sample_attribute',[ 'type' => 'varchar','label' => 'Sample Attribute', 'input' => 'text','required' => false, 'visible' => true,'user_defined' => true, 'position' => 999,'system' => 0,] ); $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'sample_attribute'); // more used_in_forms $sampleAttribute->setData( 'used_in_forms',['adminhtml_customer'] ); $sampleAttribute->save(); } }

How to to remove product attribute, can use method removeAttribute instead of addAttribute?

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->removeAttribute( \Magento\Catalog\Model\Product::ENTITY, 'sample_attribute'); }

How to Define install() method?

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ }

How to Set priority for plugins?

sortOrder option allow placing plugins which are observing same method in a queue. When before, after, or around methods start calling plugins are applied one by one.

installSchema install function?

public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context){ $installer = $setup; $installer->startSetup(); if (!$installer->tableExists('mageplaza_helloworld_post')) { $table = $installer->getConnection()->newTable( $installer->getTable('mageplaza_helloworld_post') ) ->addColumn('post_id',\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, [ 'identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true,], 'Post ID').. ->setComment('Post Table'); $installer->getConnection()->createTable($table); $installer->getConnection()->addIndex( $installer->getTable('my_mod_post'), $setup->getIdxName( $installer->getTable('my_mod_post'), ['name', 'url_key', 'post_content', 'tags', 'featured_image'], \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT ), ['name', 'url_key', 'post_content', 'tags', 'featured_image'], \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT); } $installer->endSetup(); }

Check if current requested URL is secure function in template .phtml file check url is secured https, ssl ?

public function isCurrentlySecure(){ return $this->_storeManager->getStore()->isCurrentlySecure(); } var_dump($block->isCurrentlySecure()) . '<br />';

Check if frontend URL is secure function in template .phtml file check url is secured https, ssl ?

public function isFrontUrlSecure(){ return $this->_storeManager->getStore()->isFrontUrlSecure(); } var_dump($block->isFrontUrlSecure()) . '<br />';

How to check if current url is homepage in Magento 2?

public function isHomePage(){ return $this->_logo->isHomePage();} if ($block->isHomePage()) { // do something }

How to get & set custom attribute in registry/register?

public function setCustomVariable(){$this->registry->register('custom_var', 'Added Value'); } public function getCustomVariable(){ return $this->registry->registry('custom_var'); }

Write class function magento 2 Dispatching events?

public function something() { $eventData = null; // Code... $this->eventManager->dispatch('my_module_event_before'); // More code that sets $eventData... $this->eventManager->dispatch('my_module_event_after', ['myEventData' => $eventData]); }

UninstallInterface Uninstall function?

public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context){ $installer = $setup;$installer->startSetup(); $installer->getConnection()->dropTable($installer->getTable('mageplaza_helloworld_post')); $installer->endSetup(); }

Write sample code Upgrade Schema upgrade function?

public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $context ) { $installer = $setup;$installer->startSetup(); if(version_compare($context->getVersion(), '1.2.0', '<')) { $installer->getConnection()->addColumn( $installer->getTable( 'my_mod_post' ),'test', ['type' => \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, 'nullable' => true,'length' => '12,4','comment' => 'test','after' => 'status' ] );} $installer->endSetup(); }

UpgradeData.php function upgrade of creating CMS Page programmatically?

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ $setup->startSetup(); if (version_compare($context->getVersion(), '1.1') < 0) { $page = $this->_pageFactory->create(); $page->setTitle('Example CMS page') ->setIdentifier('example-cms-page') ->setIsActive(true) ->setPageLayout('1column') ->setStores(array(0)) ->setContent('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')->save(); } $setup->endSetup(); }

UpgradeData upgrade function?

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context){ if (version_compare($context->getVersion(), '1.2.0', '<')) { $data = [ 'name' => "Magento 2 Events", 'post_content' => "This article will talk about Events List in Magento 2. ", 'url_key' => '/magento-2-module-development/magento-2-events.html', 'tags' => 'magento 2,mageplaza helloworld', 'status' => 1 ]; $post = $this->_postFactory->create(); $post->addData($data)->save(); } }

Standalone Initialization Prompt Widget?

require([ 'Magento_Ui/js/modal/prompt' ], function(prompt) { // Variable that represents `prompt` function prompt({ title: 'Some title', content: 'Some content', actions: {confirm: function(){}, cancel: function(){}, always: function(){} } }); });

How Set select query stock item from Resource Model?

retrieve data from database by command $select query. (Set select query via connection object, )

Flush cache rm command?

rm -rf var/cache/* || /page_cache/* || /generation/*

Create custom route on admin routes.xml location?

route will be same as frontend route but must declare it in adminhtml folder with router id is admin. /etc/adminhtml/routes.xml

Why need Cron Job?

schedules activities to occur in future. A partial list of these activities follows: Catalog price rules Newsletters Generating Google sitemaps Customer Alerts/Notifications (product price change, product back in stock) Reindexing Private sales (Magento Commerce only) Automatic updating of currency rates All M2 e-mails (including order confirmation & transactional)

Where Create a controller to read cookie?

setting a Readcookie.php controller :app/code/My/Mod/Controller/Cookie.

How many types of sessions are available in Magento?

two , customer & checkout sessions. All customers' related data is locked with customer session whereas data related to order & quotes are stored in checkout session. Session types are utilized separately since order gets placed; check out session data information needs to be flushed. (Thus, having two different sessions for order & customer related data makes sense. Example - customer session's first name will be $_SESSION ['customer']['firstname']. similar example works for checkout session as well.)

How many ways Initialize Prompt Widget?

two prompt widget 1. Initialization on an element 2.Standalone Initialization

How different ways Magento 2 Unit Test including ?

two:Command Line Interface (CLI), PHPStorm IDE

Where does all core modules are located in Magento2?

under vendor/magento folder.

How to get access Magento 2 core functionality need to include code in top of external file?

use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params);

How to write log in Magento 2?

use Monolog Library for purpose of logging at M2_ROOT/vendor/monolog/monolog/src/Monolog/Logger.php. Two steps : Step1: Write custom log in module Step2: Flush Cache & check result

Write custom log in your module?

use one of function app/code/My/Mod/Block/Post.php. some types of logs such as info, alert, notice, critical, error & debug in following code. all of them are archived in system.log expecting from debug log that is in debug.log

Write list of session types in Magento 2?

vendor/magento/module-catalog/Model/Session.php || /module-newsletter/Model/Session.php || /module-persistent/Model/Session.php || /framework/Message/Session.php || /module-customer/Model/Session.php || /module-backend/Model/Session.php || /module-checkout/Model/Session.php

How to overwrite phtml files in Magento 2?

vendor/magento/module-review/view/frontend/templates/helper/summary_short.phtml -> app/design/frontend/Vendor/example/Magento_Review/templates/helper/summary_short.phtml where "example" is name of theme

Where do find Blank & Luma themes?

vendor/magento/theme-frontend-blank || /theme-frontend-luma

Where can find styles for modules?

vendor/magento/theme-name/Magento_XXX/web/css/source/_module.less

What are additional files in theme?

view.xml, configures size of images & gallery settings ,default format & name of a logo image is logo.svg put a logo.svg image in conventional location, which is <theme_dir>/web/images directory automatically recognized as theme logo.

What view.xml file is used for?

view.xml: properties of product images used on storefront are stored in configuration file, displayed on product pages are defined by gallery widget options configured in theme view.xml as well. modified: width height constrain aspect_ratio frame transparency background

What happens when a customer adds two of same simple products with different custom options to cart?

will shown as two separate line items.

Example vendor-name Naming conventions of component in Magento 2 Composer?

{ "name": "mageplaza/magento-2-seo-extension", "description": "Magento 2 SEO extension", "require": { "php": "~5.5.0|~5.6.0|~7.0.0", "mageplaza/core-m2": "dev-master" }, "type": "magento2-module", "version": "1.1.1", "license": [ "OSL-3.0", "AFL-3.0" ], "authors": [ { "name": "Mageplaza", "email": "[email protected]", "homepage": "https://abc.com", "role": "Leader" } ], "autoload": { "files": [ "registration.php" ], "psr-4": { "Mageplaza\\Seo\\": "" } } }


Set pelajaran terkait

Osgood-Schlatter Disease, Legg-Calve-Perthes disease, Osteosarcoma

View Set

Metamorphic Processes and products

View Set

Chapter 4: Formation of the Solar System (Textbook Notes)

View Set

Marketing Chapter 17 Test- 12/11/15

View Set

N 204 ch 12 Collaborative practice and care coordination accross settings (final)

View Set

prep u 140 infection and inflammation

View Set

Chemical Reactions and Reaction Stoichiometry

View Set