Use a function in $this->set() with CakePHP 2.1 - cakephp-2.1

I'm just wondering how I can use/define my own function using the $this->set() method in CakePHP? I want to do something like this...
AppController.php
<?php
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
$this->set('isSetup', checkSetup());
?>
And then I will be able to access and call it in my view file:
<?php if ($isSetup): ?>
You haven't setup your profile yet!
<?php endif; ?>
I've tried that, but It clearly doesn't work as I get a massive fatal error. Any ideas/suggestions on how I can do this?

$this->set('isSetup', checkSetup());
That line needs to be inside some function in order to be called. Presumably you want it in the beforFilter of your app controller - something like this:
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
function beforeFilter() {
$this->set('isSetup', checkSetup());
}
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
}
?>

Related

Edit & Update In Codeigniter

While doing update i am getting following error
Severity: Notice Message: Undefined variable: user
This is my controller:
public function update_user_id($user_id) {
if($this->input->post('submit')){
$courses = array(
'user_name'=>$this->input->post('user_name'),
'email'=>$this->input->post('email')
);
$this->users_model->update_user($user_id,$users);
$base_url=base_url();
redirect("$base_url"."Dashboard/update_user_id/$user_id");
}
$result['user']=$this->users_model->user_id($user_id);
$this->load->view('edit_user',$result);
}
Which is my view
<?php echo form_open(base_url().'Admin/update_user_id/'.$user[0]->user_id);?>
User Name: <input type="text" name="user_name" value=" <?php echo $user[0]->user_name; ?>">
Email: <input type="text" name="email" value=" <?php echo $user[0]->user_name; ?>">
<?php echo form_close();?>
Don't know whats wrong with the code
Always follow documentation. By CI council convention, your class names should follow file names. I suppose you have that right. But you didn't follow demand for ucfirst() file and class names.
So in your case file shouldn't be named CoursesModel neither class should be named CoursesModel, but you should name your file and class Coursesmodel. Remember ucfirst() rule (regarding CI3+) for naming all classes wether controllers, models or libraries.
Also, if you load those files (models and libraries), for libraries always use strtolower() name while for models you can use both strtolower() and ucfirst() formatted name.
Personaly, I use to load libraries with strtolower while using to load models with ucfirst name and that way I make difference between those just having a quick look on code.
Try with:
Courses_m.php (This way I speed up parsing a little bit)
<?php defined('BASEPATH') or exit('Not your cup of tea.');
class Courses_m extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function update_course($course_id, $courses)
{
// your DB task --should return something
return true ?: false;
}
}
And in controller:
Courses_c.php (in APPPATH . 'config/routes.php' you can set what ever name you like for your route)
<?php defined('BASEPATH') or exit('Not your cup of tea.');
class Courses_c extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('form_validation');//just an library loading example
$this->load->model('Courses_m');//notice first capital here
}
public function update_course_id($course_id)
{
if($this->input->post('submit'))
{
$courses = array(
'course_name'=>$this->input->post('course_name'),
'no_of_hours'=>$this->input->post('no_of_hours')
);
// pay attention on capital first when you calling a model method
// need to be the same as in constructor where file is loaded
$this->Courses_m->update_course($course_id,$courses);
// you can use this way
redirect(base_url("Dashboard/update_course_id/$course_id"));
}
// use else block to avoid unwanted behavior
else
{
$result['course']=$this->Courses_m->course_id($course_id);
$this->load->view('edit_course',$result);
}
}
}

CakePHP-AjaxMultiUpload and Auth

my problem is, that I used this plugin https://github.com/srs81/CakePHP-AjaxMultiUpload/ and everything worked correctly. But now I "installed" it again, in a new project, and I got a "failed"-message. The only thing which is different, compared to my old project, is, that I used the Auth-Component. Am I not able to use both at the same time?
Sorry for my english, but I'm from Germany :)
Thanks in advance!
My UploadController:
<?php
App::uses('AppController', 'Controller');
class UploadController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('add'));
}
public function isAuthorized() {
return true;
}
public function add() {
}
} ?>
my view:
<?php
echo $this->Form->create('Upload', array('type' => 'file'));
echo $this->Upload->edit('Upload', 'test');
echo $this->Form->end();
echo $this->Upload->view('Upload', 'test');
?>
The following is taken from the github gotchas section for the plugin (in the question) re-referenced here https://github.com/srs81/CakePHP-AjaxMultiUpload/
thanks to rscherf#github for the following two fixes.
Using Auth
If you are using Auth (either the CakePHP core Auth or some of the compatible or incompatible ones), you need to modify the controller to allow uploads to work.
Add these lines to the UploadsController.php (you may have to modify slightly depending on your Auth setup):
public function isAuthorized() {
return true;
}
public function beforeFilter() {
$this->Auth->allow(array('upload','delete'));
}

Array is not recognized in Codeigniter's View

I'm trying to pass an array to a view from a controller but I can't and I don't know why.
I have a model, a controller and a view.
The model:
<?php
class Modelo_bd extends CI_Model
{
public function datos()
{
$cnb=$this->db->query("SELECT * from anuncios");
return $cnb->result();
}
}
?>
The controller:
if($this->modelo_usuarios->puede_entrar($usr))
{
$this->load->model("modelo_bd");
$cbd=$this->modelo_bd->datos();
$this->load->view('datos',$cbd);
return true;
}
The view:
<?php
echo $cbd->titulo_a;
echo $cbd->contenido;
?>
The error is in the view.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: cbd
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Why $cbd variable isn't recognized in the view if it is an array? How can I fix it?
Thanks.
In the controller :
if($this->modelo_usuarios->puede_entrar($usr))
{
$this->load->model("modelo_bd");
$cbd=$this->modelo_bd->datos();
$this->load->view('datos', array('cbd' => $cbd);
return true;
}
The second parameter should be array.
You can use in the model:
public function datos()
{
return $this->db->query("SELECT * from anuncios");
}
and in the view:
<?php
foreach ($cdb->result() as $item) {
echo $item->titulo_a;
echo $item->contenido;
}
?>
Shouldn't you rather do:
The controller:
if($this->modelo_usuarios->puede_entrar($usr))
{
$this->load->model("modelo_bd");
$data['cbd']=$this->modelo_bd->datos();
$this->load->view('datos',$data);
return true;
}
The view:
<?php
foreach($cbd as $key => $row){
echo $row->titulo_a;
echo $row->contenido;
}
?>
I think this works better, your choice.
You should do it like this
if($this->modelo_usuarios->puede_entrar($usr))
{
$this->load->model("modelo_bd");
$data['cbd'] = $this->modelo_bd->datos();
$this->load->view('datos',$data);
}

Cakephp $this->Auth->loggedIn() doesnt always work

I am using cakephps Auth Component to login to my site. When I correctly enter in my username and password, it will log me in. Then when I use loggedIn() to check that I am logged in, it is very inconsistent in returning true.
This is my AppController where I set loggedIn() to a variable to use later:
<?php
App::uses('Controller', 'Controller');
App::uses('File', 'Utility');
App::uses('AuthComponent', 'Component');
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=> array('controller'=>'users', 'action'=>'index'),
'logoutRedirect'=> array('controller'=>'users', 'action'=>'index'),
'authError' =>"You can't access that page",
'authorize'=> array('Controller')
)
);
//determines what logged in users have access to
public function isAuthorized($user){
return true;
}
//determines what non-logged in users have access to
public function beforeFilter(){
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And here is a bit of my code where I use 'logged_in'
<?php if($logged_in): ?> //this only returns true some of the time
Welcome <?php echo $current_user['username']; ?>. <?php echo $this->Html->link('Logout', array('controller'=>'users', 'action'=>'login')); ?>
<?php else: ?>
<?php echo $this->Html->link('Login', array('controller'=>'users', 'action'=>'logout')); ?>
<?php endif; ?>
And here is my login():
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){ //this returns true every time
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Your username and/or password is incorrect');
}
}
}
I have tried calling $this->Auth->loggedIn() instead of using $logged_in but I get the error that the Auth Helper cannot be found.
Please let me know if there is any more information needed to answer my question.
Move these lines to beforeRender()
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
Besides that, nothing seems wrong with your code.
The comment that Auth->login() would always return true only happens when you pass any argument to the login() method, which the code you show doesnt have though.

user can't login using CodeIgniter with facebook php sdk

I am following the guide here to play around with the facebook php sdk, but my little app doesn't work. It keeps staying on the login page.
Here is the controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_connect extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library('fb_connect');
}
function index()
{
}
function test()
{
$data['title'] = 'Facebook API Testing';
$data['user_id'] = $this->fb_connect->user_id;
if($data['user_id'])
{
$data['user_profile'] = $this->fb_connect->user;
}
if($data['user_id'])
{
$data['logout_url'] = $this->fb_connect->getLogoutUrl();;
}
else
{
$data['login_url'] = $this->fb_connect->getLoginUrl();
}
$this->template->load('template', 'facebook_connect/test', $data);
}
}
?>
Here is the view:
<h1>php-sdk</h1>
<?php if($user_id): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if($user_id): ?>
<h3>Your Avata</h3>
<img src="https://graph.facebook.com/<?php echo $user_id; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
I get stuck at it and couldn't figure out why.
Use this example provided by facebook:
https://github.com/facebook/php-sdk/blob/master/examples/example.php
But keep your $this->load->library('fb_connect'); and make sure to add $this->fb_connect to any facebook library calls in that example.
It works 100%. Try to just put all the code in the controller to make sure it works, then distribute as needed. Not sure what your problem is, perhaps faulty return url.

Resources