I have developed a code that contains a aquery which returns ratings of a product in json format. The code is as follows:
<?php header('content-type: application/json; charset=utf-8');
require_once('/opt/phpapps/magento/app/Mage.php');
umask(0);
Mage::app();
$cid=$_GET['catid'];
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = "SELECT round(t1.rating_summary / 20) AS rating, t2.product_id FROM review_entity_summary AS t1 INNER JOIN catalog_category_product AS t2 ON t1.entity_pk_value = t2.product_id WHERE category_id =" . $cid . " AND store_id = '1'";
$results = $read->fetchAll($query);
$json = json_encode($results);
print_r( $json );
?>
I am instructed to convert this into MVC pattern. I knew that MVC can be done by creating separate folders like blocks, controllers, models,sql,etc, helpers folders. But I am not sure what is the next stepa nd how to execute the developed to get the json data..
Help me in this...
The best way to is create a custom Extension/Model, there's a lot of tutorials out there to do this, however you could use something to generate an example for you to get started:
http://www.silksoftware.com/magento-module-creator/
However, for something this simple you could just create a custom block in the local namespace, for example:
app/code/local/Mage/Catalog/Block/Product/Ratingsjson.php
<?php
/**
* Ratingsjson.php
*/
class Mage_Catalog_Block_Product_Ratingsjson extends Mage_Catalog_Block_Product_Abstract
{
/**
* Get products with special offer attribute set
*
* #return type
*/
public function getRatings()
{
/**
* This will be injected from the tag / XML below
* you can pass what ever variables you want this way.
* getSomeAttribute() will get the value 'some_attribute' from the
* CMS tag or XML config.
*/
$categoryId = $this->getCategoryId();
if($categoryId == NULL) {
$categoryId = 1; // or some default;
}
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
// Do your stuff here...
$query = "SELECT round(t1.rating_summary / 20) AS rating, t2.product_id FROM review_entity_summary AS t1 INNER JOIN catalog_category_product AS t2 ON t1.entity_pk_value = t2.product_id WHERE category_id =" . $cid . " AND store_id = '1'";
$results = $read->fetchAll($query);
return json_encode($results);
}
}
Create a template to do what you want:
template/mymodeule/mytemplate.phtml
<?php
echo $this->getRatings();
You can then use your new block inside CMS pages:
{{block type="catalog/ratignsjson" category_id="3" temaplte="mymodeule/mytemplate.phtml"}}
Or if you want to load it via XML config:
<block type="catalog/ratignsjson" category_id="3" name="ratignsjson" template="mymodeule/mytemplate.phtml"/>
To do this properly and output strict Json data you would want to set json content type headers etc but I think that's a little too much for this particular case.
Related
I extended tx_news to hold a number of courses. there are courses that treat the same subject matter for different arguments (which I select as sys_categories). This means that their title is identical, now I'm trying to make the list better for the editor by including the selected category in the list...
Imply a custom title in Configuration/TCA/Overrides/tx_news_domain_model_news.php:
$GLOBALS['TCA']['tx_news_domain_model_news']['ctrl']['label_userFunc'] = 'Vendor\\NewsExt\\Userfuncs\\Tca->customTitle';
The userfunction so far Classes/Userfuncs/Tca.php:
<?php
namespace Vendor\NewsExt\Userfuncs;
use GeorgRinger\News\Domain\Model\News;
/**
* Class Tca
*/
class Tca
{
/**
* Loads a custom title for the news list view
*
* #return void
*/
public function customTitle(
&$parameters,
$parentObject
){
$record = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord($parameters['table'], $parameters['row']['uid']);
$newTitle = $record['title'];
if($record['is_course']){
$newTitle .= ' (' . $record['categories'] . ')' ;
}
$parameters['title'] = $newTitle;
}
}
which obviously gives the number of selected categories ... I did not include any of my attempts because they lead to nothing ...
You can make an mm query to resolve the assigned category title:
<?php
namespace Vendor\NewsExt\Userfuncs;
use GeorgRinger\News\Domain\Model\News;
/**
* Class Tca
*/
class Tca
{
/**
* Loads a custom title for the news list view
*
* #return void
*/
public function customTitle(&$parameters, $parentObject)
{
# fetch all categories assigned to this news
$result = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
'sys_category.uid, sys_category.title',
'sys_category',
'sys_category_record_mm',
$parameters['table'],
'AND sys_category_record_mm.tablenames = "' . $parameters['table'] . '" ' .
'AND sys_category_record_mm.fieldname = "categories" ' .
'AND sys_category_record_mm.uid_foreign = ' . $parameters['row']['uid']
);
# walk the categories an get the title of them
$categoriesLabels = [];
foreach ($result->fetch_all(MYSQLI_ASSOC) as $category) {
$categoriesLabels[] = $category['title'];
}
# if at least one category put them into the title
if (!empty(array_filter($categoriesLabels))) {
$record = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord($parameters['table'], $parameters['row']['uid']);
$parameters['title'] = $record['title'] . ' ('. implode(', ', $categoriesLabels) .')';
}
}
}
Note: This code is was tested in TYPO3 8.7.12
Probably you've to make a custom database-query at best in an own repository where you request each applying category to get the title.
It's possible that you can use the Repository of tx_news for avoiding redundant code but surely you've to include some code / function that is instantiating the request - where ever the request is addressed to.
How can i get the value ,what i set by addStatusHistoryComment while creating order by php script.
$order = $observer->getEvent()->getOrder();
$dbOrderId = $order->getId();
$MagOrderId = $order->getRealOrderId();
Mage::log('dbOrderId : '. $dbOrderId);
Mage::log('MagOrderId : '. $MagOrderId);
I need to get like something $order->getStatusHistoryComment()
it is not working.
Need help.
The following data is not working as order is not commit yet.
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "SELECT comment FROM sales_flat_order_status_history WHERE parent_id=' $dbOrderId' limit 1 ";
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
foreach ($connection->fetchAll($sql) as $arr_row) {
$comments=$arr_row['comment'];
Use getStatusHistoryCollection instead of getStatusHistoryComment and it should work. The method is defined in Mage_Sales_Model_Order.
Or you can use getVisibleStatusHistory if you want only the comments visible on frontend.
I would like to retrieve the default product thumbnail in Magento to apply it to something else other than a product, so I don't have access to $product. Would it be possible?
Thanks,
Krt_Malta
Untested but this should work:
/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');
/**
* Retrieve the read connection
*/
$readConnection = $resource->getConnection('core_read');
$query = 'SELECT thumbnail FROM ' . $resource->getTableName('catalog/product_flat') . ' WHERE sku = "(insert your product SKU here)"'; // Insert SKU here
/**
* Execute the query and store the results in $results
*/
$results = $readConnection->fetchAll($query);
/**
* Print out the results
*/
echo sprintf('<pre>%s</pre>' print_r($results, true));
I am trying to display a category name in a module position.
I tried:
<?php echo $listing['Category']['title'];?>
It did not work.
I followed this link, but it shows the article title and I need the category one.
I'm working on Joomla 1.7.
Much more simple answer:
<?php echo $this->escape($this->item->category_title);?>
As per the posters comment in the OP:
<?php
$db = &JFactory::getDBO();
$id = JRequest::getString('id');
$db->setQuery('SELECT #__categories.title FROM #__content, #__categories WHERE #__content.catid = #__categories.id AND #__content.id = '.$id);
$category = $db->loadResult();
echo $category;
?>
Travega is really close, his code works on pages, but not on category pages.
When you use $id = JRequest::getString('id'); on a category page (such as a category blog or list page) the id of the category is returned. This means we need more context of the id variable, in this case the 'view'.
Here is my modified version of travega's code:
function getCategoryName() {
//Modified from: http://stackoverflow.com/questions/8928967/joomla-display-catagory-name-in-template
$db = &JFactory::getDBO();
$id = JRequest::getString('id');
$view = JRequest::getString('view');
if ($view == 'category') {
$sql = "SELECT title FROM #__categories WHERE #__categories.id = $id";
} else {
$sql = "SELECT #__categories.title FROM #__content, #__categories WHERE #__content.catid = #__categories.id AND #__content.id = $id";
}
$db->setQuery($sql);
$category = $db->loadResult();
return $category;
}
Other relevant info:
I've only tested this on Joomla 2.5.3 on cat blog and cat list pages. I've not tested it on anything other than com_content component. This means it probably won't work on weblink, contact, etc pages as you may again loose the context.
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.