Pagination in home.ctp not clickable data - cakephp

home.ctp
<?php
echo $this->element('distromob/featured');
?>
WebsitesController.php
<?php
class WebsitesController extends AppController {
public $components = array('Paginator');
public function index(){
$images = $this->paginate('Website');
if (isset($this->params['requested'])) {
return $images;
} else {
$this->set('images', $images);
}
}
featured.ctp
<?php
$images = $this->requestAction('/Websites/index');
?>
<ul>
<?php
foreach($images as $image): ?>
<?php $domain = $image['Website']['domain'];?>
<li><?php echo $this->Html->image('websites/' . $image['Website']['image'],array('width'=>'234px','height' =>'208px','class' => 'random'));
?>
</li>
<?php endforeach;?>
</ul>
<?php echo $this->Paginator->prev('« Previous', null, null, array('class' => 'disabled')); ?>
<?php $this->Paginator->counter(); ?>
<?php echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled')); ?>
AppController.php
class AppController extends Controller {
public function beforeFilter(){
$this->Paginator->settings=array(
'limit'=>4
);
}
}
Im new to cakephp I found some tutorial on the web but it seems not fit on my needs. My question was, why is it the previous and the next pagination data is not clickable, It seems that the pagination data is base on the limit i set on
public function beforeFilter(){
$this->Paginator->settings=array(
'limit'=>4
);
}
whenever i change the limit it will also display data but i cannot click the next and the previous

make the pagination data available in the element i.e $this->params['paging']
//index method
if ($this->params['requested'])
return array('images'=>$this->paginate('WebSite'), 'paging' => $this->params['paging']);
$this->set('images', $this->paginate('WebSite') );
then in your home.ctp do this
$images = $this->requestAction(array('controller'=>'websites','action'=>'index'));
// if the 'paging' variable is populated, merge it with the already present paging variable in $this->params. This will make sure the PaginatorHelper works
if(!isset($this->params['paging'])) $this->params['paging'] = array();
$this->params['paging'] = Hash::merge( $this->params['paging'] , $images['paging'] );

Try replacing ->counter() with ->numbers() to see if you have any page numbers

Related

how give pagination to controllers

in controller
public function home($id=null){
$this->loadModel('Usermgmt.User');
if(isset($id)){
$groups=$this->User->findAllByuser_group_id($id);
$this->set('groups', $groups);
} else{
echo 'no id';
$users=$this->User->find('all');
$this->set('users', $users);
}
}
here i geeting value which matches the user_group_id and prints here i am geeting more then 10 users but i need to print only 5 on one page and need to give pagination how to give pagination here
view
<?php
if (!empty($groups)) {
// print_r($groups);
$sl=0;
foreach ($groups as $row1) {
//print_r($row1);
$sl++; ?>
<div style="width:100%;display:inline-block;">
<div style="float:left">
<?php
//echo $row1['id'];
echo $this->Html->link($this->Html->image('../files/user/photo/'.$row1 ['User']['photo_dir'].'/'.$row1 ['User']['photo'], array('width' => '180', 'height' => '180')),
array('controller'=>'Profiles','action'=>'index',$row1['User']['id']),
array('escape' => false));
?>
</div>
<div>
<?php echo h($row1['User']['first_name'])." ".h($row1['User']['last_name'])."</br>";
echo h($row1['User']['username'])."</br>";
echo h($row1['User']['email'])."</br>";
echo h($row1['User']['mobile'])."</br>";
echo h($row1['UserGroup']['name'])."</br>";
?></div>
<div style="clear:both;"></div>
</div>
<?php }
}?>
Call paginate
The equivalent paginate call to this:
$groups=$this->User->findAllByuser_group_id($id);
(incidentally - that should be findAllByUserGroupId) is this:
$groups = $this->paginate('User', array('user_group_id' => $id));
Changing default options
To achieve:
i need to print only 5 on one page
Modify the paginate property of your controller, e.g.:
class UsersController extends AppController {
public $paginate = array('limit' => 5);
function home($id = null) {
...
$conditions = array();
if ($id) {
$conditions['user_group_id'] = $id;
}
$groups = $this->paginate('User', $conditions);
...
}
}
View Modifications
In your view, the pagination helper, and the pagination information will automatically be available by calling paginate as shown above. To get pagination links use the pagination helper:
echo $this->Paginator->numbers();
See the documentation for more information and examples of using pagination.
As in cakephp pagination can be done using pagination helper of cakephp
In controller action use $this->paginate . From Model return all parameters like fields, conditions and so on in array format , so now in controller you will write
$data = $this->ModelName->functionname();
$currentPage = isset($_REQUEST['currentpage']) ? $_REQUEST['currentpage'] : '';
$this->paginate = array(
'fields' => $data['fields'],
'conditions' => $data['conditions'],
'order' => $data['order'],
'page' => $currentPage,
'limit' => 25
);
$currentPage is fetched from $_REQUEST['currentpage'];
and finally pass this data to Paginate Helper
$data = $this->paginate('ModelName');
Now in view you will use Pagination functions as shown below
<?php echo $this->Paginator->prev('revious'); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next'); ?>

CakePHP different tables displays in the same page

I'd like to make website, with news and comments attached to them.
I made Model Infos.php ( connected to news on my page) and Model Infos_coms.php ( where comment should be saved for each news). For each Model I've got controlleres as follows
InfosController.php
class InfosController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Session');
public function index()
{
$this->set('inform', $this->Info->find('all'));
//$this->loadModel('Infos_com');
//$this->set('com', $this->Infos_com->find('all'));
}}
, Info_comsController.php.
<?php
class Infos_comsController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Session');
public function index()
{
$this->set('com', $this->Infos_com->find('all'));
}}
and there is my problem, couse i don't know how to display both tables (news and their comments on one page)
here is my index, i've red twice cookbook chapter about view and i didn't find there answer for solving my problem.
here is my Index file in folder (View/Infos)
<body>
<?php echo $this->Html->link(__('Dodaj newsa',true),array('action'=>'add')); ?>
<div class="container">
<?php
foreach ($inform as $news) : ?>
<h3>
<?php echo $news['Info']['title']; ?>
</h3>
<p>
<?php echo $news['Info']['body']; ?>
</p>
<small>
<?php echo $news['Info']['created']; ?>
</small>
<small>IP:
<?php echo $news['Info']['ip']; ?>
</small>
<!-- existing comments -->
<?php foreach ($com as $comment): ?>
<h4>
<?php echo $comment['Infos_com']['body']; ?>
</h4>
<small>
<?php echo $comment['Infos_com']['created']; ?><br>
<?php echo $comment['Infos_com']['ip']; ?>
</small>
<!-- adding comments -->
<div class="form-group">
<?php echo $this->Form->create('Infos_com'); ?>
<?php echo $number = $comment['Info']['id']; ?>
<?php echo $this->Form->input(__('mail',true),array('class'=>'form-control')) ?>
<?php echo $this->Form->input(__('Comment body',true), array('class'=>'form-control')); ?>
<?php echo $this->Form->submit(__('Dodaj komentarz',true),array('class'=>'btn btn-info')); ?>
<?php echo $this->Form->end(); ?>
</div>
<?php endforeach; ?>
<?php endforeach; unset($news); unset($comment);?>
i will be gratefull for any tip
Edit.
I followed Guillemo Mansilla suggest, but now i got issue with database. I've used Guillemo Mansilla code, with changed names, and also adde something i think correctly. There are my Modal
Info.php
<?php
class Info extends AppModel
{
public $hasMany = array('Infos_com');
public $validate = array(
'title'=>array(
'rule'=>'notEmpty'
),
'body'=>array(
'rule'=>'notEmpty'
)
);
}
?>
Infos_com.php
<?php
class Infos_com extends AppModel
{
public $belongsTo = array('Info');
public $validate = array(
'mail'=>array(
'requierd'=>array(
'rule'=>'notEmpty',
'message'=>'Write your email'
)
),
'body'=>array(
'rule'=>'notEmpty',
'message'=>'Write a comment'
)
);
}
?>
i changed my index.ctp inside body part to
<?php if (isset($inform)) {
foreach($inform as $info) {
echo $info['Info']['title'];
foreach($info['Infos_com'] as $comment) {
echo $comment['Infos_com']['body'];
}
}
} ?>
now i'm getting error
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Infos_com.info_id' in 'field list'
SQL Query: SELECT Infos_com.id, Infos_com.id_infos, Infos_com.username, Infos_com.mail, Infos_com.ip, Infos_com.created, Infos_com.body, Infos_com.info_id FROM blogdb.infos_coms AS Infos_com WHERE Infos_com.info_id IN (1, 2, 3, 4, 5)
i have both tables so i don't understand where is mistake.
I will assume that your associations are correct, that is, Info hasMany Infos_com, so in your Info Model you have something like
public $hasMany => array('Infos_com')
I am going to assume that both models are correctly created (You didn't paste your models)
Now, in your controller InfosController, just do this
$this->Info->recursive = 1;
$this->set('inform', $this->Info->find('all'));
In your view, you will have all "infos" along with its comments in a var named $inform, just iterate over it recursively
if (isset($inform)) {
foreach($inform as $info) {
echo $info['Info']['title']; //I dont even know if you have a field named "title"
foreach($info['Infos_com'] as $comment) {
echo $comment['Infos_com']['comment'];
}
}
}
bear in mind that this piece of code probably don't work because we use different names, just adapt it to what you have in there
I finnaly make it , after all night !!!
i Changed column name in my Infos_com from id_infos to info_id
next i edit my index code to
<?php if (isset($inform)) {
foreach($inform as $info) {
echo $info['Info']['title']; echo '<br>';
echo $info['Info']['body']; echo '<br>';
foreach($info['Infos_com'] as $comment) {
echo $comment['body']; echo '<br>';
echo $comment['mail']; echo '<br>';
}
}
} ?>
and finnaly i got my comment under my news, THANK YOU !

Two forms from one model both forms validate when one form is submittted

I have to use a form once in footer and in individual page i.e. index.ctp.
For that I have a database table named contactforms.
I have created a model Contactform.php
<?php
App::uses('AppModel', 'Model');
/**
* Contactform Model
*
*/
class Contactform extends AppModel {
/**
* Validation rules
*
* #var array
*/
var $useTable = false;
public $validate = array(
'firstname' => array(
'notempty' => array(
'rule' => array('notempty')
)
),
'contactno' => array(
'notempty' => array(
'rule' => array('notempty')
)
),
'email' => array(
'notempty' => array(
'rule' => array('notempty')
)
)
);
}
?>
I have a controller from where I am trying to send an email
<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class ContactformsController extends AppController {
public function index() {
$this->Contactform->recursive = 0;
$this->set('contactforms', $this->paginate());
}
public function contact() {
$email = new CakeEmail();
if(isset($this->params['requested']) && $this->params['requested']==true)
{
if ($this->request->is('post'))
{
$this->Contactform->set($this->request->data);
if($this->Contactform->save($this->request->data))
{
$name=$this->request->data['Contactform']['firstname'];
$lastname=$this->request->data['Contactform']['lastname'];
$contact=$this->request->data['Contactform']['contactno'];
$mail= $this->request->data['Contactform']['email'];
$email->from(array($mail => $name));
$email->to('abc#gmail.com');
$message= $this->request->data['Contactform']['message'];
$email->subject('Wombats contact form information');
if($email->send($message))
{
$this->Session->setFlash('Quote Processed..Thank You For Visiting Our Website!!!');
$this->redirect($this->referer());
}
}
}
}
}
}
?>
And then I created an element which I used called in footer and then in index file.
contact.ctp looks like
<?php echo $this->Html->css('contactfooter.css');?>
<?php $contactforms = $this->requestAction('Contactforms/contact') ?>
<div class="frm">
<?php echo $this->Form->create('Contactform'); ?>
<div class="firstrow">
<div class="first">
<?php echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','div'=>'firstname','style'=>'width:130px; height:20px;' ));?>
<?php // echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','style'=>'width:130px; height:20px; float:left; margin-right:5px;','error'=>array('attributes'=>array('wrap'=>'div','class'=>'errorfirst'))));?>
</div>
<div class="second">
<?php echo $this->Form->input('lastname',array('label'=>false,'placeholder'=>'lastname','div'=>'lastname','style'=>'width:140px; height:20px; '));?>
</div>
</div>
<!--<div class="secondrow">-->
<?php echo $this->Form->input('contactno',array('label'=>false,'placeholder'=>'contactno','div'=>'contactno','style'=>'width:270px; height:20px; margin-bottom:10px;'));?>
<!--</div>-->
<?php echo $this->Form->input('email',array('label'=>false,'placeholder'=>'email','div'=>'email','style'=>'width:270px; height:20px; '));?>
<?php echo $this->Form->input('message',array('label'=>false,'placeholder'=>'message','div'=>'message','style'=>'width:270px; height:25px;margin-top:10px; '));?>
</div>
<!--<br>-->
<div class="sub">
<?php echo $this->Form->end('SUBMIT'); ?>
</div>
When I click submit of one form other form as well validates.
I tried a lot but don't know how to fix Can anyone please help.
EDIT:-
#Nunser I am very confused with these names sorry for that. I have changed my code according to what u told but still its validating one form only.
I have a doubt, according to you I should change in view and elements too but I just have elements.Please can u help I am posting my edited code
I called element from index page as
<?php echo $this->element('Contactform/contact',array('source'=>'index')); ?>\
and from default page as
<?php echo $this->element('Contactform/contact'); ?>
my controller action is
public function contact() {
$email = new CakeEmail();
if(isset($this->params['requested']) && $this->params['requested']==true){
if ($this->request->is('post'))
{
$index = 'Contactform';
if (isset($this->request->data['Contactformindex']))
$index = 'Contactformindex';
$this->Contactform->set($this->request->data[$index]);
if($this->Contactform->save($this->request->data[$index]))
{
$name=$this->request->data[$index]['firstname'];
$lastname=$this->request->data[$index]['lastname'];
$contact=$this->request->data[$index]['contactno'];
$mail= $this->request->data[$index]['email'];
$email->from(array($mail => $name));
$email->to('skyhi13#gmail.com');
$message= $this->request->data[$index]['message'];
$email->subject('Wombats contact form information');
//$email->send($message);
if($email->send($message))
{
$this->Session->setFlash('Quote Processed..Thank You For Visiting Our Website!!!');
//$this->render('/view/elements/quotes/quoteform.ctp');
// $this->autoRender=FALSE;
$this->redirect($this->referer());
}
}
else {
$this->set('formName',$index);
}
}
}
}
In the elements ctp file I changed as
<?php if (!empty($this->validationErrors['Contactform'])) {
$this->validationErrors[$formName] = $this->validationErrors['Contactform'];
}?>
<div class="frm">
<?php
if(isset($source)&& $source == 'index')
echo $this->Form->create('Contactformindex');
else
echo $this->Form->create('Contactform');
?>
<div class="firstrow">
<div class="first">
<?php echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','div'=>'firstname','style'=>'width:130px; height:20px;' ));?>
<?php // echo $this->Form->input('firstname',array('label'=>false,'placeholder'=>'firstname','style'=>'width:130px; height:20px; float:left; margin-right:5px;','error'=>array('attributes'=>array('wrap'=>'div','class'=>'errorfirst'))));?>
</div>
<div class="second">
<?php echo $this->Form->input('lastname',array('label'=>false,'placeholder'=>'lastname','div'=>'lastname','style'=>'width:140px; height:20px; '));?>
</div>
</div>
<!--<div class="secondrow">-->
<?php echo $this->Form->input('contactno',array('label'=>false,'placeholder'=>'contactno','div'=>'contactno','style'=>'width:270px; height:20px; margin-bottom:10px;'));?>
<!--</div>-->
<?php echo $this->Form->input('email',array('label'=>false,'placeholder'=>'email','div'=>'email','style'=>'width:270px; height:20px; '));?>
<?php echo $this->Form->input('message',array('label'=>false,'placeholder'=>'message','div'=>'message','style'=>'width:270px; height:25px;margin-top:10px; '));?>
</div>
<!--<br>-->
<div class="sub">
<?php echo $this->Form->end('SUBMIT'); ?>
</div>
Using this code still it validated one form only and form is that which I have called without source as index and when clicked on index submit button it validates the other form. I am not sure as do I have to use the same Fromindex name as specified by you, does that matter. I am not able to find as where I am going wrong.Please help and Thanks in advance.
First, why are you doing this
<?php $contactforms = $this->requestAction('Contactforms/contact') ?>
in your element? I don't see the use of that requestAction except slowing down the processing...
Ok, but your problem...
Since you're calling an element, there's no easy way to avoid the validation of both forms. Usually, when there are two forms corresponding to the same model, the way to not validate both is to change the "name" of the form like this
<!--in the first form-->
<?php echo $this->Form->create('Contactform1'); ?>
<!--in the second form-->
<?php echo $this->Form->create('Contactform2'); ?>
But, since you are creating that form with an element, there's no easy way of changing the name of the form in one place and not in the other...
So this is what you should do (there may be other ways of doing what you want, but this is the one I can think of). When you call the contact.ctp element, pass a variable to it
echo $this->element('contact', array(
"source" => "index"
));
With that, you know you're calling the element from the index.ctp, for example. Then, in the element, change the form declaration depending on the variable
//the beginning of your element
<?php
if (isset($source) && $source == 'index')
echo $this->Form->create('FromIndex');
else
echo $this->Form->create('FromContact');
?>
You'll also need to modify your action, to read the data in FromIndex or in FromContact, depending on where it came from
public function contact() {
$email = new CakeEmail();
if(isset($this->params['requested']) && $this->params['requested']==true) {
if ($this->request->is('post')) {
//change the index of the array depending on where it came form
$index = 'FromContact';
if (isset($this->request->data['FromIndex']))
$index = 'FromIndex';
$this->Contactform->set($this->request->data[$index]);
if($this->Contactform->save($this->request->data[$index]))
{
$name=$this->request->data[$index]['firstname'];
$lastname=$this->request->data[$index]['lastname'];
$contact=$this->request->data[$index]['contactno'];
$mail= $this->request->data[$index]['email'];
$email->from(array($mail => $name));
$email->to('abc#gmail.com');
$message= $this->request->data[$index]['message'];
$email->subject('Wombats contact form information');
if($email->send($message))
{
$this->Session->setFlash('Quote Processed..Thank You For Visiting Our Website!!!');
$this->redirect($this->referer());
}
}
}
}
}
}
When you save or set something (unless is with saveAssociated, saveAll or those kind of functions, when you're saving more than one model), there's no need to specify the model in the array to be saved.
$saveMe = array('User'=>array('name'=>'John'));
$saveMeToo = array('name'=>'John');
$this->User->save($saveMe); //will work
$this->User->save($saveMeToo); //will work too
That's why the change of $this->request->data indexes will work either way. But the validation will be for the specific index (FromContact or FromIndex).
Note: I haven't tested the code, so be sure to check for missing parenthesis, unclosed ' and those kind of things.
EDiT
#winnie pointed out that the validation only happened for one form, and that's because I overlooked something. The validation errors get displayed in the view if there's something set in this variable $this->validationErrors['ModelName'] in the view. And that's what I missed. So, re-change the action to pass the $index of the model to the view, so the view knows which form called the action, like this
public function contact() {
$email = new CakeEmail();
if(isset($this->params['requested']) && $this->params['requested']==true) {
if ($this->request->is('post')) {
//change the index of the array depending on where it came form
$index = 'FromContact';
if (isset($this->request->data['FromIndex']))
$index = 'FromIndex';
$this->Contactform->set($this->request->data[$index]);
if($this->Contactform->save($this->request->data[$index]))
{
//this if is exactly the same as the other one
} else {
//now, if there's no save, there's some validation errors
//tell the view which form called this save
$this->set('formName', $index);
}
}
}
Now in the view you need to copy the errors you get in the model, to the "fake model name" we gave the form. In the first line of your view do this (and in the element too)
if (!empty($this->validationErrors['Contactform'])) {
$this->validationErrors[$formName] = $this->validationErrors['Contactform'];
}

How to define a variable in Cakephp

I trying to pass a variable in cakephp to a view and getting error Undefined variable: view [APP\View\ItQueries\add.ctp, line 9] and line 9 is this
<?php echo $this->Form->hidden('status_type', array('value'=>$view)); ?>
Here is how im defining my variable in the controller
class ItQueriesController extends AppController {
var $view = 'Open';
public function index() {
$this->ItQuery->recursive = 0;
$this->set('view', $this->view);
}
//Other Code
}
and here is where im trying to pass the variable as a hidden field
<?php echo $this->Form->create('ItQuery'); ?>
<?php echo __('Add It Query'); ?></legend>
<?php
echo $this->Form->input('status_type', array('type' => 'hidden', 'value'=>$view));
?>
<?php echo $this->Form->end(__('Submit')); ?>
Can some please show me how to fix this
You need to set the variable as part of the viewVars.
To do this add this to your controller action:
$this->set('view', $this->view);
E.g.
class ItQueriesController extends AppController {
var $view = 'Open';
function index() {
$this->set('view', $this->view);
}
}
You can then access it in the view directly using $view
Your hidden field would look like:
echo $this->Form->input('status_type', array('type' => 'hidden', 'value'=>$view));

Avoiding redirect and perssisting the session

I am trying to finish this website in cake php that was previously in regular php, but as newbie in the cakephp world.. I have found some difficulties such as these.
1) .When I click on login, it transfers me to another page although i have specified no redirects in app controller except when there is a registration. The login is at the top and its viewable through out all the pages, but if i click login, it redirects me to the login page (which i do not want).
2.) After I login, it brings in the session with the user name saying welcome 'username' but then if I go to another page, it seems like it forgets the session and brings back the inputs for the login form at the top of the page.
Here is my code
app_controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
$this->Auth->allow('add','get_categories','get_home', 'get_others', 'pages');
$this->Auth->autoRedirect = false;
}
}
?>
UsersController
<?php
class UsersController extends AppController {
var $uses = array("User");
var $components = array('Auth', 'Session');
function index()
{
$this->set('users', $this->User->find('all'));
$this->layout = 'master_layout';
}
function add() {
if (!empty($this->data)) {
//pass is hashed already
//->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your were registered!.');
$this->redirect(array('action' => 'get_home'));
}
}
$this->layout = 'master_layout';
}
//IF THE DATABASE IS SET UP CORRECTLY CAKE AUTHENTICATES AUTOMATICALLY NO
//LOGIC IS NEEDED FOR LOGIN http://book.cakephp.org/view/1250/Authentication
function login() {
$this->layout = 'master_layout';
if ($this->data) {
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$this->data['User']['password'] = '';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
elements/loginform.ctp
<?php
if ($this->Session->read('Auth.User.username')):?>
<?php
echo "Welcome".' ' ;
echo $this->Session->read('Auth.User.username');
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>
UPDATE
I added the following to the app_controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
//new addition
$this->set('userData', $this->Session->read());
$this->Auth->allow('add','get_categories','get_home', 'get_others', 'pages', '*');
$this->Auth->autoRedirect = false;
}
}
?>
WHEN I LOGIN I GET THIS ARRAY
Array ( [Config] => Array
( [userAgent] => 8f12200c2d48fa7955465842befe1c9e
[time] => 1323562284 [timeout] => 10 )
[Auth] => Array (
[User] => Array (
[id] => 63
[user_role] => 2 [
[user_fname] => test
[user_lname] => test
[user_email] => test#test.com
[user_phone] => 677-988-7777
[user_cellphone] => 555-456-9999
[user_address1] => 1st Avenue
[user_address2] =>
[user_city] => Citiland FL
[user_zip] => 55555
[username] => admin2 ) ) )
BUT WHEN I NAVIGATE TO A NEW PAGE
Array ( [Config] => Array (
[userAgent] => 8f12200c2d48fa7955465842befe1c9e
[time] => 1323562591 [timeout] => 10 ) )
ADDED PRINT_R TO elements/loginform TO SEE THE VARIABLE CONTENTS ACROSS ALL PAGES
<?php
print_r($userData);
if ($this->Session->read('Auth.User.username')):?>
<?php
echo "Welcome".' ' ;
echo $this->Session->read('Auth.User.username');
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>
1) This is because in your UsersController you have a redirect after the user is logged in.
Your login function should instead read:
function login() {
$this->layout = 'master_layout';
if ($this->data) {
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
/*This is the offending line, I've commented it out, but you could have it redirect somewhere else (it might be a good idea to redirect to the index action, for example, or just delete it:*/
//$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$this->data['User']['password'] = '';
}
As for 2), I believe it may be because you are not setting the data afterwards, so that while it exists in a tmp directory on the server (using the Session component) it is not actually being passed along to the view. So basically I think it's because you can't call Session methods in the view. Even if I'm not entirely correct about that, what I'm suggesting to do should work: Instead of calling session methods in the view, call them in the controller, set them in a variable for the view to access using $this->set();, then test against that variable in the view.
If you need to do this for ton of views and actions, you could consider adding something like this to your controller or even your app controller:
function beforeFilter() {
// Get session data for appllication use
$this->appuserstuff = $this->Session->read();
}
function beforeRender() {
// Make app variables available to view
$this->set('userData', $this->appuserstuff);
}
Alternatively, if you just need this in a couple actions, you could just set the user data in those actions with a:
$this->set('userData', $this->Session->read());
Now I'd recommend that you do a <?php debug($userData); ?> in one of your views so you can see how the data is structured in the array when it is set, so that you can user or test conditionals against. Finally, you could replace the direct calls to Session in your view with instead checks against the array of data:
Please note that I'm not sure how your specific array is structured so do a debug as recommended above and plug in your own keys for it to work:
<?php
if (!empty($userData['User'])):?>
<?php
echo "Welcome".' ' ;
echo $userData['User']['username'];
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>

Resources