In Magento 2 how can I retrieve a container from layout? - magento2

How can I retrieve a container from the layout programmatically?
I would like to be able to do something like the following...
$container = $layout->getContainer('name');
$container->setAttribute('htmlClass', 'class');

So I'll be that guy, try your best not to use the object manager directly. To use or not to use the ObjectManager directly?
<?= $block->getLayout()->renderNonCachedElement('top-right-wrapper'); ?>
-or-
<?= $this->getLayout()->renderNonCachedElement('top-right-wrapper'); ?>
Both above will work but using $this is discouraged. Magento 2 Templates: Use $block or $this?

With little debugging in core I have found that there is a method which
returns any container,block or UIcomponent html using name as parameter.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$layoutObj = $objectManager->get('Magento\Framework\View\Layout');
$html = $layoutObj->renderNonCachedElement('top-right-wrapper');
echo $html;
* Replace top-right-wrapper with your block,container or UIcomponent name.

Related

Get Category Description in my cutom phtml file in magento 2

I am using Magento 2. I want to get category description and image in my custom phtml file.
How can i do that?
If you want to get in current category information in phtml you can use following code.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentCategory = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category information
echo $currentCategory->getId();
echo $currentCategory->getName();
echo $currentCategory->getDescription();
echo $currentCategory->getImageUrl();
?>
Or do you want to load any specific category then you can use below code.
$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')
->load($categoryId);
echo $category->getName();
echo $category->getImageUrl();

in magento 2 which block methods are available in a template?

m2 is much different than m1.
When I'm writing code (programming public methods) in the template they don't seem to be working. Are all methods allowed like protected and private as well? or getters or only public getters? I'm confused.
I believe it's only public getters right?
Any help would be greatly appreciated.
All public methods from the block context are available in the template.
Block context is the block class you've assigned to the template in layout XML. It's equivalent to block type in Magento 1. By default it is \Magento\Framework\View\Element\Template, which is equivalent to Mage_Core_Block_Template in Magento 1.
This block context is assigned to the template as the $block variable during rendering. This is different from Magento 1, where $this refers to the block context in the template. In Magento 2, $this refers to the template engine responsible for rendering the template. You can see this all play out in the render method of the template engine, where the $dictionary parameter (containing $block among others) is extracted just before including the phtml file. This allows all extracted variables, notably $block, to be used in the template.
Example block usage
Say you've created a custom block class in your module as app/code/MyNamespace/MyModule/Block/MyBlock.php like this.
<?php
namespace MyNamespace\MyModule\Block;
use Magento\Framework\View\Element\Template;
class MyBlock extends Template
{
public const FOO = 'foo';
private const BAR = 'bar';
public function isFoo(string $str): bool
{
return $str === self::FOO;
}
private function isBar(string $str): bool
{
return $str === self::BAR;
}
}
You'd include this block to, let's say every product page by creating a file in app/code/MyNamespace/MyModule/view/frontend/layout/catalog_product_view.xml like this.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="MyNamespace\MyModule\Block\MyBlock" name="myblock" template="MyNamespace_MyModule::mytemplate.phtml" />
</referenceContainer>
</body>
</page>
This will add MyBlock to the content-container on every product page. Containers will auto-render their child blocks, so they are similar to the core/text_list block type in Magento 1.
Then in the template configured in the layout XML, app/code/MyNamespace/MyModule/view/frontend/templates/mytemplate.phtml, you can use public methods and properties, including isFoo, but not private or protected ones like isBar. Doc-comments in the beginning of the template file make it clear what $this and $block are.
<?php
/** #var $this \Magento\Framework\View\TemplateEngine\Php */
/** #var $block \MyNamespace\MyModule\Block\MyBlock */
$thing1 = 'foo';
$thing2 = 'bar';
?>
<div class="my-thing">
<?php if ($block->isFoo($thing1)): ?>
<!-- isFoo works since it's a public method -->
<?php endif; ?>
<?php if ($block->isBar($thing2)): ?>
<!-- isBar doesn't work since it's a private method -->
<?php endif; ?>
<!-- You can access public properties and constants from the $block object, too -->
<span><?php echo $block::FOO; ?></span>
</div>

Zend Framework translate language text

I have some translation code which is working fine.
<?php echo $this->translate("54"); ?>
Outputs
Hello World
is it possible to output instead of above
<div class='lang' id='54'>Hello World</div>
Later using jquery I would like to manipulate the div.
create a custom view helper named MyTranslate extends \Zend\I18n\View\Helper\Translate then override the _invoke method :
public function __invoke($message, $textDomain = null, $locale = null)
{
$t = parent::__invoke($message, $textDomain , $locale);
//change the value of $t however you wnat
return $t;
}
if you don't what to change your code where ever you have used translate register this new view helper as translate and not my_translate
If you use Zend1, you can use a view helper like this:
Create a Helper directory in your library
for example, in my case I have this directory:
library/DoyDoy/Helper/
Create your helper like this:
library/DoyDoy/Helper/TranslateID.php
<?php
class DoyDoy_Helper_TranslateID extends Zend_View_Helper_Abstract
{
public function translateID($id)
{
return '<div class=\'lang\' id=\'' . $id . '\'>'. $this->view->translate($id) . '</div>';
}
}
Add your Helper in the bootstrap:
protected function _initDoyDoyView(){
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('DoyDoy/Helper/', 'DoyDoy_Helper');
}
In your view, call the helper like this:
<?php echo $this->translateID("54");?>
This should display:
<div class='lang' id='54'>Hello World</div>
I hope it will help you :)

Symfony2 $request->query->get() returning null value

I'm new to Symfony2.I am understanding the framework.
I try to access the get parameters of my request using Symfony2.
But it is returning null when I access them like
$name = $request->query->get('name');
echo $name;
My code for controller is
namespace abc\myBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
public function getnameAction()
{
$request = $this->get('request');
echo $request->getMethod();
$name = $request->query->get('name');
echo $name. "---";
}
my routing file is as follows:
abcmy_newpage:
pattern: /new/{name}
defaults: { _controller: abcmyBundle:new:getname }
When I run the URL
http://dashboardsmf.iiit.ac.in/web/app_dev.php/new/India
I get the method name
"GET"
corresponding to echo statement " echo $request->getMethod(); ".
But I get the null/"" blank value for the echo statement
echo $name. "---";
I dont know where I have mistaken.
Please help me.Thanks in advance.
Try to change you action to this:
public function getnameAction($name) {
echo $name;
}
Symfony binds parameters defined in routing file to parameter names in action method (see Symfony book chapter on controller parameters for more details).
If you want to use $request->query to get your parameters it should be passed like this: http://http://dashboardsmf.iiit.ac.in/web/app_dev.php/new?name=India.

How to render a view with specific text?

I have a class like this:
class myData {
function render(){
$str = 'This is string.';
// have to code here
}
}
and a myview.phtml file:
<div id='someid'></div>
Q: Now I want to do something like this in another phtml file:
<?php
$obj = new myData ();
echo $obj->render(); // it should be <div id='someid'>This is string.</div>
?>
So how can I change my render function in myData class that it should get myview.phtml and place string between DIV tag(<div id='someid'></div>) and print.
Thanks
One possible solution could be to use Partial view helper. This helper can be used to " render a specified template within its own variable scope".
Specifically in myview.phtml you can add the following:
<div id='someid'><?php echo $this->myText; ?></div>
Then, in the another phtml you could have:
<?php
$obj = new myData ();
echo $this->partial('path/to/myview.phtml',array('myText' => $obj->render()));
?>
Maybe you are looking for something like this:
http://webgen.hu/class.html.txt
http://webgen.hu/class.html.php