Magento Product Images Full URL Path Instead of Cached - magento

The code below works for products that have images, but for products that don't have images, the placeholder small image doesn't show.
echo Mage::getModel('catalog/product_media_config')->getMediaUrl( $_product->getSmallImage());

<?php
// get image full url
echo $imageUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product' . $_product->getImage();
// get image using custom size with url
echo $imageCacheUrl = Mage::helper('catalog/image')->init($_product, 'image')->resize(135,135);
?>

The code that affects what you want to do is
//file: app/code/core/Mag/Catalog/Helper/Image.php
//class: Mage_Catalog_Helper_Image
/**
* Return Image URL
*
* #return string
*/
public function __toString()
{
try {
//...
} catch (Exception $e) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
The interesting line is
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
So in your code you need to test the return value of $_product->getSmallImage() and if it is false or null use Mage::getDesign()->getSkinUrl($this->getPlaceholder()); instead.
You might want to inspect $_product->getSmallImage() to see what it returns when no value is set.
Oh, and I just checked: getPlaceholder() is a function not a magic getter. This is the function:
public function getPlaceholder()
{
if (!$this->_placeholder) {
$attr = $this->_getModel()->getDestinationSubdir();
$this->_placeholder = 'images/catalog/product/placeholder/'.$attr.'.jpg';
}
return $this->_placeholder;
}
So you will have to unravel some $this (hint $this->_getModel() is Mage::getModel('catalog/product_image') )
or to cut a long story short just fall back to the default:
echo ($this->helper('catalog/image')->init($_product, 'small_image'));
in your phtml file if $_product->getSmallImage() doesn't exist.
Update following your comment:
Specifcically in the .phtml file that you are using to generate the HTML that displays the small image you could write:
$testSmallImageExists = $_product->getSmallImage();
if($testSmallImageExists)
{
echo Mage::getModel('catalog/product_media_config')->getMediaUrl( $_product->getSmallImage());
}
else
{
echo ($this->helper('catalog/image')->init($_product, 'small_image'));
}
Or just simply use
echo ($this->helper('catalog/image')->init($_product, 'small_image'));
I'm sure that is the standard Magento way.

Related

JOOMLA 3.x How to hide a template after if check

I'm trying to understand Joomla language and I have this situation:
In a models/calcoloonline.php I have this function
public function estraivariabili()
{
$db = JFactory::getDBO();
// Put the result into a variable first, then return it.
$value = $db->setQuery("SELECT * FROM #__calcolo_imposte")->loadObjectList();
if ($value != NULL)
{
return $value;
}
else
{
return JFactory::getApplication()->enqueueMessage(JText::_('COM_CALCOLO_IMPOSTE_IMPORTI_NON_DEFINITI'), 'type');
}
}
This works perfectly but I'd like that after check if the return is NULL I want to hide display default.php and show only the message on JText.
How can I do this?
For your purpose, you just return the $value from the model function and call the function at view.html.php's display() function.
At default.php file check the availability of the $value and show your contents.
For example, you store the data at view.php.html. It looks like
public function display($tpl = null)
{
$model = $this->getModel();
$this->value = $model->estraivariabili();
return parent::display($tpl);
}
And your default.php file would be
<?php if (!empty($this->value)) { ?>
<h1>The value is not empty.</h1>
<?php } else {
// value not found :(
JFactory::getApplication()->enqueueMessage(JText::_('NOT_FOUND_MESSAGE'), 'warning');
} ?>

Magento: Canonical Link disappeared

I have modified the _prepareLayout() function in Mage_Catalog_Block_Category_View class to have a customized canonical url. After modifying the URL, the canonical code does not display in the html source code anymore.
Here are my codes:
protected function _prepareLayout() {
Mage_Core_Block_Template::_prepareLayout();
$this->getLayout()->createBlock('catalog/breadcrumbs');
if ($headBlock = $this->getLayout()->getBlock('head')) {
$category = $this->getCurrentCategory();
if ($title = $category->getMetaTitle()) {
$headBlock->setTitle($title);
}
if ($description = $category->getMetaDescription()) {
$headBlock->setDescription($description);
}
if ($keywords = $category->getMetaKeywords()) {
$headBlock->setKeywords($keywords);
}
if ($this->helper('catalog/category')->canUseCanonicalTag()) {
//$headBlock->addLinkRel('canonical', $category->getUrl());
if ($category->getCategoryUrlAlias()) {
$url = Mage::getBaseUrl() . $category->getCategoryUrlAlias();
} else {
$key = $this->helper('my_package/category')->getIsTitleCategoryKey($category);
$url = $category->getUrl();
$url = $this->_removeKeyFromUrl($url, $key);
}
$headBlock->addLinkRel('canonical', $url);
}
/*
want to show rss feed in the url
*/
if ($this->IsRssCatalogEnable() && $this->IsTopCategory()) {
$title = $this->helper('rss')->__('%s RSS Feed', $this->getCurrentCategory()->getName());
$headBlock->addItem('rss', $this->getRssLink(), 'title="' . $title . '"');
}
}
return $this;
}
I have verified that the $url variable always have the customized url value that I want. I'm wondering if there is any validation function that's preventing me to have a customized canonical URL?
Any help will be greatly appreciated. Thanks!

Redirect , POST and Flashdata issue in Codeigniter

i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.

How to test a Magento Block

I want to test a Magento block function. I don't know, how to call the function outside .phtml files. Does anybody know a function like getModel() for blocks?
I found
getBlockSingleton()
But, it is deprecated and I can't get it to work.
Let's say your Magento root is your web root. In your Magento root, create a test.php file. You'll be able to access it at http://base_url/test.php.
ini_set('display_errors',true); //PHP has such friendly errors, show them!
include 'app/Mage.php'; //include the helper class/bootstrap file
Mage::setIsDeveloperMode(true); //flag to render Magento's traces
Mage::app();
/**
Instantiate the app. Note that this is different from Mage::run()! This can
be skipped given the Mage::app() call below.
*/
//block "type"
$class = 'core/bar';
//block instance
$block = Mage::app()->getLayout()->createBlock($class);
if (is_object($block)) die("Okay! ".get_class($block));
/**
* If script execution reaches this point, there is one of
* two problems:
*
* 1) bad/missing config
* 2) bad path based on filename
*/
//the xpath which is used
$xpath = 'global/blocks/'.strstr($class,'/',true).'/class';
//a node from config XML (we hope)
$node = Mage::getConfig()->getNode($xpath);
//error condition 1:
if (!$node) die("Bad xpath, check configuration: ".$xpath);
//error condition 2:
$name = uc_words((string) $node . '_' . substr(strrchr($class, '/'), 1));
$file = str_replace('_', DIRECTORY_SEPARATOR, $name.'.php');
$issue = '<br /><br />';
if (!is_readable($file)) {
//no file matching classname
$issue .= "No file found for $file, tried:<pre> - ";
$issue .= str_replace(PATH_SEPARATOR,'/'.$file.'<br /> - ',get_include_path()).$xpath.'</pre>';
} else {
$issue .= "Wrong class name in $file";
}
echo sprintf('Xpath ok, looking for class <span style="font-family: Courier New">%s</span>%s',$name,$issue);
If you just need the block instance itself to test methods on, the following function may do:
/**
* Create block instance for given block classAlias.
*
* #param string $classAlias Magento class alias for this block, e.g. 'catalog/product_price'
*
* #return Mage_Core_Block_Abstract
*/
public static function getBlockInstance($classAlias)
{
$className = Mage::getConfig()->getBlockClassName($classAlias);
$result = new $className;
return $result;
}

How to make link in joomla

hi i am new in joomla.I need the dynamic link in view file.
//no direct access
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
// include the helper file
require_once(dirname(FILE).DS.'helper.php');
// get a parameter from the module's configuration
$userCount = 5;
// get the items to display from the helper
$items = ModNewHelper::getItems($userCount);
//link of the component
// include the template for display
require(JModuleHelper::getLayoutPath('mod_new'));
this is main file
/**
* #author Raju Gautam
* #copyright 2011
*/
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
class ModNewHelper
{
/**
* Returns a list of post items
*/
public function getItems($userCount)
{
// get a reference to the database
$db = &JFactory::getDBO();
// get a list of $userCount randomly ordered users
$query = 'SELECT name,id FROM `#__hello` ORDER BY ordering LIMIT ' . $userCount . '';
$db->setQuery($query);
$items = ($items = $db->loadObjectList())?$items:array();
return $items;
} //end getItems
} //end ModHelloWorld2Helper
this is helper file
defined('JEXEC') or die('Restricted access'); // no direct access
echo JText::('Latest News');
//echo ""; print_r($items); exit;
foreach ($items as $item) {
echo JText::sprintf($item->name);
} this is view file
I need the link on echo JText::sprintf($item->name); this line. can i helped please?
change your this line from view file:
echo JText::sprintf($item->name);
to :
echo "<a href='".$item->link."'>". JText::sprintf($item->name)."</a>";
assuming, link is the field name of your link else change it according to the field name you've used for link. this may help, i guess .. good luck with it.
use
echo "<a href='".JRoute::_($item->link, false)."'>". JText::sprintf($item->name)."</a>";
JRoute will take care of routing also, if routing is enabled.

Resources