Joomla: Write and call a helper function in a component - joomla

Fledgling Joomla / PHP developer, hitting a wall understanding how to do this. Everything I found searching has been for older versions of Joomla or other frameworks and so it's all confusing the first time around.
I want to have a helper function that I can call from anywhere in my component. Basically it takes a userID input and returns their full name, let's say hair color and height. Here's the function:
function get_profile_info($userID) {
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->SELECT('u.id as UserID
, u.name AS Name
, up.profile_value AS Hair
, up2.profile_value AS Height
');
$query->FROM (' #__users AS u');
$query->LEFTJOIN (' #__user_profiles AS up ON u.id = up.user_id AND up.ordering = 1');
$query->LEFTJOIN (' #__user_profiles AS up ON u.id = up.user_id AND up.ordering = 2');
$query->WHERE(' u.id = '.$userID.'');
$query->GROUPBY (' u.id
, u.name
, up.profile_value
');
$db->setQuery($query);
return $query;
}
I'd put this in a file called "lookups.php" within the "helpers" folder of my component...but here's where I'm not sure what to do next. Top of lookups.php has the obligatory:
<?php defined ( '_JEXEC' ) or die;
So two questions:
1) Do I put everything in a class or keep it as a series of functions (since there will be others)?
2) How do I pass the userID and get back the values of Name, Hair, and Height in the view (view.html.php / default.php)?
Thank you!
==================================
Edit: Based on #Shaz 's response below here's where I'm at (again, just starting off and trying to wrap my head around some of this):
lookups.php
abstract class LookupHelper {
var $Name;
var $Hair;
var $Height;
public function get_profile_info($userID) {
...
(same as above until the next line)
$db->setQuery($query);
$result=$db->loadRow();
$Name = $result[1];
$Hair = $result[2];
$Height = $result[3];
$getprofileinfo = array(Name=>$Name, Hair=>$Hair, Height=>$Height);
$return $getprofileinfo;
}
}
Then in my default.php (will probably move to view.html.php):
$getprofileinfo = Jview::loadHelper('lookups'); //got an error without this
$getprofileinfo = LookupHelper::get_profile_info($userID);
$Name = $getprofileinfo[Name];
$Hair = $getprofileinfo[Hair];
$Height = $getprofileinfo[Height];
So...it's working - but it seems like there's a much easier way of doing this (specifically manually creating an array then recalling by position). Thoughts?
Thank you!!

Create the helper class and include there all your functions:
abstract class HelloWorldHelper
{
/* functions */
}
Call the function and store the result:
$var = HelloWorldHelper::get_profile_info($thatId);

Is not possible to write your helper class inside of an existing helper Joomla file that's already being calling by all your components?
By default Joomla have helper classes doing stuff, so all you have to do is to expand the core helper classes with your owns.

Related

Load view by current URL last segment in Codeigniter

I'm trying to load view content page when url last segment matched. When click a link which get link in url like http://192.168.20.2/vtp/attendance/rawAttendance then load the rawAttendance view and when I click other link which last segment is getAttendance then it's also load the same same view not getAttendance. How do get this done?
$last = $this->uri->total_segments();
$lastSegment = $this->uri->segment($last);
if ($this->input->post("fromAjax")) {
if($lastSegment == "rawAttendance"){
$this->load->view('attendance/rawAttendance', $data);
}else if($lastSegment == "getAttendance"){
$this->load->view('attendance/getAttendance', $data);
}else {
}
}
CI has its inbuilt helper for knowing controller name and method name.
$classname = $this->router->fetch_class();
$methodname = $this->router->fetch_method();
if ($this->input->post("fromAjax")) {
if($classname == "attendance" && $methodname == "rawAttendance"){
$this->load->view('attendance/rawAttendance', $data);
}else if($classname == "attendance" && $methodname == "getAttendance"){
$this->load->view('attendance/getAttendance', $data);
} else {
}
}
CodeIgniter is a basic MVC framework - so everything starts with the controller. From the code you've written, I assume you already have your routes, etc configured to point at the method you've placed in your question.
You can simplify things quite a bit from the way you have them. Using the CI helper for controller/method is a bit helpful, but I think you're looking for something a little more elastic in your approach to dynamically load a view based on your last URI segment.
Try something like this:
// Get your last URI segment
$last = $this->uri->total_segments();
$lastSegment = $this->uri->segment($last);
/**
* Do whatever logic you need to do to calculate your data
*/
// ...
/**
* Load the view
*/
$this->load->view( 'attendance/' . $lastSegment, $data );
This could probably be better architected using the CI routes capability though. For instance, if you have several view folders and view files within, it would be best practice to organize those and better cement your URI structures so that each URI segment plays a specific role:
CI routes.php
$route["vtp/(:any)/(:any)"] = "path_to_method";
Method
$dir = $this->uri->segment(2);
$view = $this->uri->segment(3);
$this->load->view( $dir . "/" . $view, $data );

magento get custom attribute label

I've a problem, I want to show the label of a custom attribute in the product page.
I explain me better, starting from this link because is what I want to do:
http://www.customy.com/blog/how-to-display-video-on-magento-product-page/
I want a video product in the sidebar of the product page, so I create a new custompage.phtml and i put this in the sidebar from catalog.xml, in my custompage.phtml I put this code to have the custom label:
getResource()->getAttribute('video')->getStoreLabel();?>
but I have this error:
"Fatal error: Call to a member function getResource() on a non-object in ..path//"
I have try different code but still have this problem.
I think that I forget to put something in my .phtml but I'm new of Magento and I don't know what!
Thank in advance!
Since $_product didn't work then you'll need to load the object before attempting to access the attribute. Try this:
$product_id = Mage::registry('current_product')->getId();
$_product=Mage::getModel('catalog/product')->load($product_id);
echo $_product->getResource()->getAttribute('video')->getStoreLabel();
If you don't have access to the product model, I wrote a small query to get it from DB. This could be done better, but should be a decent starting point for your class:
protected $_dbConn;
public function __construct()
{
$this->_dbConn = Mage::getSingleton('core/resource')->getConnection('core_read');
}
public function getAttributeLabel($code)
{
$query = "
SELECT b.value
FROM eav_attribute a
JOIN eav_attribute_label b
ON a.attribute_id = b.attribute_id
WHERE a.attribute_code = '".$code."'";
return $this->_dbConn->fetchOne($query);
}

Displaying in back end component the parameters of module(s) and saving them through component

Hi i kinda found the way to display the modules in the component but i am wondering how could i save the parameters through component i mean editing the values in component and saving it.
The modules names and paramaters are known in advance. So the calling will be like this
jimport( 'joomla.application.module.helper' );
$module = &JModuleHelper::getModule( "ModuleName");
$params = new JParameter($module->params);
The purpose of doing so is to ease editing certain values for the customer so it is a pain for a newbie to browse all that joomla stuff(in my case).
All in all cant figure out, how to save the params of a module(s)
Hi this is the code to save the params of a component, module or plugin in Joomla.
It first loads the current params, makes its changes, then saves again; ensure you always load the current params first.
$mparams = JComponentHelper::getParams( 'com_littlehelper' );
$params = $mparams->get('params');
$mparams->set('params.favicons_sourcepath','icons');
$this->saveParams($mparams, $this->componentName);
private function saveParams($params, $extensionName, $type='component') {
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where(sprintf('a.element = %s AND a.%s = %s',
$db->quote($extensionName),
$db->quoteName('type'),
$db->quote($type)
));
$db->setQuery($query);
return $db->execute();
}
This code comes from my extension LittleHelper published on the JED.

codeigniter count_all_results

I'm working with the latest codeIgniter released, and i'm also working with jquery datatables from datatables.net
I've written this function: https://gist.github.com/4478424 which, as is works fine. Except when I filter by using the text box typing something in. The filter itself happens, but my count is completely off.
I tried to add in $res = $this->db->count_all_results() before my get, and it stops the get from working at all. What I need to accomplish, if ($data['sSearch'] != '') then to utilize the entire query without the limit to see how many total rows with the search filter exists.
If you need to see any other code other than whats in my gist, just ask and I will go ahead and post it.
$this->db->count_all_results() replaces $this->db->get() in a database call.
I.E. you can call either count_all_results() or get(), but not both.
You need to do two seperate active record calls. One to assign the results #, and one to get the actual results.
Something like this for the count:
$this->db->select('id');
$this->db->from('table');
$this->db->where($your_conditions);
$num_results = $this->db->count_all_results();
And for the actual query (which you should already have):
$this->db->select($your_columns);
$this->db->from('table');
$this->db->where($your_conditions);
$this->db->limit($limit);
$query = $this->db->get();
Have you read up on https://www.codeigniter.com/userguide2/database/active_record.html#caching ?
I see you are trying to do some pagination where you need the "real" total results and at the same time limiting.
This is my practice in most of my codes I do in CI.
$this->db->start_cache();
// All your conditions without limit
$this->db->from();
$this->db->where(); // and etc...
$this->db->stop_cache();
$total_rows = $this->db->count_all_results(); // This will get the real total rows
// Limit the rows now so to return per page result
$this->db->limit($per_page, $offset);
$result = $this->db->get();
return array(
'total_rows' => $total_rows,
'result' => $result,
); // Return this back to the controller.
I typed the codes above without testing but it should work something like this. I do this in all of my projects.
You dont actually have to have the from either, you can include the table name in the count_all_results like so.
$this->db->count_all_results('table_name');
Count first with no_reset_flag.
$this->db->count_all_results('', FALSE);
$rows = $this->db->get()->result_array();
system/database/DB_query_builder.php
public function count_all_results($table = '', $reset = TRUE) { ... }
The
$this->db->count_all_results();
actually replaces the:
$this->db->get();
So you can't actually have both.
If you want to do have both get and to calculate the num rows at the same query you can easily do this:
$this->db->from(....);
$this->db->where(....);
$db_results = $this->get();
$results = $db_results->result();
$num_rows = $db_results->num_rows();
Try this
/**
* #param $column_name : Use In Choosing Column name
* #param $where : Use In Condition Statement
* #param $table_name : Name of Database Table
* Description : Count all results
*/
function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
$this->db->select($column_name);
// If Where is not NULL
if(!empty($where) && count($where) > 0 )
{
$this->db->where($where);
}
// Return Count Column
return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}
Then Simple Call the Method
Like this
$this->my_model->count_all_results(['column_name'],['where'],['table name']);
If your queries contain a group by, using count_all_results fails. I wrote a simple method to work around this. The key to preventing writing your queries twice is to put them all inside a private method that can be called twice. Here is some sample code:
class Report extends CI_Model {
...
public function get($page=0){
$this->_complex_query();
$this->db->limit($this->results_per_page, $page*$this->results_per_page);
$sales = $this->db->get()->result(); //no table needed in get()
$this->_complex_query();
$num_results = $this->_count_results();
$num_pages = ceil($num_results/$this->results_per_page);
//return data to your controller
}
private function _complex_query(){
$this->db->where('a', $value);
$this->db->join('(subquery) as s', 's.id = table.s_id');
$this->db->group_by('table.column_a');
$this->db->from('table'); //crucial - we specify all tables here
}
private function _count_results(){
$query = $this->db->get_compiled_select();
$count_query = "SELECT count(*) as num_rows FROM (".$query.") count_wrap";
$r = $this->db->query($count_query)->row();
return $r->num_rows;
}
}

jomsocial groups and events integration

I am trying to integrate jomsocial events with jomsocial groups.
What i am trying to achieve is to automatically create a group when the event is being created.
Would anyone have some hints regarding such functionality?
The approach i have in mind is to utilize a function onEventCreate($event) from jomsocial API
to call the group creation mechanism. Is that the right way to do it?
Yes, this is the approach I'd take.
You can find method save() in groups.php controller. There you've got all of the required code to implement this.
The rough code :
$my =& CFactory::getUser();
$config =& CFactory::getConfig();
$group =& JTable::getInstance( 'Group' , 'CTable' );
$group->name = $name;
$group->description = $description;
$group->categoryid = $categoryId; // Category Id must not be empty and will cause failure on this group if its empty.
$group->website = $website;
$group->ownerid = $my->id;
$group->created = gmdate('Y-m-d H:i:s');
$group->approvals = 0;
$params = new CParameter( '' );
// Here you need some code from private _bindParams()
$group->params = $params->toString();
$group->published = ( $config->get('moderategroupcreation') ) ? 0 : 1;
$group->store();
// Other useful stuff:
// - store the creator / admin into the groups members table
// - add into activity stream

Resources