I have following XML:
<reference name="content">
<block type="name/myblockname" name="blockname" alias="blockalias" template="name/myblockname.phtml">
<action method="setData"><key>name</key><value>value</value></action>
<block type="core/template" name="otherblock" template="catalog/product/view/otherblock.phtml"/>
</block>
</reference>
And I need same as code in block constructor, I tried this. Result was that block was rendered, but getChild inside name/myblockname.phtml returns null value and not the block.
class MyCompany_ModuleName_Block_MyBlock extends Mage_Core_Block_Template
{
public function __construct() {
parent::__construct();
// $layout = $this->getLayout(); // this didn't work
// $layout = Mage::getModel('core/layout'); // this didn't work
$layout = $this->loadLayout()->getLayout(); // this didn't work
$block = $layout->createBlock("core/template");
$block->setTemplate("catalog/product/view/otherblock.phtml");
$block->setNameInLayout("otherblock");
$this->append($block, "otherblock");
}
// ... other stuff here ...
}
Here is how I am including my block to CMS page:
{{block type="name/myblockname" name="value" template="name/myblockname.phtml"}}
I want to know what I am doing wrong or is this even possible in Magento? (Don't worry about xml etc. namings, I had to overwrite those, because they contained company data, so they could be wrong in this example, but most likely are not in original code.)
I highly recommend to use the "fake"-constructor _construct(), which is called by the core __construct() to avoid misusage.
Then to add a new child block use this code:
function _construct() {
$layout = Mage::getSingleton('core/layout');
$block = $layout->createBlock('core/template','mychildblockname');
$block->setTemplate('your/childtemplate.phtml');
$this->append($block);
}
Then in the block's phtml file, you call the child by:
$this->getChildHtml('mychildblockname');
Related
Been spending the last 1 day to find a fix for this.
Basically everything works normal if I delete all the contents of generated folder and then generate the files dynamically by accessing the pages rather than doing setup:di:compile.
On the production though, I'm forced to do setup:di:compile and I end up with this certain admin module page being empty.
This is the controller of the page:
namespace Eadesigndev\AWB\Controller\Adminhtml\Index;
use Eadesigndev\Awb\Api\AwbRepositoryInterface;
use Eadesigndev\Awb\Model\Awb;
use Eadesigndev\Awb\Model\AwbFactory;
use Eadesigndev\Awb\Helper\Data as DataHelper;
use Magento\Framework\Registry;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action;
class Edit extends Action
{
/**
* Authorization level of a basic admin session
*
*
*/
const ADMIN_RESOURCE = 'Eadesigndev_Awb::awb';
protected $resultPageFactory;
private $awbRepository;
private $awbFactory;
private $registry;
private $session;
private $dataHelper;
private $awbModel;
public function __construct(
Context $context,
PageFactory $resultPageFactory,
AwbRepositoryInterface $awbRepository,
AwbFactory $awbFactory,
Awb $awbModel,
Registry $registry,
DataHelper $dataHelper
) {
$this->resultPageFactory = $resultPageFactory;
$this->awbRepository = $awbRepository;
$this->awbFactory = $awbFactory;
$this->registry = $registry;
$this->awbModel = $awbModel;
$this->session = $context->getSession();
$this->dataHelper = $dataHelper;
parent::__construct($context);
}
/**
* Edit action new awb.
*
* #return \Magento\Backend\Model\View\Result\Page
*/
public function execute()
{
$id = $this->getRequest()->getParam('entity_id');
if ($id) {
$model = $this->awbRepository->getById($id);
if (!$model->getEntityId()) {
$this->messageManager->addErrorMessage(__('This field no longer exists.'));
/** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create();
return $resultRedirect->setPath('*/*/');
}
} else {
echo '3';
$model = $this->awbFactory->create();
}
/** #var Session $data */
$data = $this->session->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}
$this->registry->register('awb_data', $model);
echo 'wat';
/** #var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->addBreadcrumb(__('Edit new Awb'), __('Edit new Awb'));
$resultPage->getConfig()->getTitle()->prepend(__('Edit new Awb'));
echo 'pac';
return $resultPage;
}
the controller currently returns a blank page with my debug strings:
3watpac
in /vendor/eadesignro/awb/Block/Adminhtml/Xtea I have the next files:
Edit (folder)
Edit.php
EditAwb.php
in /vendor/eadesignro/awb/view/adminhtml/layout I have the next files:
shipping_awb_index_edit.xml
shipping_awb_index_editawb.xml
shipping_awb_index_index.xml
Content of shipping_awb_index_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="editor"/>
<head></head>
<body>
<referenceContainer name="content">
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit" name="awb_edit"/>
</referenceContainer>
<referenceContainer name="left">
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit\Tabs" name="awb_edit_tabs">
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit\Tab\General" name="awb_edit_tab_general"/>
<action method="addTab">
<argument name="name" xsi:type="string">general_section</argument>
<argument name="block" xsi:type="string">awb_edit_tab_general</argument>
</action>
<block class="Eadesigndev\Awb\Block\Adminhtml\Xtea\Edit\Tab\Curier" name="awb_edit_tab_curier"/>
<action method="addTab">
<argument name="name" xsi:type="string">curier_section</argument>
<argument name="block" xsi:type="string">awb_edit_tab_curier</argument>
</action>
</block>
</referenceContainer>
</body>
</page>
This is the page:
magento_admin_secreturl/shipping_awb/index/edit/key/xxxxxx
these are the routers:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="shipping_awb" frontName="shipping_awb">
<module name="Eadesigndev_Awb" before="Magento_Backend"/>
</route>
<route id="edit_awb" frontName="edit_awb">
<module name="Eadesigndev_Awb" before="Magento_Backend"/>
</route>
</router>
</config>
Any possible idea on why $this->resultPageFactory->create(); is simply returning nothing on production but working on development?
The index page works both on production and dev without any problem.
I can provide more info if needed, thank you!
The problem was a CAPSLOCK mistake in the namespace.
namespace Eadesigndev\AWB\Controller\Adminhtml\Index;
should have been
namespace Eadesigndev\Awb\Controller\Adminhtml\Index;
notice the 'AWB' becoming 'Awb'.
Apparently in development mode, the namespaces are not case-sensitive? or perhaps they are all transformed to capslock. If anyone has a clue, leave a comment, thanks!
For anyone who is still getting a blank page in Admin Controller, but the alternative solutions (case-sensitive) doesn't work for you, you may try running php bin/magento setup:di:compile.
This helped me.
i want to add custom script just after the start of head tag.
like.
<head>
<script>console.log("I'm loaded!");</script>
i tried to add code in default_head_blocks.xml
<referenceContainer name="head.additional">
<block class="Custom\Module\Block\Success" template="Custom_Module::success/head.phtml"/>
</referenceContainer>
=> output :
<script>console.log("I'm loaded!");</script>
</head>
this code are using add script before the end of head tag.
Please check Below code
Block => Custom/Module/Block/Onepage/Success.php
namespace Custom\Module\Block\Onepage;
use Magento\Framework\View\Element\Template;
class Success extends \Magento\Checkout\Block\Onepage\Success {
public function getOrder()
{
$objectManager =\Magento\Framework\App\ObjectManager::getInstance();
$helper = $objectManager->get('Custom\Module\Helper\Data');
$lastOrderId = $this->getOrderId();
if (empty($lastOrderId))
{
return null;
}
$orderData = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($this->getOrderId());
return $orderData;
}
}
Helper => Custom\Module\Helper\Data.php
namespace Custom\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* #param \Magento\Framework\App\Helper\Context $context
*/
protected $_request;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\App\Request\Http $request
) {
$this->_request = $request;
parent::__construct($context);
}
public function getConfigValue($value = '') {
return $this->scopeConfig
->getValue($value,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
public function getTemplate()
{
if ($this->getConfigValue('custom_general/general/active') == 1) {
$template = 'Custom_Module::checkout/success.phtml';
} else {
$template = 'Magento_Checkout::success.phtml';
}
return $template;
}
}
di.xml => etc\di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Block\Onepage\Success" type="Custom\Module\Block\Onepage\Success"/>
</config>
Layout Xml => Custom/Module/view/frontend/layout/default.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="require.js">
<action method="setTemplate">
<argument name="template" xsi:type="string">Custom_Module::success/head.phtml</argument>
</action>
</referenceBlock>
</body>
</page>
Template => Custom/Module/view/frontend/templates/success/head.phtml
<script>
console.log("I'm loaded!");
</script>
Please help me and solve this issue
Thanks in advance.
I am not sure if this is the correct way or not, but I have got a lead.
By default magento 2 usees the root.phtml file to setup head content accordingly, which is located in vendor/magento/module-theme/view/base/templates/root.phtml (if it has not been overridden).
Here, the $requireJs variable is loaded first in the head block. The $requireJs variable is defined in the render method inside Page class -which is located in vendor/magento/framework/view/Result/Page.php.
In this file, $requireJs contains the require.js block. And the require.js block is defined in vendor/Magento/module-theme/view/frontend/layout/default.xml :
<block name="require.js" class="Magento\Framework\View\Element\Template" template="Magento_Theme::page/js/require_js.phtml" />
Solution
1) Copy require_js.phtml from vendor/magento/module-theme/view/frontend/templates/page/js to your theme app/design/frontend/{VENDOR}/{THEME_NAME}/Magento_Theme/templates/page/js/
2) Now you can add your script like this:
<script>
console.log("I'm loaded!");
var require = {
"baseUrl": "<?php /* #escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
};
</script>
UPDATE (Using Module)
Overriding the require.js block is not an elegant solution. if anyone has a good solution please answer. For now edit your layout xml:
<referenceBlock name="require.js">
<action method="setTemplate">
<argument name="template" xsi:type="string">Custom_Module::success/head.phtml</argument>
</action>
</referenceBlock>
and inside success/head.phtml add your code:
<script>
console.log("I'm loaded!");
var require = {
"baseUrl": "<?php /* #escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
};
</script>
I found a simple way of doing it that seems very reasonable, because it uses existing features in the adminhtml theme without any need to override/intercept anything.
Background
Like #sanchit-gupta mentioned, the root.phtml template is used as the basis to render both the frontend and adminhtml areas, and so is the associated class \Magento\Framework\View\Result\Page, which always looks for a block named head.additional before rendering.
This block exists in the frontend layouts by default, but unfortunately it doesn't exist in the adminhtml layout.
Solution
With that in mind, the current best way (as of 2.3.x) to add inline <scripts> to the adminhtml's <head> section is to add any head.additional block: it will be automatically rendered by the framework. It either has to be a ListText block so that it renders all it's children automatically, or a Template with a specified template file. I actually chose too nest my actual block inside the ListText block just to keep the same mechanism available as in the frontend area (i.e. for compatibility with other plugins that might be doing the same).
Example
In your custom module or theme, add a layout update that inserts the following block into the body of the page layout (which is just to do it the same way as it's done in Magento 2 core for the frontend area):
<body>
<block class="Magento\Framework\View\Element\Text\ListText" name="head.additional">
<block name="your_block" class="Magento\Framework\View\Element\Template" template="Your_Module::your/template.phtml" />
</block>
</body>
Done! Your template will render inside <head></head> – without any awkward overrides or "hacks".
What's more, if other modules also reference head.additional in the adminhtml area, they will be compatible with your code.
I'm working on Magento 2.
But couldn't find the solutions for getting scopeconfig values in layout xml files.
In magento 1.x, using like below.
<block type="cms/block" ...>
<action method="..." ifconfig="config_path/config"></action>
</block>
In magento 2, how to use "ifconfig" in the layout xml?
It's same with magento 1.x.
You can use like below.
<block class="Magento\Framework\View\Element\Html\Link\Current" ifconfig="catalog/seo/search_terms" name="search-term-popular-link">
You can simply use like as
<block class="Ced\Abhinay\Block\Account\Active" ifconfig="ced/account/activation" name="ced_account_activation">
Where
Ced = Your Namespace
Abhinay = Your Module Name
Method1: Using Object Manager
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$conf = $objectManager
->get('Magento\Framework\App\Config\ScopeConfigInterface')
->getValue('section_id/group_id/field_id');
echo $conf;
?>
Method2: Using Helper
Create Data.php inside Helper folder of your module and write below code inside it.
<?php
namespace VendorName\ModuleName\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function getConfig($config_path)
{
return $this->scopeConfig->getValue(
$config_path,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
}
?>
You can call this helper inside your phtml file by below code-
<?php
$value=$this->helper('Megha\Menu\Helper\Data')->getConfig('section_id/group_id/field_id');
echo $value;
?>
You can use like below.
<block class="Magento\Rss\Block\Feeds" ifconfig="rss/config/active" name="head_rss">
You can get directly scop config value into phtml file using below code.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$conf = $objectManager
->get('Magento\Framework\App\Config\ScopeConfigInterface')
->getValue('group/field/value');
Second Way to Created function for getting configuration values in your custom module's helper
<?php
namespace Vendor\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function getConfig($config_path)
{
return $this->scopeConfig->getValue(
$config_path,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
}
Then you can get the configuration values to call this function in any phtml files.
$this->helper('Vendor\Module\Helper\Data')->getConfig('section/group/field');
Note: Please refer below links.
https://magento.stackexchange.com/questions/84481/magento-2-how-to-get-the-extensions-configuration-values-in-the-phtml-filesemphasized text
I just started to learn magento.I have a list of data in controller. I want to show that list in my view file. How can i do that ?
Here is my controller action- category. Where i getting the array of data.
<?php
class Company_Web_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
public function addcategoryAction()
{
if ($this->getRequest()->isPost())
{
$data = $this->getRequest()->getParams();
$catName = $data['catName'];
$status = $data['status'];
$data = array('name'=>$catName,'status'=>$status);
$model = Mage::getModel('web/web')->setData($data);
try {
$insertId = $model->save()->getId();
$this->_redirect('web/index/category');
} catch (Exception $e){
echo $e->getMessage();
}
}
$this->loadLayout();
$this->renderLayout();
}
public function categoryAction()
{
$collection = Mage::getModel('web/web')->getCollection()->getData();
$this->loadLayout();
$this->renderLayout();
}
}
?>
Magento works with block type i.e where you have mentioned your phtml file to render the content for category action i.e
<web_index_category>
<reference name="content">
<block type="core/template" name="category.block" template="customfile.phtml" />
</reference>
</web_index_category>
for the block type you can drfine your custome type
i.e. type="web/category"
and create one Block
Company_Web_Block_Category extends Mage_Core_Block_Template
inside this create a function and return your collection
i.e.
public function getCollection()
{
return Mage::getModel('web/web')->getCollection()->getData();
}
In your phtnl access this function using,
$this->getCollection()
Check here for more elaboration
http://www.gravitywell.co.uk/blog/post/how-to-creating-your-own-custom-block-in-magento
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-4-magento-layouts-blocks-and-templates
You could do this from the controller, but it's much simpler and much more in line with Magento best practices to pass data to templates via Blocks.
To figure out which template and block is being rendered, go to System > Configuration > Advanced > Developer > Debug and enable template path hints (with block names). Now when you load the frontend, you'll see red borders around parts of the page that illustrate which block and template combination is loading various parts of the webpage.
Properties and methods of a Block object are automatically available to the template being rendered by that Block.
To make that data available in your template, just add a method to the Block that's rendering the template, then call that method from within your template.
As a shortcut, you could also just call $collection_data = Mage::getModel('web/web')->getCollection()->getData(); directly inside your template.
For more information, see Magento for Developers: Part 4 - Magento Layouts, Blocks and Templates.
I'm performing a quick job for a Magento-based site and can't recall how to pull in TPL files within the CMS. I've tried using the following code in my CMS page...
{{block type="cms/block" block_id="page_heading" template="cms/content_heading2.phtml"}}
The TPL file is already in the correct folder... app/design/frontend/default/wfs/cms
I'm just not sure how to include this PHTML file correctly. Is it possible to provide the correct syntax?
Thanks!
When you say
`type="cms/block"`
you're telling Magento to create a 'cms/blocktemplate object, which translates to aMage_Cms_Block_Block` class. If you take a look at this block's source
#File: app/code/core/Mage/Cms/Block/Block.php
protected function _toHtml()
{
$blockId = $this->getBlockId();
$html = '';
if ($blockId) {
$block = Mage::getModel('cms/block')
->setStoreId(Mage::app()->getStore()->getId())
->load($blockId);
if ($block->getIsActive()) {
/* #var $helper Mage_Cms_Helper_Data */
$helper = Mage::helper('cms');
$processor = $helper->getBlockTemplateProcessor();
$html = $processor->filter($block->getContent());
}
}
return $html;
}
you can see this doesn't render templates, but instead renders Magento's static block objects.
Try
`type="core/template"`
instead, and make sure your block ID is unique.