$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$row = new \Magento\Framework\DataObject(); $row->setData($key, $value); $row->getData($key); $row->hasData($key); $row->unsetData(); $row->toXml(); $row->toJson(); $row->debug();
/* @var $localeDate \Magento\Framework\Stdlib\DateTime\TimezoneInterface */ $localeDate = $objectManager->create(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); $localeDate->date()->format('Y-m-d H:i:s');
$session = $objectManager->get('Magento\Framework\Session\Storage'); $session->setXxxx($value); $session->getXxxx(); $session->hasXxxx(); $session->unsXxxx();
// save $this->cache = $context->getCache(); $this->cache->save(\Zend_Json::encode($data), self::CACHE_PREFIX . $key, [], $lifeTime); // load $jsonStr = $this->cache->load(self::CACHE_PREFIX . $cacheKey); if (strlen($jsonStr)) { $this->cachedData = \Zend_Json::decode($jsonStr); } // sample $cache = $objectManager->get(\Magento\Framework\App\CacheInterface::class); $cached = $cache->load($cacheKey); if(strlen($cached)) { $data = unserialize($cached); } else { $data = []; $product = $objectManager->create('Magento\Catalog\Model\ProductRepository')->getById($id); $row = new \Magento\Framework\DataObject(); $row->setData($row->getData()); $data []= $row; $cache->save(serialize($data), $cacheKey); }
// in action if($this->_request->getRouteName() == 'cms' && $this->_request->getActionName() == 'index') { // is home }
/* @var \Magento\Framework\Registry $coreRegistry */ $coreRegistry = $this->_objectManager->get('Magento\Framework\Registry'); // 存儲值 $coreRegistry->register('current_category', $category); // 提取值 $coreRegistry->registry('current_category');
$store = $objectManager->get( 'Magento\Store\Model\StoreManagerInterface' )->getStore();
// \Magento\Framework\App\Action\Action::execute() $this->messageManager->addSuccessMessage(__('You deleted the event.')); $this->messageManager->addErrorMessage(__('You deleted the event.')); return $this->_redirect ( $returnUrl );
\Magento\Framework\App\ObjectManager::getInstance() ->get( '\Psr\Log\LoggerInterface' )->addCritical( 'notice message', [ 'order_id' => $order_id, 'item_id' => $item_id // ... ]);
$currentUrl = $objectManager->get( 'Magento\Framework\UrlInterface' )->getCurrentUrl();
$url = $objectManager->get( 'Magento\Store\Model\StoreManagerInterface' )->getStore()->getUrl( 'xxx/xxx/xxx' );
// 首頁地址 $block->getBaseUrl(); // 指定 route 地址 $block->getUrl( '[module]/[controller]/[action]' ); // 指定的靜態文件地址 $block->getViewFileUrl( 'Magento_Checkout::cvv.png' ); $block->getViewFileUrl( 'images/loader-2.gif' );
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); foreach($storeManager->getWebsites() as $website) { $store_id = $storeManager->getGroup($website->getDefaultGroupId())->getDefaultStoreId(); $storeManager->getStore($store_id)->getBaseUrl(); }
/** @var \Magento\Framework\Module\Dir\Reader $reader */ $reader = $objectManager->get('Magento\Framework\Module\Dir\Reader'); $reader->getModuleDir('etc', 'Infinity_Project').'/di.xml';
/* @var \Magento\Framework\View\Asset\Repository $asset */ $asset = $this->_objectManager->get( '\Magento\Framework\View\Asset\Repository' ); $asset->createAsset('Vendor_Module::js/script.js')->getPath();
/* @var \Magento\Framework\Filesystem $fileSystem */ $fileSystem = $this->_objectManager->get('Magento\Framework\Filesystem'); $fileSystem->getDirectoryWrite('tmp')->copyFile($from, $to); $fileSystem->getDirectoryWrite('tmp')->delete($file); $fileSystem->getDirectoryWrite('tmp')->create($file);
// 上傳到media $request = $this->getRequest (); if($request->isPost()) { try{ /* @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_objectManager->create( 'Magento\MediaStorage\Model\File\Uploader', ['fileId' => 'personal_photos'] ); /* @var $filesystem \Magento\Framework\Filesystem */ $filesystem = $this->_objectManager->get( 'Magento\Framework\Filesystem' ); $dir = $filesystem->getDirectoryRead( \Magento\Framework\App\Filesystem\DirectoryList::UPLOAD )->getAbsolutePath(); $fileName = time().'.'.$uploader->getFileExtension(); $uploader->save($dir, $fileName); $fileUrl = 'pub/media/upload/'.$fileName; } catch(Exception $e) { // 未上傳 } }
// 上傳到tmp /* @var \Magento\Framework\App\Filesystem\DirectoryList $directory */ $directory = $this->_objectManager->get('Magento\Framework\App\Filesystem\DirectoryList'); /* @var \Magento\Framework\File\Uploader $uploader */ $uploader = $this->_objectManager->create('Magento\Framework\File\Uploader', array('fileId' => 'file1')); $uploader->setAllowedExtensions(array('csv')); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $result = $uploader->save($directory->getPath($directory::TMP)); $directory->getPath($directory::TMP).$result['file'];
$imageHelper = $objectManager->get( 'Magento\Catalog\Helper\Image' ); $productImage = $imageHelper->init( $product, 'category_page_list' ) ->constrainOnly( FALSE ) ->keepAspectRatio( TRUE ) ->keepFrame( FALSE ) ->resize( 400 ) ->getUrl();
$imageFactory = $objectManager->get( 'Magento\Framework\Image\Factory' ); $imageAdapter = $imageFactory->create($path); $imageAdapter->resize($width, $height); $imageAdapter->save($savePath);
/* @var \Magento\Catalog\Model\ProductRepository $product */ $product = $objectManager->create('Magento\Catalog\Model\ProductRepository')->getById($id); // print price /* @var \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency */ $priceCurrency = $objectManager->get('Magento\Framework\Pricing\PriceCurrencyInterface'); $priceCurrency->format($product->getData('price')); // print option value $product->getResource()->getAttribute('color')->getDefaultFrontendLabel(); $product->getAttributeText('color'); // all options $this->helper('Magento\Catalog\Helper\Output')->productAttribute($product, $product->getData('color'), 'color'); $product->getResource()->getAttribute('color')->getSource()->getAllOptions(); // save attribute $product->setWeight(1.99)->getResource()->saveAttribute($product, 'weight'); // 庫存 $stockItem = $this->stockRegistry->getStockItem($productId, $product->getStore()->getWebsiteId()); $minimumQty = $stockItem->getMinSaleQty(); // Configurable Product 獲取父級產品ID $parentIds = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable') ->getParentIdsByChild($productId); $parentId = array_shift($parentIds); // Configurable Product 獲取子級產品ID $childIds = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable') ->getChildrenIds($parentId); // 獲取Configurable Product的子產品Collection $collection = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable') ->getUsedProducts($product); // 判斷是否Configurable Product if ($_product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
/* @var \Magento\Checkout\Model\Session $checkoutSession */ $checkoutSession = $objectManager->get('Magento\Checkout\Model\Session'); foreach($checkoutSession->getQuote()->getItems() as $item) { /* @var \Magento\Quote\Model\Quote\Item $item */ echo $item->getProduct()->getName().'<br/>'; }
$eavConfig->getAttribute('catalog_product', 'price'); $eavConfig->getEntityType('catalog_product');
/* @var $objectManager \Magento\Framework\App\ObjectManager */ $eavConfig = $objectManager->get( '\Magento\Eav\Model\Config' ); $options = $eavConfig->getAttribute( '[entity_type]', '[attribute_code]' ) ->getFrontend()->getSelectOptions(); //或者 /* @var $objectManager \Magento\Framework\App\ObjectManager */ $options = $objectManager->create( 'Magento\Eav\Model\Attribute' ) ->load( '[attribute_code]', 'attribute_code' )->getSource() ->getAllOptions( false );
$this->_scopeConfig = $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'); // 語言代碼 $this->_scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
if($customer instanceof \Magento\Customer\Model\Customer) { /* @var \Magento\Customer\Model\Attribute $attribute */ foreach($customer->getAttributes() as $attribute) { if($attribute->getIsUnique()) { if (!$attribute->getEntity()->checkAttributeUniqueValue($attribute, $customer)) { $label = $attribute->getFrontend()->getLabel(); throw new \Magento\Framework\Exception\LocalizedException( __('The value of attribute "%1" must be unique.', $label) ); } } } }
<vars module="Vendor_Module"> <var name="var1">value1</var> </vars>
/* @var \Magento\Framework\Config\View $viewConfig */ $viewConfig = $objectManager->get('Magento\Framework\Config\View'); $viewConfig->getVarValue('Vendor_Module', 'var1');
雖然叫郵件模板,但也能夠用於須要後臺編輯模板的程序php
// template id, 一般在email_templates.xml定義。若是是在後臺加的email template,須要換成template的記錄ID,例如90 $identifier = 'contact_email_email_template'; /* @var \Magento\Framework\Mail\TemplateInterface $templateFactory */ $templateFactory = $this->_objectManager->create( 'Magento\Framework\Mail\TemplateInterface', ['data' => ['template_id' => $identifier]] ); // 模板變量,取決於phtml或後臺email template的內容 $dataObject = new \Magento\Framework\DataObject(); $dataObject->setData('name', 'william'); // 決定模板變量取值區域,例如像{{layout}}這樣的標籤,若是取不到值能夠試試把area設爲frontend $templateFactory->setOptions([ 'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID ]); $templateFactory->setVars(['data' => $dataObject]); return $templateFactory->processTemplate();
$this->resultFactory = $this->_objectManager->create('Magento\Framework\Controller\Result\RawFactory'); /* @var \Magento\Framework\Controller\Result\Raw $result */ $result = $this->resultFactory->create(); $result->setContents('hello world'); return $result;
$this->resultFactory = $this->_objectManager->create('Magento\Framework\Controller\Result\JsonFactory'); /* @var \Magento\Framework\Controller\Result\Json $result */ $result = $this->resultFactory->create(); $result->setData(['message' => 'hellog world']); return $result;
$this->_fileFactory = $this->_objectManager->create('Magento\Framework\App\Response\Http\FileFactory'); $this->_fileFactory->create( 'invoice' . $date . '.pdf', $pdf->render(), DirectoryList::VAR_DIR, 'application/pdf' );
$currencyCode = 'GBP'; /* @var \Magento\Store\Model\Store $store */ $store = $this->_objectManager->get('Magento\Store\Model\Store'); $store->setCurrentCurrencyCode($currencyCode); $storeCode = 'uk'; /* @var \Magento\Store\Api\StoreRepositoryInterface $storeRepository */ $storeRepository = $this->_objectManager->get('Magento\Store\Api\StoreRepositoryInterface'); /* @var \Magento\Store\Model\StoreManagerInterface $storeManager */ $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); /* @var \Magento\Store\Api\StoreCookieManagerInterface $storeCookieManager */ $storeCookieManager = $this->_objectManager->get('Magento\Store\Api\StoreCookieManagerInterface'); /* @var \Magento\Framework\App\Http\Context $httpContext */ $httpContext = $this->_objectManager->get('Magento\Framework\App\Http\Context'); $defaultStoreView = $storeManager->getDefaultStoreView(); $store = $storeRepository->getActiveStoreByCode($storeCode); $httpContext->setValue(\Magento\Store\Model\Store::ENTITY, $store->getCode(), $defaultStoreView->getCode()); $storeCookieManager->setStoreCookie($store); $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());
\Magento\Framework\Profiler::start( 'CONFIGURABLE:' . __METHOD__, ['group' => 'CONFIGURABLE', 'method' => __METHOD__] ); \Magento\Framework\Profiler::stop('CONFIGURABLE:' . __METHOD__);
$block->getLayout()->createBlock('Magento\Framework\View\Element\Html\Date') ->setName('date') ->setId('date') ->setClass('date') ->setDateFormat('M/d/yy') ->setImage($block->getViewFileUrl('Magento_Theme::calendar.png')) ->setExtraParams('data-validate="{required:true}"') ->toHtml();
$block->getLayout()->createBlock('Magento\Framework\View\Element\Html\Select') ->setName('sel1') ->setId('sel1') ->setClass('select') ->addOption('value', 'label') ->setValue($default) ->setExtraParams('data-validate="{required:true}"') ->toHtml();