How to append a parameter to current page using CHtml::link? - yii

Using Yii, and trying to append a Lang=xx to the end of the current page url and present it on the page.
I put the below code in the protected/views/layout/main.php
<?php echo CHtml::link('English', array('','lang'=>'en'), array('class'=>'en')) ?>
<?php echo CHtml::link('中文', array('','lang'=>'tw'), array('class'=>'tw')) ?>
<?php echo CHtml::link('日本語', array('','lang'=>'jp'), array('class'=>'jp')) ?>
With standard pages like "/site/index", or controller action pages like "/site/contact", they work fine. But with the standard static pages like "site/page?view=about", it's not working. The url expected should be something like "site/page?view=about&lang=tw", but instead, it gives me "site/page?lang=tw".
How can I fix that?

I ended up doing it with langhandeler extension and url rules and map [site]/[path]?lang=[language code] to [site]/[language code]/[path]
And then I coded the links like below:
<?php
$request = $_SERVER['REQUEST_URI'];
$path_a = explode("/",$request);
$haveLang = isSet($_GET["lang"]);
$uri = ($haveLang?
substr($request, strlen($path_a[1])+1) //strip language prefix and the slash
:$request); //don't process if the page is in default language
echo CHtml::link(CHtml::encode(Yii::app()->name), CHtml::normalizeUrl(($haveLang?'/'.$_GET["lang"].'/':'/')), array('id'=>'logo'));
?>
<div id="lang_switch">
<?php
echo CHtml::link('English', CHtml::normalizeUrl($uri), array('class'=>'en')); //no need to add default language prefix
echo CHtml::link('中文', CHtml::normalizeUrl('/tw'.$uri), array('class'=>'tw'));
echo CHtml::link('日本語', CHtml::normalizeUrl('/jp'.$uri), array('class'=>'jp'));
?>
</div>
that pretty much solved my problem. I hope this could help out someone else in the future.

you can give chtml link like this
$language = 'en';
CHtml::link("English", array('site/about/lang/' . $language));
site/about/lang/en = controller/action/lang/en
i hope this will help you.

Related

Joomla 3.0 not echoing usertype

I made the following code to get some user variables in a flash app:
<?php
$user =& JFactory::getUser();
echo $user->get('username') ;
echo $user->get('id') ;
echo $user->get('name') ;
echo $user->get('usertype') ;
?>
Everything but usertype works, for some reason. Usertype is vital to be able to monetize my app. I followed this as a reference, so it seems alright:
http://docs.joomla.org/Accessing_the_current_user_object
Whats wrong here?
Right, I've had a look around and I can't actually find a decent solution that simply provides you with the name of the group that the user belongs to. Everything else gives you an array or the ID, so I have written a simple function that will get you exactly what you want:
function getUserGroup($userId){
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('title')
->from('#__user_usergroup_map AS map')
->where('map.user_id = '.(int) $userId)
->leftJoin('#__usergroups AS a ON a.id = map.group_id');
$db->setQuery($query);
$result = $db->loadResult();
return $result;
}
echo getUserGroup($user->id);
Hope this helps

virtuemart 2 product pdf does not display custom fields

I'm using VirtueMart 2.0.10 with Joomla! 2.5.6 and my problem is the autogenerated pdf documents for each product don't include my custom fields. I'm no php expert but I think theese lines in file /components/com_virtuemart/views/productdetails/tmpl/default_pdf.php has something to do with it, starting at line 145:
<?php // Product custom_fields TODO relation to Childs
if (!empty($this->product->customfields)) { ?>
<div class="product-fields">
<?php
$custom_title = null ;
foreach ($this->product->customfields as $field){
?><div style="display:inline-block;" class="product-field product-field-type-<?php echo $field->field_type ?>">
<?php if ($field->custom_title != $custom_title) { ?>
<span class="product-fields-title" ><strong><?php echo JText::_($field->custom_title); ?></strong></span>
<?php //echo JHTML::tooltip($field->custom_tip, $field->custom_title, 'tooltip.png');
} ?>
<span class="product-field-display"><?php echo $field->display ?></span>
<span class="product-field-desc"><?php echo jText::_($field->custom_field_desc) ?></span>
</div>
<?php
$custom_title = $field->custom_title;
} ?>
</div>
<?php
} // Product custom_fields END ?>
I tested adding an else statement echoing some text after the above if statement and it executetd. So apperently there are no custom fields... but there really are...
I haven't found anyone else experiencing this problem wich I think is weird, but I don't think I have screwed something up. I HAVE made a few changes in the /components/com_virtuemart/views/productdetails/tmpl/default.php file.
I removed all the code that I entered in my question and replaced it with the following code from the file /components/com_virtuemart/views/productdetails/tmpl/default.php:
<?php
$custom_title = null;
foreach ($this->product->customfieldsSorted['normal'] as $field) { // I set the position to normal
if ( $field->is_hidden )
continue;
if ($field->display) {
?>
<?php if ($field->custom_title != $custom_title) { ?>
<b><?php echo JText::_($field->custom_title); ?></b><br />
<?php
if ($field->custom_tip)
echo JHTML::tooltip($field->custom_tip, JText::_($field->custom_title), 'tooltip.png');
}
?>
<?php echo $field->display ?><br />
<?php echo jText::_($field->custom_field_desc) ?><br />
<?php
$custom_title = $field->custom_title;
}
}
?>
I'm no expert but this worked for me. The PDF now includes the custom fields.
As you see in the comment in the code I changed the position to 'normal'. The other positions seems to be 'ontop' and 'onbot'. But I won't change that setting so I leave it be.
EDIT: I forgot to mention I added some other html-code to that segment, like <br /> and <b> just for apperences. So nothing major, just to clarify that the code isn't EXACTLY like it is in the file default.php

Youtube api get latest upload thumbnail

I am looking to returning the video-thumbnail of the latest uploaded video from my channel, and display it on my website.
Anyone know how I can do a minimal connection trough api and get only the thumbnail?
Thanks!
-Tom
REVISED!!
Using Cakephp, this is how I did it (thanks dave for suggestions using zend);
controller:
App::import('Xml');
$channel = 'Blanktv';
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads?v=2&max-results=1&orderby=published';
$parsed_xml =& new XML($url);
$parsed_xml = Set::reverse($parsed_xml);
//debug($parsed_xml);
$this->set('parsed_xml',$parsed_xml);
View;
$i=0;
foreach ($parsed_xml as $entry)
{
echo '<a href="/videokanalen" target="_self">
<img width="220px" src="'.$entry['Entry']['Group']['Thumbnail'][1]['url'] .'">
</a>';
}
Now the only thing remaining is to cache the feed call someway.. Any suggestions???
-Tom
here is a quick dirty way of doing it without really touching the api at all.
I'm not suggesting it's best practice or anything and I'm sure there are smarter ways but it definitely works with the current Youtube feed service.
My solution is PHP using the Zend_Feed_Reader component from Zend Framework, if you need a hand setting this up if you're not familiar with it let me know.
Essentially you can download version 1.11 from Zend.com here and then make sure the framework files are accessible on your PHP include path.
If you are already using Zend Framework in an MVC pattern you can do this in your chosen controller action:
$channel = 'Blanktv'; //change this to your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
$this->view->feed = $feed;
Then you can do this in your view:
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($this->feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
otherwise you can do:
<?php
$channel = 'Blanktv'; //change this to your channel
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
?>
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
With the latter method you'll likely need to use a php require statement for the Zend_Feed_Reader files etc....
Hope this helps, like I say let me know if you need a hand.
All the best,
Dave
UPDATE: In response to your comments about caching
Hi Tom, here is another quick and dirty solution which doesn't use cache but may be very quick to implement.
The reason I didn't go with a caching component is because I figured a simple db solution would suffice under the circumstances. I also thought having to pull the feed to compare whether it was new or not wouldn't be the most economical for you.
You could automate this process to be run automatically at specified times but if you don't want to automate the process and don't mind clicking a link to update the video manually you could trigger it that way.
My solution is again based on ZF but since you were ok hacking it into something useful with cakephp you should have no problem doing the same here.
First set up a new table (assuming a MySQL db):
CREATE TABLE `yourdbname`.`latestvid` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
`videoId` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video id',
`videoTitle` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video title',
`uploadDate` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video upload date'
) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `yourdbname`.`latestvid` (`id`, `videoId`, `videoTitle`, `uploadDate`) VALUES (NULL, '--', '--', '--');
This will create a table for your latest video info for use in your template however the default values I've set up will not work with your template for obvious reasons.
You could then do something similar to this:
public function updateAction()
{
$this->_helper->viewRenderer->setNoRender(); // disable view
$this->_helper->layout()->disableLayout(); // disable layout
$user = 'Blanktv'; // insert your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$user.'/uploads';
$feed = Zend_Feed_Reader::import($url);
if(!$feed)
{
die("couldn't access the feed"); // Note: the Zend component will display an error if the feed is not available so this wouldn't really be necessary for ZF
}
else
{
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
$videoTitle = $entry->getTitle();
$uploadDate = $entry->getDateCreated();
// use your preferred method to update the db record where the id = 1
$i++;
if($i==1) break;
}
}
}
Maybe have a go and let me know how you get on?
You'd just need to tweak the template so you'd get the variables from the database instead of Youtube with the exception of the thumbnail.
I suppose you could always take that approach further and actually store images etc since the thumbnail is still being pulled from Youtube and may slow things down.
You could set up a script to copy the thumbnail to your own server and store the path in the db or use a standard thumbnail if you are running a series of videos for which you require standard branding - anyway hope it helps.
:-D
Dave

Best way to display current logged-on user in default.ctp?

I am in the process of customizing the default.ctp file and I am trying to display the currently logged on user's name on the top of the page.
In app_controller.php, I have the following:
function beforeFilter()
{
$user = $this->Auth->user();
if($user != null)
{
$this->Session->write('user_name',$user['User']['username']);
}
}
And in default.ctp, I have:
$user = $this->Session->read('Auth.User');
if(!empty($user))
{
echo 'Hello, ' . $user['user_name'];
}
However, it seems like the value $user_name is not getting set anywhere.
What am I doing wrong? Is there a better way to accomplish this?
Update: I've modified it as described in the answer, but it still doesn't work. I get an error:
Undefined index: user_name [APP/views/layouts/default.ctp, line 21]
you can also use the SessionHelper directly in the view / layout
$user = $this->Session->read('Auth.User');
if(!empty($user)) {
echo 'Hi ', $user['user_name'];
}
Cakephp 2.x:
<?php if (AuthComponent::user('id')): ?>
<p class="navbar-text pull-right">
Logged in as <?= AuthComponent::user('name') ?>
</p>
<?php endif; ?>
$user = $this->Session->read('Auth.User');
if(count($user))
echo $user['name'];

symfony get data from array

I'm trying to use an SQL query to get data from my database into the template of a symfony project.
my query:
SQL:
SELECT l.loc_id AS l__loc_id, l.naam AS l__naam, l.straat AS l__straat,
l.huisnummer AS l__huisnummer, l.plaats AS l__plaats, l.postcode AS l__postcode,
l.telefoon AS l__telefoon, l.opmerking AS l__opmerking, o.org_id AS o__org_id, o.naam AS o__naam
FROM locatie l
LEFT JOIN organisatie o
ON l.org_id = o.org_id
This is generated by this DQL:
DQL:
$this->q = Doctrine_Query::create()
->select('l.naam, o.naam, l.straat, l.huisnummer, l.plaats, l.postcode, l.telefoon, l.opmerking')
->from('Locatie l')
->leftJoin('l.Organisatie o')
->execute();
But now when i try to acces this data in the template by either doing:
<?php foreach ($q as $locatie): ?>
<?php echo $locatie['o.naam'] ?>
or
<?php foreach ($q as $locatie): ?>
<?php echo $locatie['o__naam'] ?>
i get the error from symfony:
500 | Internal Server Error | Doctrine_Record_UnknownPropertyException
Unknown record property / related component "o__naam" on "Locatie"
Does anyone know what is going wrong here? i dont know how to call the value from the array if the names in both query's dont work.
Doctrine will have hydrated your results into objects corresponding to the models in your query. In your case these will be Locatie and Organisatie. You should therefore be able to access the data as follows:
<?php foreach ($q as $obj): ?>
<?php echo $obj->Locatie->naam; ?>
<?php echo $obj->Organisatie->naam; ?>
<?php endforeach; ?>
If you have the above method in eg the Locatie table class and use self::create("l") to create your method, the object you use in the view won't need the ->Locatie part.
Edit: table method example:
class LocatieTable extends Doctrine_Table
{
public function getLocaties()
{
$q = self::createQuery("l")
->select('l.naam, o.naam, l.straat, l.huisnummer, l.plaats, l.postcode, l.telefoon, l.opmerking')
->leftJoin('l.Organisatie o')
->execute();
return $q;
}
}
You should be able to find this class (probably empty) already auto-generated in lib/model/doctrine/LocatieTable.class.php. Now call it with:
$this->q = Doctrine::getTable("Locatie")->getLocaties();
If you want to know how to get some value from the result DoctrineRecord object I advise to use var_dump($obj->toArray()) method to get clear view of the object structure. After that you can use several types of getters to retrive what you want (e.g. $obj->A->b, $obj->getA()->getB() etc..)