Best to call a template within a template Magento - magento

So I have been working on a Magento module that hides the price when the user is not logged in. I got it working thanks to #AlanStorm but I just want to make sure it I'm going for the best approach.
What I did is setting a different template for the *catalog_product_price_template* block and from there I did all the logic
<?php $_message = Mage::getStoreConfig('catalog/pricehideconfig/title');
$_enabled = Mage::getStoreConfig('catalog/pricehideconfig/active');
$_current_template = Mage::getBaseDir('design')
. '/frontend/'
. Mage::getSingleton('core/design_package')->getPackageName() . '/'
. Mage::getSingleton('core/design_package')->getTheme('frontend') .'/'
. 'template/catalog/product/price.phtml';
$_default_template = Mage::getBaseDir('design') . '/frontend/base/default/template/catalog/product/price.phtml';
?>
<p>
<?php if ( $_enabled && !($this->helper('customer')->isLoggedIn()) ) { ?>
<?php echo $_message; ?>
<?php } else {
if (file_exists($_current_template)){
include $_current_template;
} else{
include $_default_template;
}
} ?>
</p>
However, two parts seems really unnatural
Calling the 'original' or default template code for the price doesnt feel right, does Magento provides any function to do this, call the default template within a template, while checking if the template exists in the current package and then revert back to the default if none?
I think the template should be used for presentation only, so the variables assignment should be moved to a block instead, but i can't really do that since I'm just setting the template and not extending the *Mage_Catalog_Block_Product_Price_Template*

I don't really understand the code above !!
if you want to hide price from non-logged in customers the easiest and best way i have used is :
The Module will be Only one Block and the config.xml
Extend - Rewrite class Mage_Catalog_Block_Product_Price
class Namespame_ModuleName_Block_Product_Price extends Mage_Catalog_Block_Product_Price
{
// and Override _toHtml Function to be
protected function _toHtml()
{
if(!$this->helper('customer')->isLoggedIn()){
$this->getProduct()->setCanShowPrice(false);
}
if (!$this->getProduct() || $this->getProduct()->getCanShowPrice() === false) {
return '';
}
return parent::_toHtml();
}
}
This works perfectly without adding more codes to view/template/layout !
If you still want to set Template you can do it also as :
class Namespame_ModuleName_Block_Product_Price extends Mage_Catalog_Block_Product_Price
{
// and Override _toHtml Function to be
protected function _toHtml()
{
if(!$this->helper('customer')->isLoggedIn()){
$this->setTemplate('mymodule/price_template.phtml');
}
if (!$this->getProduct() || $this->getProduct()->getCanShowPrice() === false) {
return '';
}
return parent::_toHtml();
}
}
Thanks

Related

Laravel access blade variable in helper

I have a public variable $publisher shared to all view:
$view->with('publisher', $publisher);
Example: I would like to check this publisher is named as 'main' and is status 'active', hence I have to write if statement in blade like this:
#if ($publisher->name == 'main' && $publisher->status == 'active')
// Code here
#endif
It's replicated for all the blade file, therefore I created a custom helper file at app/Helpers/general.php, named it as isMainPublisher($publisher):
function isMainPublisher($publisher)
{
return ($publisher->name == 'main' && $publisher->status == 'active') ? true: false;
}
The blade if statement will be changed to:
#if (isMainPublisher($publisher))
// Code here
#endif
I am thinking to shorten the blade code to this:
#if (isMainPublisher())
// Code here
#endif
But app/Helpers/general.php will not access the blade variable $publisher, is there anyway or actually no way to access blade variable in helper? Thanks.
Essentially, short of setting the publisher name on an internal variable of the helper class, isMainPublisher($publisher) is your best choice, AND its way more idiomatic than the other option.
In order to get isMainPublisher() to work (possibly), you would have to work with a hacky global declaration, which even then, would probably not work as it is not available to the class
ALTERNATIVELY, you could add the helper onto the model as a method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Publisher extends Model
{
// Your new helper method
public function isMain()
{
// some logic to determine if the publisher is main
return ($this->name == "main" || $this->name == "blah");
}
}
...and then call it like this:
$publisher->isMain();
Which in my point of view, is the superior choice as it reads like you'd say it.
I hope this helps!

How to interact with prestashop data using ajax?

I have a prestashop store, I wish to add some interactivity in the shop but for that purpose I need to fetch some data about the products from the database. I tried to search the prestashop docs but didn't find anything useful.
How can I interact with prestashop's products data using ajax?
You can make a php file where you want (root folder is ok) and and start the "enviroment" like this
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
echo("<br />a log string " . date("H:i:s d/m/Y"));
error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT);
// here you have all prestashop class
$myCategory = new Category($id)
after that you reach your's php in your ajax call
1- Go to : https://validator.prestashop.com/auth/login
2- create a generic module (more fast)
3- create folder controllers/front/ajaxmain.php (example)
add:
<?php
class YOURMODULENAMEAjaxmainModuleFrontController extends ModuleFrontController
{
public function __construct()
{
parent::__construct();
$this->context = Context::getContext();
}
public function initContent()
{
parent::initContent();
if (Tools::isSubmit('anysubmitname'))
{
$this->getproduct();
}
//or Tools::getvalue("anyvalue")....
}
private function getproduct(){
// do your magic
die(json_encode(array(
"response"=> "response"
) ));
}
Then, call it -> index.php?fc=module&module=test&controller=ajaxmain
I think that this is more clean, then you can get more things with this

Magento $this->__('Create an Account')

In Magento $this->__('Create an Account') How this echo Create an Account?
abstract class Mage_Core_Helper_Abstract{ public function __()
{
$args = func_get_args();
$expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
array_unshift($args, $expr);
return Mage::app()->getTranslator()->translate($args);
}
I saw that __ function in Mage_Core_Helper_Abstract Class.but i cant understand Mage::app()->getTranslator()->translate($args) what's happending in that getTranslator function.
public function getTranslator()
{
if (!$this->_translator) {
$this->_translator = Mage::getSingleton('core/translate');
}
return $this->_translator;
}
Mage::getSingleton('core/translate') what's happening there ? and why in this function call like core/translate which file its denote and how it Create an Account text?
You might search how the magento translator works
What ever text is written in $this->_('') will dynamically translated to the current locale which is loaded in your current store(That text must be specified in magento-root/app/locale//.csv)
I think the below answer might be helpfull
How does Magento translate works?

How To Start Using Kostache?

I just asked a question ( Templates In Kohana 3.1 ) about templates and now I know that I should use Kostache. It's a module for the Mustache template language.
Anyway, I just enabled Kostache module for my Kohana 3.1 and all works. It's installed correctly! What to do next? How to use it?
Where should I put my views now?
What my controller should extend?
How to assign variable?
How to make header, footer etc. for views?
Maybe there are step to step guide for it? This and this won't help me a lot...
Where should I put my views now?
View classes contain logic for your templates and by convention should be stored in classes/view/{template name}.php
Templates contain your HTML and should be stored in the templates directory in the root of your module, e.g. templates/login.mustache
By default kostache will try and work out the location of the template based on your view class' name.
If your view class is called View_Admin_Login then kostache will look for templates/admin/login.mustache
What my controller should extend?
You do not need to extend any special controllers, the normal Controller will work fine as a base.
How to assign variable
Controller:
$view = new View_Admin_Login;
$view->message = 'Hello';
$this->response->body($view->render());
Template:
{{message}}
Of course, any methods or variables you declare in your view class will also be available in
the template. If there is a class variable and method with the same name then the method will always take precedence over the variable.
How to make header, footer etc. for views
It will help if you read the kostache guide. The idea is that your views extend Kostache_Layout, see also the layout template
There's lots of demos and examples in both of the repositories that you said won't help you.
Try this...
//application/classes/controller:
class Controller_Test extends Controller {
public function action_index()
{
$view = new View_Home;
$this->response->body($view->render());
}
}
//application/classes/view/Home.php:
class View_Home {
public $name = "Chris";
public $value = 10000;
public function taxed_value() {
return $this->value - ($this->value * 0.4);
}
public $in_ca = true;
protected $_layout = 'home';
}
//application/templates/home.mustache:
Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{ taxed_value }}, after taxes.
{{/in_ca}}
In your APPPATH/classes/controller/Test.php:
class Controller_Test extends Controller{
public function action_index()
{
$renderer = Kostache::factory();
$this->response->body($renderer->render(new View_Test));
}
}
In your MODPATH/KOstache/classes/view/Test.php:
class View_Test
{
public $name = "Chris";
public $value = 10000;
public function taxed_value() {
return $this->value - ($this->value * 0.4);
}
public $in_ca = true;
}
In your MODPATH/KOstache/classes/templates/test.mustache:
Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{ taxed_value }}, after taxes.
{{/in_ca}}
In the following example, do not pay attention to naming classes and inheritance:
More examples on GitHub

Magento createBlock method not working, displaying static block data

Ok so Ive created static blocks in my CMS area, and Im trying to output them inside of a custom homepage template Ive built.
Every document I can find says to output the block as follows
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my-block-identifier')->toHtml() ?>
That didnt work for me, so then I tried another way. --
<?php $block = Mage::getSingleton('core/layout')->createBlock('cms/block')->setBlockId('my-block-identifier');
echo $block->toHtml();
All the sites referencing this tell me to use the actual blocks identifier to get the block. So then I decide to manually lookup the block_id in my cms_block table and see if using the block_id number in place of the literal my-block-identifier name will work - and it did. So I am confused... Can anyone tell me how I can get the block by the actual identifier, or look up the blocks id by the identifier so that I can grab the block by block name?
Any help much appreciated.
Looking at the cms/block block source, those tutorials have mislead you, or you misinterpreted them.
#File: app/code/core/Mage/Cms/Block/Block.php
class Mage_Cms_Block_Block extends Mage_Core_Block_Abstract
{
protected function _toHtml()
{
if (!$this->_beforeToHtml()) {
return '';
}
$html = '';
if ($blockId = $this->getBlockId()) {
$block = Mage::getModel('cms/block')
->setStoreId(Mage::app()->getStore()->getId())
->load($blockId);
if (!$block->getIsActive()) {
$html = '';
} else {
$content = $block->getContent();
$processor = Mage::getModel('core/email_template_filter');
$html = $processor->filter($content);
}
}
return $html;
}
}
The block content is always loaded with ->load($blockId); -- load with one parameter always means loding by a database ID.
So, with no supported way of doing this built into the block, you'll need to look up the block ID.
$model = Mage::getModel('cms/block')->getCollection()
->addFieldToFilter('identifier','footer_links')
->getFirstItem();
var_dump($model->getBlockId());
In the admin, when you are editing the contents of the static block, you will see a field called Identifier second from the top. Copy the value of that field, and insert it into your code. So if your Block is called contact-info in the admin, then your code will look like:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('contact-info')->toHtml() ?>
The value in that Identifier textbox in the admin is also what will be saved into the cms_block table, as you're worked out.
HTH,
JD

Resources