Elements in cake php - cakephp

i am using linux-mint os
i have to put a search form on front-end on my web's home page:
i have done something like this:
Model for my app:
var/www/project/app/model/search.php
<?php
class Search extends AppModel {
var $name = 'Search';
}
?>
My controller :
var/www/project/app/controller/searches_controller.php
<?php
class SearchesController extends AppController {
var $name = 'Searches';
var $helpers = array('Html', 'Form');
function search()
{
$this->layout = 'default';
return $searches = $this->Search->find('all');
}
}
?>
After following the above steps i have create an Element to show the form on my home page
My Element :
var/www/project/app/views/element/search.ctp
<?php
$searches = $this->requestAction('searches/search');
?>
<?php
echo $form->create('Search', array('controller'=>'searches',
'action' => 'search'));?>
<select name="search">
<option>------Select------</option>
<?php foreach($searches as $search) { ?>
<option value="<?php echo $search['Search']['id'];?>">
<?php echo $search['Search']['media'];?></option>
<?php } ?>
</select>
<?php echo $form->end('submit'); ?>
And i put code in my default.ctp like this :
<?php echo $this->element('search');?>
Having done all this, i tried to view my home page but it shows an error message:
Fatal error: Call to a member function create() on a non-object in
/var/www/Emedia/app/views/elements/search.ctp on line 4
Notice (8): Undefined variable: form [APP/views/elements/search.ctp, line 4]

The form should be:
//in your element
//remove echo $element->create... and use
echo $form->create('Search', array(
'id' => 'someform',
'url' => array(
'controller' => 'searches',
'action' => 'search')
)
);
//and form end
echo $form->end('submit'); //not $element->end('submit');

there shouldnt be any "return" - why are you doing that?
use "cake bake" if you are not yet familiar with how it works.
anyway, that should help:
$searches = $this->Search->find('all');
$this->set(compact('searches'));

If you are using CakePHP 2.x then I thinks you cant access FormHelper directly through variable $form
Try:
$this->Form->create('Search',array('action'=>'yourAction'));

echo $form->create('Search', array('controller'=>'searches',
'action' => 'search'));?>
instead of using :
echo $this->Form->create('Search', array('controller'=>'searches',
'action' => 'search'));?>
it will Resolve :
Fatal error: Call to a member function create() on a non-object in
/var/www/Emedia/app/views/elements/search.ctp on line 4

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'); ?>

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));

CakePHP 2.1 + AJAX Search / JsHelper

I try to create an Ajax search with CakePHP using the JsHelper. The Ajax request triggers but it never returns values:
Search form (find_entries.ctp):
<?php echo $this->Form->create('Entry');?>
<?php echo $this->Form->input('title', array('div' => false, 'empty', 'label' => false, 'placeholder' => 'Search'));?>
<?php echo $this->Js->submit('Upload', array(
'before'=>$this->Js->get('#checking')->effect('fadeIn'),
'success'=>$this->Js->get('#checking')->effect('fadeOut'),
'update'=>'#choose_options')
)
;?>
<?php echo $this->Form->end();?>
Controller:
public function find_entries(){
if(!empty($this->request->data)){
$entries = $this->Entry->find('all', array('conditions' => array('Entry.title' => $this->request->data['Entry']['title);
$this->set('entries', $entries);
if($this->RequestHandler->isAjax()){
$this->render('entries', 'ajax');
}
}
}
Partial to render (entries.ctp)
<div id="entries">
<?php foreach ($entries as $entry) :?>
<?php echo $entry['Entry']['title']; ?>
<?php endforeach ;?>
What goes wrong here? thanks!
have you created any div tag with id choose_options to render the ajax result? If not create a div tag like this in the view file.
<div id="choose_options"></div>

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; ?>

Why do I get these errors:?

My error code is:
Notice: Undefined variable: form in
c:\AppServ\www\applogic\app\views\users\index.ctp on line 1
Fatal error: Call to a member function create() on a non-object in
c:\AppServ\www\applogic\app\views\users\index.ctp on line 1)))
(index.ctp)
<?php echo $form->create(null, array('action' => 'index'));?>
<fieldset>
<legend>Enter Your Name</legend>
<?php echo $form->input('name'); ?>
</fieldset>
<?php echo $form->end('Go');?>
(users_controller.php)
<?php
class UsersController extends AppController {
var $name = 'Users';
var $uses = array();
function index() {
if (!empty($this->data)) {
//data posted
echo $this->data['name'];
$this->autoRender = false;
}
}
}
?>
Did you set the $helpers in app_controller or users_controller? You need to include 'Form' in it.
If you are using 2.0, I think you need to use $this->Html (not $html)

Resources