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
Related
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 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 building an extension that creates a backend module that enables be_users to resize images.
I'm trying to add / include css and javascript files by using the pageRenderer but the files are never included I can only apply css if add it directly in the fluid Template using a style tag and include the javascript file with a script tag.
I tried something like this in the controller
protected $pageRenderer;
....
$this->pageRenderer = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Page\\PageRenderer');
$this->pageRenderer->addCssFile('/typo3conf/ext/extKey/Resources/Public/css/styles.css');
$this->pageRenderer->loadJquery();
also tried with a viewHelper
namespace Vendor\ExtKey\ViewHelpers;
class AddJsFileViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\Be\AbstractBackendViewHelper {
public function render() {
$doc = $this->getDocInstance();
$pageRenderer = $doc->getPageRenderer();
$pageRenderer->loadJquery();
}
}
and in my tempate
{namespace pager=Vendor\ExtKey\ViewHelpers}
<f:layout name="Default" />
<f:section name="main">
<pager:addJsFile />
...
still nothing
I'm not sure how you define the template for your backend, but it seems this usually happens using the backend container view helper which already has functions for that:
<f:be.container
addCssFile="{f:uri.resource(path:'css/style.css')}"
addJsFile="{f:uri.resource(path:'js/scripts.js')}">
[your templates content]
</f:be.container>
In TYPO3 7.6.X, It has to be like following
<f:be.container
includeCssFiles="{style:'{f:uri.resource(path:\'css/style.css\')}'}"
includeJsFiles="{script:'{f:uri.resource(path:\'js/script.js\')}'}"
>
<!-- Template Code -->
</f:be.container>
As includeCssFiles and includeJsFiles requires array to be passed, we
can include any number of js and css.
i think the problem was my ViewHelper need to renderChilden and start/end page
current implementation is like this
the ViewHelper
namespace Vendor\ExtKey\ViewHelpers;
class AddPublicResourcesViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\Be\AbstractBackendViewHelper {
public function render() {
$doc = $this->getDocInstance();
$pageRenderer = $doc->getPageRenderer();
$extRelPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath("ext_key");
$pageRenderer->addCssFile($extRelPath . "Resources/Public/css/styles.css");
$pageRenderer->loadJquery();
$pageRenderer->addJsFile($extRelPath . "Resources/Public/js/app.js");
$output = $this->renderChildren();
$output = $doc->startPage("title") . $output;
$output .= $doc->endPage();
return $output;
}
}
the template
{namespace pager=Vendor\ExtKey\ViewHelpers}
<f:layout name="Default" />
<f:section name="main">
<pager:addPublicResources />
Pagerender::loadJjquery is working and accessible like this
TYPO3.jQuery(function($) {
});
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.
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');