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

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'];

Related

Cake PHP Update single fields in View - Undefined Variable

i search a long time, but i dont find a solution for my problem.
The case is, that i have a few buttons integrated in my view and clicking on them affected updating single input fields. The problem is that i have warnings, that variables are undefined in view. I understand why and how i suppress them, but i`m not sure, if this is a good solution. Is there a better way to solve this? What is best practice?
Here is my code from the view file:
<?php
echo $this->Form->create('Excel', array('type' => 'file'));
echo $this->Form->file('File');
echo $this->Form->submit('Upload xls File');
echo $this->Form->end();
echo $this->Form->create('Config');
//echo $this->Form->input('Name');
echo $this->Form->input('vlanNumber');
echo $this->Form->input('description', array('value' => $description));
echo $this->Form->input('preSharedKey', array('value' => $preSharedKey));
echo $this->Form->button('generate', array('name'=>'generateButton'));
echo $this->Form->input('customerPeerIp', array('default' => 'id_of_default_val','value' => $cusPeerIp));
The generate button affect a new preSharedKey. And the upload of the csv affected an update of the other fields.
The relevant code of the controller is this:
public function inputData() {
if ($this->request->is('post')) {
$post_data = $this->request->data;
if (isset($this->request->data['show'])) { //Submit Button was clicked
$this->Session->write('Configuration',$post_data); //Store the input fields in the session
return $this->redirect(array('action' => 'showPreview'));
} else if (isset($this->request->data['cancel'])) { // Cancel button was clicked: Go back to index site
return $this->redirect(array('action' => 'index'));
} else if (isset($this->request->data['generateButton'])) {
return $this->set('preSharedKey', $this->getRandomString(20)); //Set a Pre Shared Key with 30 signs
}
if (!empty($this->data) && is_uploaded_file($this->data['Excel']['File']['tmp_name'])) {
$this->importData($this->data['Excel']['File']['tmp_name']);
$excel=new Excel();
$values=$excel->getParams($this->data['Excel']['File']['tmp_name']);
$this->set('description',$values['description']);
$this->set('cusPeerIp',$values['cust_peer']);
return;
//this calls the Excel Class function
}
//print_r($post_data);
//echo $post_data['Config']['Name'];
//echo $this->request['Config']['task_1'];
}
$this->set('description','');
$this->set('cusPeerIp','');
$this->set('preSharedKey', '');
}
Can you please help me?

How to get multiple POST data?

I am trying to get the $_POST data from some inputs fields, but the thing is I am getting the number of fields from my database:
$query2 = $DB->prepare("SELECT * FROM params WHERE modulid = $parameterid");
$query2->execute();
<td>Parameter unit:</td>
<?php while (($row2 = $query2->fetch()) != false)
{
$unit = $row2->name;
?><td><input type="text" name="<?php echo $row2->id; ?>" value="<?php echo $unit; ?>" class="textbox"></td><?php
}
?>
What is the code to get post data from all of them so I can update the database if the user wants to type new data in the input?
You can get all values submitted by a form by iterating through the following global variable:
$_POST
By using a foreach loop, you can then check which values were filled and generate an UPDATE SQL statement with them.
Example to get all non-empty values:
$changed = array();
foreach($_POST as $key => $value) {
if(!empty($value)) {
$changed[$key] = $value;
}
}
Then create the query using the $changed array.
Why don't you do something like that
$temp=$row2->id;
mysql_query("insert into params (modulid) values ('$temp')");

YII Call to a member function getErrors() on a non-objec

Following this tutorial; When I try to get the data to display in the form and update
For my error was:
$n = $this->loadModel($id);
I want to make two models with one form, this is my code for update:
Controller:
public function actionUpdate($id)
{
$n = new Noticias;
$m = new Multimedia;
$this->performAjaxValidation(array($n,$m));
$n=$this->loadModel($id);
if(isset($_POST['Noticias'],$_POST['Multimedia']))
{
$n->attributes=$_POST['Noticias'];
$m->attributes=$_POST['Multimedia'];
$m->ID_NOT=$n->ID;
$m->setIsNewRecord(false);
if($n->save())
$this->redirect(array('admin','id'=>$n->ID));
}
$this->render('update',array('n'=>$n,'m'=>$m));
}
update.php
<?php echo $this->renderPartial('_form', array('n'=>$n, 'm'=>$m)); ?>
some view
//get Multimedia FK
<?php if ($n->isNewRecord==false) {
$m=Multimedia::model()->findByPk($n->ID);
} ?>
//Validation
<?php echo $form->errorSummary(array($n,$m)); ?>
//Field FOTO between other
<div class="row">
<?php echo $form->labelEx($m,'FOTO_URL'); ?>
<?php echo $form->textField($m,'FOTO_URL',array('size'=>25,'maxlength'=>100)); ?>
<?php echo $form->error($m,'FOTO'); ?>
</div>
First - do not load models in view
<?php if ($n->isNewRecord==false) {
$m=Multimedia::model()->findByPk($n->ID);
} ?>
This part should be in controller action.
Make sure $m and $n are really models. If findByPk statement above fails, $m will be null, so you will get error from errorSummary which calls $m->getErrors() and $n->getErrors(). In short - make sure $n and $m are properly initialized - both must be instances of model, either empty, or filled from db, but in your case one is null. Most probably $m
this error occur when Noticias (ie $n is newrecord) or $n->ID is not found in Multimedia
you can solve this if you need to work even if its a new record you can use.
if ($n->isNewRecord==false) {
$m=Multimedia::model()->findByPk($n->ID);
}
else
$m=new Multimedia;
You can try to load both models in Controller (ex. in actionUpdate) :
public function actionUpdate($id)
{
$n = new Noticias;
$m = new Multimedia;
$this->performAjaxValidation(array($n,$m));
$n=$this->loadModelNoticias($id);
$m=$this->loadModelMultimedia($n->ID); //just put it here..
if(isset($_POST['Noticias'],$_POST['Multimedia']))
{
$n->attributes=$_POST['Noticias'];
$m->attributes=$_POST['Multimedia'];
$m->ID_NOT=$n->ID;
$m->setIsNewRecord(false);
if($n->save())
$this->redirect(array('admin','id'=>$n->ID));
}
$this->render('update',array('n'=>$n,'m'=>$m));
}
Please be noticed that you have to define both loadModel functions in the same controller too.
function loadModelNoticias($id){
$model = Noticias::model()->findByPk($id);
return $model;
}
function loadModelMultimedia($id){
$model = Multimedia::model()->findByPk($id);
return $model;
}

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

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

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.