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.
Related
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 have been successfully using XML view files in CakePHP (request the XML output type in headers so CakePHP will use e.g. Orders/xml/create.ctp instead of Order/create.ctp).
However, now i need to add some functionality that requires me to the reformat the XML at the end of most business logic in the controller.
So i tried this in the controller action:
public function createorder() {
$this->autoRender = false; // disable automatic content output
$view = new View($this, false); // setup a new view
{ ... all kinds of controller logic ...}
{ ... usually i would be done here and the XML would be outputted, but the autorender will stop that from happening ... }
{ ... now i want the XML in a string so i can manipulate the xml ... }
$view_output = $view->render('createorder'); // something like this
}
But what this gives me is:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<error>View file "/Users/test/Documents/hosts/mycakeapp/app/View/Orders/createorder.ctp" is missing.</error>
<name>MissingViewException</name>
<code>500</code>
<url>/orders/createorder/</url>
</response>
So i need to tell CakePHP to pickup the xml/createorder.ctp instead of createorder.ctp. How do i do this?
Cheers!
This answers refers to cakephp 2.4
I have been successfully using XML view files in CakePHP (request the XML output
type in headers so CakePHP will use e.g. Orders/xml/create.ctp
instead of Order/create.ctp).
In lib/Cake/View you can see different View files like:
View.php
XmlView.php //This extends View.php
JsonView.php //This extends View.php
So you told cakephp to use the XmlView. When you create a new View you need to use the XmlView instead of View. Or you can create your own custom View and put it inside app/View folder. In your custom View you can set your subdir.
<?php
App::uses('View', 'View');
class CustomView extends View {
public $subDir = 'xml';
public function __construct(Controller $controller = null) {
parent::__construct($controller);
}
public function render($view = null, $layout = null) {
return parent::render($view, $layout);
}
}
So what you need now is to create your custom view $view = new CustomView($this, false);
You can also write in your CustomView functions to handle the data as xml and use it to every action.
Also #Jelle Keizer answer should work. $this->render('/xml/createorder'); points to app/View/xml/createorder. If you need this to point to app/View/Order/xml/create just use $this->render('/Orders/xml/create');.
$this->render('/xml/createorder');
I'm trying to integrate Fotolia Api with Prestashop 1.6.0.9.
I already make module with custom tab, but I have no idea how set view from module folder for this tab. Sorry to say, but "documentation for developers" SUCKS.
I can't find any working solution.
public function install() {
if (!parent::install()
|| !$this->registerHook('backOfficeHeader')
|| !$this->registerHook('header')
) return false;
$tab = new Tab();
$tab->class_name = 'AdminFotoliaSelector';
$tab->id_parent = 0;
$tab->module = $this->name;
$tab->name[(int)(Configuration::get('PS_LANG_DEFAULT'))] = 'Fotolia Selector';
$tab->add();
return true;
}
I had big problem with make proper controller, and now I just can't load anything/ I have no idea how do this.
<?php
if (!defined('_PS_VERSION_'))
exit;
class AdminFotoliaSelectorController extends ModuleAdminController {
public $name;
public function __construct() {
$this->lang = (!isset($this->context->cookie) || !is_object($this->context->cookie)) ? intval(Configuration::get('PS_LANG_DEFAULT')) : intval($this->context->cookie->id_lang);
parent::__construct();
}
public function initContent() {
parent::initContent();
$this->renderForm();
}
public function renderForm() {
$path = _MODULE_DIR_."fotoliaselector";
$more = $this->module->display($path, 'views/templates/admin/fotoliaselector.tpl');
return $more.parent::renderForm();
}
When I try die($more) it gives me content of .tpl, anyway when I click tab in back office it's still empty.
I have debug options on, compiling on, cache off.
So just enlight me please, how am I supose to show ANYTHING there?
I think the problem is that you don't display tab's content at all.
I don't know what module->display method does, but I think you should change in initContent() method line:
$this->renderForm();
into
echo $this->renderForm();
If it won't help you should look at this documentation and try to do it without external classes - only try to use Smarty to display simple content without using Tab class or AdminFotoliaSelector
Well i know it will sounds weird but you need to take some similar modules, and read his code and will see some methods names are the same in each module.
Then copy that, install and play with some changes etc.
Imho you miss standard method getContent() form where you need to pass some data for smarty:
public function getContent()
{
global $smarty, $cookie;
......
//some code
......
$this->_html .= '<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>';
$this->_html .= '<h1>My module title or stuff</h1>';
$this->_html .= $this->getMyCoolFormOrConfig();
$smarty->assign('errors', $this->errors);
$smarty->assign('message', $this->message);
$this->_html .= $this->display(__FILE__, 'name_of_tpl_file.tpl');
return $this->_html;
}
to simple add tab in BackOffice code like this:
$id_tab=Tab::getIdFromClassName('AdminPayment');
$newtab=new Tab();
$newtab->id_parent=$id_tab;
$newtab->module=$this->name;
$newtab->class_name='MyClassName'; //will be same like MyClassName.php in folder of you module where you need to create you class and extend the AdminTab and from there with function you need to echo you name module
$newtab->position=Tab::getNbTabs($id_tab)+1;
$newtab->name[$cookie->id_lang]=$this->l("Name of you stuff");
$newtab->name[Configuration::get('PS_LANG_DEFAULT')]=$this->l("Name of you stuff");
$newtab->add();
Study this file there /controllers/admin/AdminModulesController.php
and you see what methods are using in each module
Take a look greater feature to generate you module structure (register requeired) https://validator.prestashop.com/generator
I need to compose a web page of several view templates (the view template rendering page content and a view template rendering sidebar). In my layout.phtml, I have two variable placeholders: $content and $sidebar:
......
<?php echo $this->sidebar; ?>
......
<?php echo $this->content; ?>
......
In my controller's action, I pass the data to these view templates through the ViewModels chained in a tree:
public function indexAction() {
// Preparing my data
// $form = ...
// $menuItems =
// $activeItem =
// Create sidebar view model
$sidebarViewModel = new ViewModel(array('menuItems'=>$menuItems, 'activeItem'=>$activeItem));
// Add it as a child to layout view model
$this->layout()->addChild($sidebarViewModel, 'sidebar');
// Page content view model
$viewModel = new ViewModel(array('form'=>$form));
return $viewModel;
}
But, because I have the sidebar on every page, I will have to copy and paste this code for every action of every controller. Is there any recommended way of reusing the code that populates the ViewModel for sidebar?
One approach would be to achieve this with a controller plugin.
Assuming you have wired it up with appropriate config, and you're in the Application module.
In module/Application/src/Application/Controller/Plugin/AddSidebar.php:
namespace Application\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class addSidebar extends AbstractPlugin {
public function __invoke($menu, $active) {
// create new view model
$sidebarVM = new ViewModel(array(
'menuItems' => $menu,
'activeItem' => $active
));
// add it to the layout
$this->getController()->layout()->addChild($sidebarVM, 'sidebar');
}
}
Then in each of your controllers:
$this->addSidebar($menuItems, $activeItem);
Another (probably better) option would be to hook into the render MvcEvent and add the sidebar there. You'd have to work out how to generate $menuItems and $activeItem in that context however.
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.