Getting Menu Parameters from Joomla - php

I'm trying to get parameters from the menu table in Joomla. What I have below is working in the sense that it is returning the parameters.
$menu = &JSite::getMenu();
$item = $menu->getItem($menuId)->params;
print $items;
However, It's returning them in plain text, as if I had just queried the column and returned the params contents.
Can someone tell me how to return this as an Object or Array so that I can use something like:
$myParam = $item->getParams('theParamIwant');

I think JParameter is obsolete in Joomla! 3.x, so the answer now is something like:
$app = JFactory::getApplication();
$menuitem = $app->getMenu()->getActive(); // get the active item
$menuitem = $app->getMenu()->getItem($theid); // or get item by ID
$params = $menuitem->params; // get the params
print_r($params); // print all params as overview
You can get the menu_image variable by doing:
echo $params->get('menu_image');
Or first check if it's filled in and, if it is, echo it:
// using get() with a second parameter makes it fall back to this if nothing is found
$menu_image = $params->get('menu_image', false);
if ($menu_image && strlen($menu_image)) {
echo "<img src='$menu_image'/>";
}
Or, using a tertiary operator:
$menuimg = $params->get('menu_image')
echo strlen($menuimg) ? "<img src='$menuimg'/>" : '';

You need to use the JParameter class to read the params. Try something like this:
$item = $menu->getItem($menuId);
$params = new JParameter($item->params);
$myParam = $params->get('theParamIwant');

It doesn't work
Try to use this:
$params = $menus->getParams($menuId);
$myParam = $params->get('theParamIwant');

$app = JFactory::getApplication();
$params = $app->getParams();
$yourParameter = $params->get('YOURPARAMETERNAME');

($currentMenuId = JSite::getMenu()->getActive()->id ; // `enter code here`
$document =& JFactory::getDocument(); // `enter code here`
$app = JFactory::getApplication(); // `enter code here`
$menuitem = $app->getMenu()->getItem($currentMenuId); // or get item by ID `enter code here`
$params = $menuitem->params; // get the params `enter code here`
$params->get('menu-meta_keywords');
if($document->description == '') // 116 is the ID number of the menu pointing to the component `enter code here`
{
$this->setMetaData( 'description', $params->get('menu-meta_description') );
$this->setMetaData( 'keywords', $params->get('menu-meta_keywords') );
}
else
{
// do nothing
})

Working in 3.5.1
$app = JFactory::getApplication();
$currentMenuId = JSite::getMenu()->getActive()->id;
$menuitem = $app->getMenu()->getItem($currentMenuId);
$params = $menuitem->params;
echo $params['menu_image'];
Shows menu item image

JParameter is deprecated in Joomla 2.5, so to get Kevin's code to work add
jimport( 'joomla.html.parameter' ) before i.e
jimport( 'joomla.html.parameter' );
$item = $menu->getItem($menuId);
$params = new JParameter($item->params);
$myParam = $params->get('theParamIwant');

Related

Drupal block_load page

How I cant load a 'page' view within my template. My page view is "foo_bar" and the view file is "views-view-unformatted--foo-bar--page.tpl.php" then I use the next code but it did't load the view.
$block = block_load('views', 'foo_bar');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
echo $output;
There are 2 functions to load a view;
$view = views_get_view('view_name');
// ensure view exists
if (!$view)
return;
$view->set_display('view_display');
$view->set_arguments(array($tid));
//$view->is_cacheable = FALSE; //default
$view->pre_execute();
$view->execute();
$result = $view->render();
or a simpler:
$result = views_embed_view($name, $display_id = 'default');

Joomla create menu item from component

Here is my current component setup. I have a very dynamic page generation component that syncs with data from a external API to create pages for products without extra data entry.
Right now it works at a simple button click to populate all and update any changes, or just update individual fields. What this leads to is the generation of static "pages" from the api in joomla, and the ability to update it from the api.
The problem comes into the fact that this is used as the "home" menu item so the component itself takes the root directory. What I need is each "page" to take a sub menu of home automatically, though just setting the main menu item as home does not seem to work, it leads to the JRoute class getting confused and using component/ , everything I have read so far takes the assumption it is not the default menu item so I am losing home making it fully automatic.
So my question is, is there a function class to create menu items from components in joomla? adding another row to the joomla menu table for each page while i update them "should" solve the problem, I know I can try to figure out how joomla adds them to the database on my own, but I would prefer to use a joomla class/function if at all possible, any ideas?
here is my current router.php, works fine for directly linking to the page but not when using JRoute. There is some uneeded parts to this as I have been doing some extensive testing though.
<?php
defined('_JEXEC') or die;
function GoFormsBuildRoute($query){
$segments = array();
$app = JFactory::getApplication();
$menu = $app->getMenu();
$params = JComponentHelper::getParams('com_goforms');
$db = JFactory::getDBO();
if (empty($query['Itemid'])) {
$menuItem = $menu->getActive();
$menuItemGiven = false;
}
else {
$menuItem = $menu->getItem($query['Itemid']);
$menuItemGiven = true;
}
//print_r($menuItem);
if(isset($query['option'])){
unset($query['option']);
}
if(isset($query['view'])){
$view = $query['view'];
}else{
return $segments;
}
unset($query['view']);
if(isset($query['id'])){
if ($menuItemGiven && isset($menuItem->query['id'])) {
$mCatid = $menuItem->query['id'];
} else {
$mCatid = 0;
}
//echo 'hi';
if(strpos($query['id'], ':') === false) {
$db = JFactory::getDbo();
$aquery = $db->setQuery($db->getQuery(true)
->select('alias')
->from('#__goforms_list')
->where('id='.(int)$query['id'])
);
$alias = $db->loadResult();
$query['id'] = $alias;
}
$segments[] = $query['id'];
unset($query['id']);
}
print_r($segments);
return $segments;
}
function GoFormsParseRoute($segments){
$vars = array();
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item = $menu->getActive();
$params = JComponentHelper::getParams('com_goforms');
$db = JFactory::getDBO();
print_r($item);
$count = count($segments);
if($count == 1){
if(isset($segments[0])){
$vars['view'] = 'region';
$alias = str_replace(':','-',$segments[0]);
//print_r($alias);
//echo '<br>';
$query = 'SELECT alias, id FROM #__goforms_list WHERE alias = "'.$alias.'"';
$db->setQuery($query);
$page = $db->loadObject();
if($page){
$vars['view'] = 'region';
$vars['id'] = (int)$page->id;
return $vars;
}else{
$vars['view'] = 'goforms';
}
}else{
$vars['view'] = 'goforms';
}
}
return $vars;
}
?>
in review:
Joomla 2.5
component is at root menu item of site (home)
items from component need to fall under the first level of menu after home
links work, however JRoute class in joomla does not properly make the link.

Integrate Sitelink using php

I want to integrate Sitelink with my website using php. For demo they have just provided this code
echo '<p>Testing SiteLink...</p>';
define( 'SITELINK_URL', "https://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define( 'SITELINK_CORP_CODE', "CCTST" );
define( 'SITELINK_LOC_CODE', "Demo" );
define( 'SITELINK_CORP_LOGIN', "Administrator" );
define( 'SITELINK_CORP_PASS', "Demo" );
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
try
{
$units = $client->SiteInformation( $params );
$result = $units->SiteInformationResult;
}
catch (Exception $e )
{
die( 'Error: '.$e->getMessage().'<br>'.$e );
}
echo htmlentities( $result->any );
But I am not able to understand how to fecth the data and process it using php. I have to Fetch unit sizes and their respective prices. Any help is greatly appreciated. Thanks in advance.
You are not trying to get Units you are getting SiteInformation
add type for $params first:
$params = new stdClass; // as stdClass
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
then:
$units = $client->UnitTypePriceList($params);
$result = $units->UnitTypePriceListResult->any;
and you have to parse the data with DOMDocument, check the tag name you want to display and print it out:
$dom = new DOMDocument;
$dom->loadXML($result);
$xpath = new DOMXPath($dom);
$el = $xpath->query('//Table');
foreach($el as $units){
$UnitID = $xpath->query('UnitID_FirstAvailable', $units)->item(0)->nodeValue;
echo $UnitID;
}
I don't know what are your desired values, but I took UnitID_FirstAvailable as example.
SiteInformation is expecting array not Object and your $params was never declared
define('SITELINK_URL', "http://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define('SITELINK_CORP_CODE', "CCTST");
define('SITELINK_LOC_CODE', "Demo");
define('SITELINK_CORP_LOGIN', "Administrator");
define('SITELINK_CORP_PASS', "Demo");
$client = new SoapClient(SITELINK_URL);
$params = array("sCorpCode" => SITELINK_CORP_CODE,"sLocationCode" => SITELINK_LOC_CODE,"sCorpUserName" => SITELINK_CORP_LOGIN,"sCorpPassword" => SITELINK_CORP_PASS);
try {
$units = $client->SiteInformation($params);
header("Content-Type: text/xml");
print($units->SiteInformationResult->any);
} catch ( Exception $e ) {
die('Error: ' . $e->getMessage() . '<br>' . $e);
}
See Live DEMO
I know this is kind of old, but I've been doing some extensive work with the API. First off, you'll want this: SiteLink API Documentation
To get all available units, you could do something like this:
// define API connection credentials
define('SITELINK_URL', "http://www.smdservers.net/CCWs_3.5/CallCenterWs.asmx?WSDL");
define('SITELINK_CORP_CODE', "CCTST");
define('SITELINK_LOC_CODE', "Demo");
define('SITELINK_CORP_LOGIN', "Administrator");
define('SITELINK_CORP_PASS', "Demo");
$client = new SoapClient( SITELINK_URL );
$params->sCorpCode = SITELINK_CORP_CODE;
$params->sLocationCode = SITELINK_LOC_CODE;
$params->sCorpUserName = SITELINK_CORP_LOGIN;
$params->sCorpPassword = SITELINK_CORP_PASS;
$params->lngLastTimePolled = 0;
$params->bTestMode = true;
try
{
$units = $client->UnitsInformationAvailableUnitsOnly_v2($params);
$result = $units->UnitsInformationAvailableUnitsOnly_v2Result;
}
catch (Exception $e)
{
die( 'Error: '.$e->getMessage().'<br />'.$e );
}
echo '<table>';
$formatUnits = new SimpleXMLElement($result->any);
foreach($formatUnits->NewDataSet->Table as $unit){
echo "<tr>\r\n";
echo "<td><a href='#' data-unit-number='".$unit->sUnitName."' data-unit-id='".$unit->UnitID."' data-rate='".$rate."' class='res-unit-link'>".$unit->sUnitName."</a></td>\r\n";
echo "<td>".$unit->sTypeName."</td>\r\n";
echo "</tr>\r\n";
}
echo '</table>';
You could do var_dump($formatUnits) to see all available data in the object that gets returned by SiteLink. The above code is an example from something I made where I used jQuery to grab all of the data- attributes from the link to use for the rental/reservation process.
I hope this helps somebody. I really could have used it when I first started using the API.

Add new values to a attribute option in Magento

I am trying to add new values to an attribute option in Magento using a script to speed up the process since I have over 2,000 manufacturers.
Here is a piece of code that I used to perform exactly this task. Create a custom module (using ModuleCreator as a tool) and then create a mysql4-install-0.1.0.php under the sql/modulename_setup folder. It should contain the following (adapted to your own data, of course!).
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$aManufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$iProductEntityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$aOption = array();
$aOption['attribute_id'] = $installer->getAttributeId($iProductEntityTypeId, 'manufacturer');
for($iCount=0;$iCount<sizeof($aManufacturers);$iCount++){
$aOption['value']['option'.$iCount][0] = $aManufacturers[$iCount];
}
$installer->addAttributeOption($aOption);
$installer->endSetup();
More documentation on the Magento wiki if you want.
If you don't want to do it in a custom module, you could just create a php file that starts with:
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
Answer of Jonathan is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key=>$manufacturer) {
$option['value'][$key.'_'.$manufacturer][0] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
More information can be found here.
I have created a function to dynamically add option to attribute
public function addAttributeOptions($attributeCode, $argValue)
{
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
$id = $attribute->getSource()->getOptionId($argValue);
if ($id)
return $id;
}
$value = array('value' => array(
'option' => array(
ucfirst($argValue),
ucfirst($argValue)
)
)
);
$attribute->setData('option', $value);
$attribute->save();
//return newly created option id
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
return $attribute->getSource()->getOptionId($argValue);
}
}
You can add an option to your attribute by providing code and option value
$this->addAttributeOptions('unfiorm_type', 'leotartd')
Important! (Hopefully this helps somebody, cause I was stuck like 2h with this issue)
If you are using special characters (such as ä, ö, ü, ß, ×, ...) make sure to encode them properly!
array_walk($manufacturers , create_function('&$val', '$val = utf8_encode($val);'));
Here a simple and very fast way....
Delete an option
/* My option value */
$value = 'A value';
/* Delete an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID from value...
if ($option_id) {
$options['delete'][$option_id] = true;
$attribute->setOption($options)->save();
}
}
/* END ! */
Add or update an option
/* Add/Update an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID...
$options['order'][$option_id] = 10; // Can be removed... Set option order...
$options['value'][$option_id] = array(
0 => $value, // Admin Store - Required !
1 => $value, // Store id 1 - If U want ! Can be removed
);
$attribute->setDefault(array($option_id)); /* If you want set option as default value */
$attribute->setOption($options)->save(); /* That's all */
}
/* END ! */
In my tutorial I am explaining how to read the options from the CSV and create the options pro grammatically.
http://www.pearlbells.co.uk/add-attribute-options-magento-scripts/
please click the tutorial for further explanation
function createAttribute($options) {
$option = array('attribute_id' =>
Mage::getModel('eav/entity_attribute')->getIdByCode(
Mage_Catalog_Model_Product::ENTITY,
'color'
)
);
for ($i = 0; $i < count($options); $i++) {
$option['value']['option'.$i][0] = $options[ $i ]; // Store View
$option['value']['option'.$i][1] = $options[ $i ]; // Default store view
$option['order']['option'.$i] = $i; // Sort Order
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
}
Answer of Arvind Bhardwaj enter code here is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
Agree with Arvind but it's only works for insert the single option value and if you want to perform insert multiple option value then you just needs to replace the code from "$option['value'][$key.''.$manufacturer] = $manufacturer;" to "$option['values'][$key.''.$manufacturer] = $manufacturer;" to this.
below is the final code
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony', 'Philips', 'Samsung', 'LG', 'Panasonic', 'Fujitsu', 'Daewoo', 'Grundig', 'Hitachi', 'JVC', 'Pioneer', 'Teac', 'Bose', 'Toshiba', 'Denon', 'Onkyo', 'Sharp', 'Yamaha', 'Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key => $manufacturer) {
$option['values'][$key . '_' . $manufacturer] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
I hope its works for insertion multiple option.

WordPress Get the Page ID outside the loop

I want to get the page ID before starting the loop in WordPress. I am using
$page = get_query_var('page_id');
Apparently, it returns nothing.
I just want to check a page for its ID and add a class to <body> tag based on it.
If you're using pretty permalinks, get_query_var('page_id') won't work.
Instead, get the queried object ID from the global $wp_query:
// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id = get_queried_object_id();
// "Dirty" pre 3.1
global $wp_query;
$page_object = $wp_query->get_queried_object();
$page_id = $wp_query->get_queried_object_id();
You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):
<?php
/**
* #uses WP_Query
* #uses get_queried_object()
* #see get_the_ID()
* #return int
*/
function get_the_post_id() {
if (in_the_loop()) {
$post_id = get_the_ID();
} else {
global $wp_query;
$post_id = $wp_query->get_queried_object_id();
}
return $post_id;
} ?>
And simply do:
$page_id = get_the_post_id();
Use this global $post instead:
global $post;
echo $post->ID;
If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:
if (get_option('show_on_front') == 'page') {
$page_id = get_option('page_for_posts');
echo get_the_title($page_id);
}
(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)
If you're on a page and this does not work:
$page_object = get_queried_object();
$page_id = get_queried_object_id();
you can try to build the permalink manually with PHP so you can lookup the post ID:
// get or make permalink
$url = !empty(get_the_permalink()) ? get_the_permalink() : (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$permalink = strtok($url, '?');
// get post_id using url/permalink
$post_id = url_to_postid($url);
// want the post or postmeta? use get_post() or get_post_meta()
$post = get_post($post_id);
$postmeta = get_post_meta($post_id);
It may not catch every possible permalink (especially since I'm stripping out the query string), but you can modify it to fit your use case.
I have done it in the following way and it has worked perfectly for me.
First declared a global variable in the header.php, assigning the ID of the post or page before it changes, since the LOOP assigns it the ID of the last entry shown:
$GLOBALS['pageid] = $wp_query->get_queried_object_id();
And to use anywhere in the template, example in the footer.php:
echo $GLOBALS['pageid];
You can use is_page($page_id) outside the loop to check.
This function get id off a page current.
get_the_ID();
Use below two lines of code to get current page or post ID
global $post;
echo $post->ID;
This is the correct code.
echo $post->ID;
If you are out of the Loop of WordPress you can not use any of the method of wordpress so you must use pure php.
You can use this code. And sure will help you :)
$page_id = #$_GET['page_id'];
if (!is_numeric($page_id)) {
// Then the uri must be in friendly format aka /my_domain/category/onepage/
// Try this
//$path = '/www/public_html/index.php/';
///$path = '/my_domain/category/onepage/';
$path = $_SERVER['REQUEST_URI'];
// Clean the uri
//$path = str_replace('/', '', $page);
$path = str_replace('.php', '', $path);
//$path = str_replace('?s=', '', $path);
$path = $path ? $path : 'default';
$path_len = strlen($path);
$last_char = substr($path, $path_len -1);
//echo $last_char;
$has_slash = strpos($last_char, "/");
//echo $has_slash;
if ($has_slash === 0) :
$path = substr($path, 0, $path_len -1);
elseif ($has_slash === null) :
$path = substr($path, 0, $path_len);
endif;
//echo "path: ".$path; // '/www/public_html/index'
$page = substr(strrchr($path, "/"), 1);
echo "page: ".$page; // 'index'
}
$my_page_id = 31;
$my_page = 'mypage';
//echo "page: ".$page;
//echo "page_id ".$page_id;
if($page_id == $my_page_id || $page == $my_page)
{
// your stuff....
}
Enjoy!

Categories