Joomla get content by ajax - php

How to get joomla content using ajax? (I want to show content of specyfic page in popup), this is my code: (called by ajax)
$option = JRequest::getCmd('option');
$view = JRequest::getCmd('view');
if ($option=="com_content" && $view=="article") {
$ids = explode(':',JRequest::getString('id'));
$article_id = $ids[0];
$article =& JTable::getInstance("content");
$article->load($article_id);
echo '<h2>'.$article->get("title").'</h2>';
echo $article->get("introtext"); // and/or fulltext
}
This works fine only for artilces, but the problem is when for example I want to show category, or component

Please see your if condition it checks if option is equal to com_content & view is equal to article only. If view contains category it won't work. So add the conditions in if statement so that your code gets executed.
for category you need to add view=category & like for other components as well.

Related

Joomla custom fields inside template

I would like to customize my template for Joomla 3.7 so that I can use the new feature of Joomla 3.7, Custom fields (com_fields), and display and format them via CSS in my template where I need to display them.
Can someone suggest me the PHP code I should use in the template to display field(s), some example please.
Thanks in advance.
For everyone getting late to the party. In case you want to use your custom form fields in a Module-Override (which really are the only way to modify j!-templates, so google 'joomla template override') you can use this handy snippet:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field->rawvalue;
}
?>
Now you cna use your customfields like so: itemCustomFields['customFieldName1']
Haven't tested in article overrides. May soon, if so, this will get updated.
certainly not the right way to do it but I had the same need and I found a work around based on https://www.giudansky.com/news/12-coding/146-joomla-custom-fields
Copie default.php from /components/com_content/views/article/tmpl/default.php to
templates/YOUR_THEME/html/com_content/article/default.php
Add following code line 25 :
$myCustomFields = array();
foreach($this->item->jcfields as $field) {
$myCustomFields[$field->name] = $field->value;
}
$GLOBALS['myCustomFields'] = $myCustomFields;
Typically you put on a global var the content of fields attached to your article.
On your template page you can know retrieved value of your field.
just print_r($GLOBALS['myCustomFields']); to view the content of your array.
That will do the trick waiting for a better answer..
This is absolutely the wrong way to do this I think but I was tearing my hair out so i came up with this quick db query to return custom field values in the template. surely this violates some kind of joomla protocol?
obviously this assumes you can get $articleid into your template already which is the Current ID of your article.
I too am waiting on a better solution but hope this helps
$db =& JFactory::getDBO();
$sql = "select * from #__fields_values where `item_id` = $articleid";
$db->setQuery($sql);
$fieldslist = $db->loadObjectList();
echo $fieldslist[0]->value;
echo $fieldslist[1]->value;
echo $fieldslist[your field ID here]->value;
I found it was easiest to follow how com_fields does it in its rendering code. In Joomla!3.7+, you'll find it in [joomla_root]/components/com_fields/layouts/fields/render.php .
Here are the main parts you need to reproduce the formatting that Joomla has:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
<dl class="fields-container">
<?php foreach ($this->item->jcfields as $field) : ?>
<?php // If the value is empty do nothing ?>
<?php if (!isset($field->value) || $field->value == '') : ?>
<?php continue; ?>
<?php endif; ?>
<?php $class = $field->params->get('render_class'); ?>
<dd class="field-entry <?php echo $class; ?>">
<?php echo FieldsHelper::render($context, 'field.render', array('field' => $field)); ?>
</dd>
<?php endforeach; ?>
</dl>
This loops through all available tags for the component or article. The nice thing about this method is it still applies the render classes you include with the fields.
Make sure to set Automatic Display to Do not automatically display on your fields; otherwise you will see them twice on your page view.
If you want to just target specific fields to show, you can use the name of the field to target it. (The label and value pair is underneath.) See the field Joomla docs for more info.
I implemented this small function to get specific custom field values:
function getCustomFieldValue($field_name, $article_id, $default_value = '') {
// Load custom field list
$fields = FieldsHelper::getFields('com_content.article', $article_id, true);
$field_ids = array_column($fields, 'id', 'name');
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
// Return the value if the field exists, otherwise the default
return array_key_exists($field_name, $field_ids)
? $model->getFieldValue($field_ids[$field_name] , $article_id)
: $default_value;
}
Usage:
$some_field_value = getCustomFieldValue('some-field-name', $some_article_id);
Optimization: I placed the function into a helper class, implemented the variables $fields, $field_ids and $model static and checked if they are already loaded to prevent redundant loading of the same data.

Drupal: How to display part of an author's profile in a node

I have been trying to do display a custom field I created in the manage fields section of user accounts for nodes in addition to the profile page. The problem I am having with this code is that it will display the first field it finds and display that for every user, not the field for that particular user.
And ideas? I believe it's finding the first value in the array and not the value for the particular user in the array.
Here is m setup so far:
Added this to my template.php of my theme:
function mythemename_preprocess_node(&$vars) {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$team = field_get_items('user', $user, 'field_team');
if ($team) {
$vars['field_team'] = $team[0]['value'];
}
}
Then, added this to my node.tpl.php in order to display it on nodes.
if (isset($field_team) && !empty($field_team)) :
echo '$field_team.'</div>';
endif;
UPDATE:
Found my own aswer here:
http://drupal.org/node/1194506
Code used:
<?php
$node_author = user_load($node->uid);
print ($node_author->roles[3]);
print ($node_author->field_biography['und'][0]['value']);
?>
You can use drupal's 'Author Pane' module for that. Try this:
http://drupal.org/project/author_pane

Get custom advanced parameter from article in my module in Joomla

I have a small news module on the home page in my website. It shows the news articles added from the Joomla admin.
It shows the article title in the module section.
But I do not want to show article title in the news module on the home page. I need to show some other text in the news module instead of the news title.
For this I have added a new custom parameter called "News title" in the article manager.
This new custom parameter is getting saved and updated properly with the other article content.
But I am having problems while retrieving the value of this custom parameter in the news module.
Below is the code which is used to get the title of the article in the module.
// getting content
$this->content = $newsClass->getNewsStandardMode($categories, $sql_where, $this->config, $this->config['news_amount']);
//
$this->SIDTab = $this->content['SID'];
$this->titleTab = $this->content['title'];
$this->textTab = $this->content['text'];
$this->idTab = $this->content['ID'];
$this->cidTab = $this->content['CID'];
Below is my code used to show article title.
function render(&$params)
{
$content = array();
//
for($i = 0; $i < count($this->idTab); $i++)
{
$content[$i] = '';
//
if($this->config['links'] == 1)
{
$url = $this->idTab[$i].'&Itemid='.$this->config['item_id'];
if ($this->config['url'] != ""){
$content[$i] .= '<a href="'.$this->config['url'] .'">';
} else {
$content[$i] .= '<a href="'.JRoute::_(ContentHelperRoute::getArticleRoute($url, $this->cidTab[$i], $this->SIDTab[$i])).'">';
}
}
// some more code }
Please help.
Thanks.
When the module is getting the parameters, it is pull the module parameters, not the parameters from the article. The parameters for the article are stored in the attributes fields in the jos_content table. You'll need to get your text from there.
There is an easier way to do this without hacking the core. I noticed that you do not have any intro text in your article. It would be much easier to put the text you want to use at the beginning of the article content and insert a read more break after it. Now the text you want will be processed as intro text by Joomla. You can set it to display in the module and to be hidden in the article view. This prevents you from having to hack the core so you can update easily and should make it easier to display the content you want.

Why can't I see the database updates unless I refresh the page?

Hmmmmm I worked on some PHP code that pulls stock levels from my supplier and inserts the stock level into the database based on the product's SKU. I've inserted it into the class.product.php file which contains all the code used for the individual product page. The issue I'm having is that when the product page loads, it doesn't show the updated inventory levels unless you hit refresh. I've moved the code all over the place and can't get it to update the database and have the updated number loaded before the page is displayed.
Even when placed before all other code, I still have to refresh the page to see the update. I don't know what else to do about this. I feel like perhaps, I don't truly understand how PHP loads code. I've been working on this every day for weeks. I tried running it as an include file, on a separate page, at the top, in the middle, all over the place.
In the class file, it looks like I have the code before it calls the code to display the stock levels, that's why I'm so confused as to why it won't load the updates.
Any thoughts on why I'm unable to see the changes unless I refresh the page?
Thanks!
PHP loads the content when you request it ,
so opening a page gets the content ONCE,
The thing you want to do to get data updated is have AJAX calls to a php function that return data in JSON or XML format
Here you can see some examples but consider googling around for more detailed examples.
The problem was my code was not running until after the code to get and display the product data because I was using info from the product data that was only being called once. So the product data had be be called first in order for my code to run. So to fix this, I had to create a new function that would get the sku and pass it to my code before the code that called the product data to be displayed on the page. I copied the existing function to get the product data, renamed it to GetRealTimeStockLevels and added my code to the bottom of it. I put the call for the function above the call for the product data and it worked like I wanted. I'm glad I got this worked out, now I can add the same feature to the checkout page.
Below is the function call at the start of the page and then the function I created to run my update code.
public function __construct($productid=0)
{
// Get the stock level from supplier and update the database
$this->_GetRealtimeStockLevels($productid);
// Load the data for this product
$this->_SetProductData($productid);
public function _GetRealtimeStockLevels($productid=0)
{
if ($productid == 0) {
// Retrieve the query string variables. Can't use the $_GET array
// because of SEO friendly links in the URL
SetPGQVariablesManually();
if (isset($_REQUEST['product'])) {
$product = $_REQUEST['product'];
}
else if(isset($GLOBALS['PathInfo'][1])) {
$product = preg_replace('#\.html$#i', '', $GLOBALS['PathInfo'][1]);
}
else {
$product = '';
}
$product = $GLOBALS['ISC_CLASS_DB']->Quote(MakeURLNormal($product));
$productSQL = sprintf("p.prodname='%s'", $product);
}
else {
$productSQL = sprintf("p.productid='%s'", (int)$productid);
}
$query = "
SELECT p.*, FLOOR(prodratingtotal/prodnumratings) AS prodavgrating, pi.*, ".GetProdCustomerGroupPriceSQL().",
(SELECT COUNT(fieldid) FROM [|PREFIX|]product_customfields WHERE fieldprodid=p.productid) AS numcustomfields,
(SELECT COUNT(reviewid) FROM [|PREFIX|]reviews WHERE revstatus='1' AND revproductid=p.productid AND revstatus='1') AS numreviews,
(SELECT brandname FROM [|PREFIX|]brands WHERE brandid=p.prodbrandid) AS prodbrandname,
(SELECT COUNT(imageid) FROM [|PREFIX|]product_images WHERE imageprodid=p.productid) AS numimages,
(SELECT COUNT(discountid) FROM [|PREFIX|]product_discounts WHERE discountprodid=p.productid) AS numbulkdiscounts
FROM [|PREFIX|]products p
LEFT JOIN [|PREFIX|]product_images pi ON (pi.imageisthumb=1 AND p.productid=pi.imageprodid)
WHERE ".$productSQL;
if(!isset($_COOKIE['STORESUITE_CP_TOKEN'])) {
// ISC-1073: don't check visibility if we are on control panel
$query .= " AND p.prodvisible='1'";
}
$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
$row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
if (!$row) {
return;
}
$this->_product = $row;
$this->_prodid = $row['productid'];
$this->_prodname = $row['prodname'];
$this->_prodsku = $row['prodcode'];
$GLOBALS['CurrentProductLink'] = ProdLink($this->_prodname);
$server_url = "http://ms.com/fgy/webservices/index.php";
$request = xmlrpc_encode_request("catalog.getStockQuantity", array($this->_prodsku));
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml",
'content' => $request
)));
$file = file_get_contents($server_url, false, $context);
$response = xmlrpc_decode($file);
$query = sprintf("UPDATE [|PREFIX|]products SET prodcurrentinv='$response' where prodcode='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($this->_prodsku));
$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
}

Joomla : how to get the url of a specific Menu itemID?

Friends a newbie question.........I need help in getting the URL of a specific Menu itemID. The situation is like this:
I am running Joomla and asking for a user to input for a menu ID and choose a layout for that menu ID.
I want to do something else with this URL of the Menu itemID.
How can I get the URL of this Menu itemID provided by the user?
For Example if the user input is liek $this->get ('menulayoutid'>; and he inputs and ID of 54 then how do I get the URL for Menu ID 54.
Please note: I want to get this URL from within my PHP file and not in the browser so that I can use the value of that URL for some other purpose.
Kindly help.
$itemid = JRequest::getVar('Itemid');
$application = JFactory::getApplication();
$menu = $application->getMenu();
$item = $menu->getItem($itemid);
$link = new JURI($item->link);
$link->setVar('ItemId', $itemid);
Source: http://forum.joomla.org/viewtopic.php?p=1836005
However, we get the Itemid from anywhere (user input, from our own developed module using the "menu item" field type in the xml file as described in the Joomla Docs - Standard form field types)
// get the menuItemId from wherever...
// as described above or as in other posts here and do whatever with that!
$menuItemId = 'fromWherever'; // as an example "107";
// build the link to the menuItemId is just easy and simple
$url = JRoute::_('index.php?Itemid=' . $menuItemId);
i think if we need only a link to a specific menu id, this is the best solution, because we have absolutely less requests and a clean code
this works also in Joomla 3.0, 3.1
I just want to add that if you need to target a specific menu you pass the menu name as an argument to getMenu().
$itemid = JRequest::getVar('Itemid');
$application = JFactory::getApplication();
$menu = $application->getMenu( 'menu-name' );
$item = $menu->getItem($itemid);
$link = new JURI($item->link);
$link->setVar('ItemId', $itemid);
I'm not sure if Joomla changed the way this works since 2.5 or even 1.7 but I spent the worse half of 2 hours looking for this.
Hopefully it helps someone.
$menuID = $params->get('menuItem'); // from module field menu ex. '105'
$js = new JSite;
$menu = $js->getMenu();
$link = $menu->getItem($menuID)->route;
//Returns URL Friendly Link -> menu/article
//Then format it ->
$link = 'http://www.yoursite.com/index.php/'.$link;
echo 'Borrowed Menu Link Path";
When you need to get your active menu item ID in Joomla to display some specific content for only that menu item or just to show the ID of the menu item, insert the following code where you wish to display the active menu item ID:
<?php
$currentMenuId = JSite::getMenu()->getActive()->id;
echo $currentMenuId;
?>

Categories