Pass array within controller in cakePHP - cakephp

In my controller i have 2 actions e.g
action1() {
//code
SomeArray=();
//code
}
How can i pass all the SomeArray data to action2?
I have tried to create a public array variable in my class and pass it but with no luck.
i have tried to pass as an argument to the action2...
e.g in action1, $this->action2(SomeArray) and then action2($param) with no luck again.
function doExam($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid exam', true));
$this->redirect(array('action' => 'index'));
}
$this->Exam->recursive=1;
$conditions_question = array('Question.exam_id' => $id);
$questions = $this->Exam->Question->find('all',array('conditions' => $conditions_question));
foreach ($questions as $question) {
**$this->questionsByExam[]** = $question['Question']['qst'];
}
//OK PASSED
echo debug($this->questionsByExam);
//OK $exam_id
$this->exam_id = $id;
}
i have another action validate_answer, and i want to pass the questionsByExam in here
any help?
Thanks in advance

I have tried to create a public array variable in my class and pass it but with no luck.
Can you show the code for this? It should work fine as class variable...
E.g:
class FooController extends AppController {
var $someArray = array();
function doExam() {
// Populate the array here
$this->someArray = array(1,2,3);
}
function bar() {
// Use it here, no need to pass it as an argument
print_r($this->someArray);
}
}

Related

Pass array from one controller to another. Laravel

I'm trying to pass array from one controller to another. But I have no idea how to that.
I have my Bill Controller with array:
public function store(Request $request, $id,$sid)
{
$selected = array();
if ($request->annual != 0) {
$selected['annual'] = $request->annual;
}
if ($request->registration != 0) {
$selected['registration'] = $request->registration;
}
if ($request->monthly != 0) {
$selected['monthly'] = $request->monthly;
}
if ($request->annual != 0) {
$selected['annual'] = $request->annual;
}
return redirect()->route('invoice', [$sid]);
}
Here, I have passed $sid to another controller PdfController through route.
My Route:
Route::get('sid/{sid}', 'PdfController#invoice')->name('invoice');
PdfController:
class PdfController extends Controller
{
public function invoice($sid)
{
$data = $this->getData();
$date = date('Y-m-d');
$student = Student::where('id',$sid)->first();
$view = \View::make('layouts.bill',compact('data', 'date','student'))->render();
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($view);
return $pdf->stream('invoice');
}
How can I pass array from my BillController to my PdfController? Can anyone help me?
You can use different ways,
Create a cache (Cache::forever) variable and pass it.
Create a database temporary table with model and pass it.
Create a static variable and first set your variable and get again.
If you can tell which data you need to pass, we can help you much better.

Codeigniter - Array dont work correctly

Whenever I call this function, I get the user_id correctly but the password isnt checked...
Model:
<?php
class Prometheus_model extends CI_Model {
var $tables = array(
'bots' => 'bots',
'users' => 'users'
);
function __construct() {
parent::__construct();
}
public function tablename($table = NULL) {
if(! isset($table)) return FALSE;
return $this->tables[$table];
}
public function get($table, $where = array(), $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
// You should use $q->num_rows() to detect the number of returned rows
if($q->num_rows()) {
return $result[0];
}
return $result;
}
public function update($table, $where = array(), $data) {
$this->db->update($this->tablename($table),$data,$where);
return $this->db->affected_rows();
}
public function insert($table, $data) {
$this->db->insert($this->tablename($table),$data);
return $this->db->insert_id();
}
public function delete($table, $where = array()) {
$this->db->delete($this->tablename($table),$where);
return $this->db->affected_rows();
}
public function explicit($query) {
$q = $this->db->query($query);
if(is_object($q)) {
return $q->result_array();
} else {
return $q;
}
}
public function num_rows($table, $where = NULL) {
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
public function get_bot_data_by_hw_id($bot_hw_id) {
$q = $this->get('bots', array('bot_hw_id' => $bot_hw_id));
return $q;
}
public function check_user_data($user_incredials, $user_password) {
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1){
$q = $this->get('users', array('user_name' => $this->security->xss_clean($user_incredials)));
return $q['user_id'];
}
return FALSE;
}
}
?>
My function-calling at the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index(){
if($this->input->post('user_login')){
var_dump($this->prometheus_model->check_user_data($this->input->post('user_incredials'), $this->input->post('user_password')));
}
$this->load->view('login_index');
}
}
How can i fixx this ?
In your check_user_data() method you are using
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1)
I think (logically) following code
$this->encrypt->decode($user_password)
should be
$this->encrypt->encode($user_password)
because, you are calling num_rows() method and it is
public function num_rows($table, $where = NULL)
{
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
which is actually querying the data base something like, for example,
select * from USERS where user_name = 'heera' and password = decode('abcde12345')
In this case, the password you are trying to match is need to be encrypted using encode (not decode) method, because the user has given you a non-encrypted (plain) password and the password saved in the database is already encrypted, so encode the plain password using encode method before you query the database to match with already encoded passwords.

How to define a checkbox variable in Cakephp

I have a form in my Plugin elements and what i would like to insert the checkbox value into a table named it_queries and field status_type and its giving me an error Undefined variable: variableValue [APP\Plugin\Feedback\View\Elements\comment_add.ctp, line 37] .I have declared the variable in my controller like this
$this->set('variableValueStatus', 'Pending');
and this is line 37 thats giving me the error
Below is the Controller code
App::uses('FeedbackAppController', 'Feedback.Controller');
class CommentsController extends FeedbackAppController
{
public $components = array('Feedback.Comments');
public function add($foreign_model = null, $foreign_id = null)
{
if (empty($foreign_model) ||
empty($foreign_id) ||
!$this->request->is('post')
)
{
foreach ($_POST['likebutton'] as $pageId => $likeFlag) {
$dbFlag = $likeFlag ? 'Yes' : 'No';
}
return $this->redirect('/');
}
App::uses($foreign_model, 'Model');
$Model = ClassRegistry::init($foreign_model);
if (!($Model instanceof Model))
{
return $this->redirect('/');
}
if ($Model->hasAny(array($Model->primaryKey => $foreign_id)) == false)
{
return $this->redirect('/');
}
if (!isset($this->request->data['Comment']['foreign_model']) ||
!isset($this->request->data['Comment']['foreign_id']) ||
$this->request->data['Comment']['foreign_model'] != $foreign_model ||
$this->request->data['Comment']['foreign_id'] != $foreign_id)
{
return $this->redirect('/');
}
$user_id = null;
if (isset($this->Auth))
{
$user_id = $this->Auth->user('id');
}
$this->request->data['Comment']['foreign_model'] = $Model->name;
$this->request->data['Comment']['foreign_id'] = $foreign_id;
$this->request->data['Comment']['user_id'] = $user_id;
$this->Comment->create();
if (!$this->Comment->save($this->request->data))
{
$this->set('validation_errors', $this->Comment->validationErrors);
return;
}
$this->redirect($this->request->referer().'#comment-'.$this->Comment->id);
}
}
and in the add view in my element here is how i am trying to accessing the variable value
echo $this->Form->checkbox('ItQuery.status_type', array('type' => 'hidden', 'value'=>$variableValueStatus));
If someone can show me how to fix this, that would be awesome
You are only passing the variable down on !post and if foreign model and foreign id are not set.
That will most likely not work in most of the cases.
You should be always passing down a variable if you do not check on it in the view prior to using it.
But it would still be wrong, anyway. You would have to use "default" instead of "value" if you dont want your form to fall back on the old value on POST (which it shouldnt).
Also, it is always better to use $this->request->data to properly fill the form with defaults:
if (!$this->request->is('post')) {
$this->request->data['ItQuery']['status_type'] = 'Pending';
}
See working-with-forms

CakePHP 2.2.4: Redirect not Working When Using Component

It has come to my attention that the redirect controller method is not working part of the time. No message appears when I set debug > 0. I don't echo any code before calling the redirect method so it shouldn't be because of "headers already sent".
Let's take a look at my ArticlesController add action where redirect works in one instance but not in another.
public function add($page = null) {
// Custom component to get if user has required access level
// of page to write an article. If not, setflash to an error message
// specific to user's access level and redirect.
$access_message = $this->CustomPage->AccessMessage(4, $this->viewVars['access']);
if($access_message){
// Flash works but redirect does not
$this->Session->setFlash(__($access_message));
$this->redirect(array('action' => 'index', 'page' => $page));
// Also tried
// $this->redirect(array('controller'=>'articles', 'action' => 'index', 'page' => $page), null, true);
} else
{
if ($this->request->is('post')) {
$this->Article->create();
if ($this->Article->save($this->request->data)) {
// BLAH BLAH save post, do other stuff
// BLAH BLAH save post, do other stuff
// This flash and redirect works
$this->Session->setFlash(__('The article has been saved'));
$this->redirect(array('action' => 'view', 'id' => $article_id, 'page' => $page));
} else {
$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
} // end else if article cannot be saved
} // if method is post
} // end if user has access
} // end add action
It definitely has something to do with the component but I'm not sure what. Maybe since redirect is called right after the component is used, the "$this" is trying to do the redirect method on the component instead of the controller. I tried $this->Article->redirect and reloading the Article model before the redirect but neither of those worked.
My component code is:
public function AccessMessage($required_level, $user_level) {
if(!$user_level && $this->_View->viewVars['access']){
$user_level = $this->_View->viewVars['access'];
}
if(!$required_level || !$user_level || $user_level != $required_level){
$accessModel = ClassRegistry::init('Access');
$access_message = $accessModel->field('access_message', array('Access.id' => $required_level));
}
return $access_message;
}
Edit 1: Ok so I did some digging to find exactly where the problem is stemming from. The USE of the component is not the problem which I thought it was before. If all I have in my component is
public function AccessMessage($required_level, $user_level) {
if(!$user_level && $this->_View->viewVars['access']){
$user_level = $this->_View->viewVars['access'];
}
if(!$required_level || !$user_level || $user_level != $required_level){
$access_message = 1;
}
return $access_message;
}
Then it works. The issue is with these two lines which are correctly implemented because they return the value for $access_message I am expecting, but they are interfering with the ability to redirect. Perhaps headers are already sent out?
$accessModel = ClassRegistry::init('Access');
$access_message = $accessModel->field('access_message', array('Access.id' => $required_level));
Please note I have also tried:
$access_message = ClassRegistry::init('Access')->field('access_message', array('Access.id' => $required_level));
And
$this->loadModel('Access');
$access_message = $this->Access->field('access_message', array('Access.id' => $required_level));
Gists:
component gist: https://gist.github.com/970a951715205c222348
controller gist: https://gist.github.com/2b90e5af2518a81672fb
access model gist: https://gist.github.com/bhndbrwneyes/f333a93f0a21302d832f
You may have space before/after php Opening/Closing tags in controller and models. Remove all the closing tags from all controllers and models and any whitespace before opening tags. Then check the result.
Not an answer yet, but at least there are some variables in your code that may not be defined, or errors that can occur:
public function AccessMessage($required_level, $user_level) {
if(!$user_level && $this->_View->viewVars['access']){
$user_level = $this->_View->viewVars['access'];
}
if(!$required_level || !$user_level || $user_level != $required_level){
$access_message = 1;
}
return $access_message;
}
Variable $access_message will only be defined if a user is not allowed to access the page
An error may occur if the 'access' viewVar is not set at all
Change it to this:
public function AccessMessage($required_level, $user_level) {
$access_message = 0;
if(!$user_level && $this->_View->get('access')){
$user_level = $this->_View->get('access');
}
if(!$required_level || !$user_level || $user_level != $required_level){
$access_message = 1;
}
return $access_message;
}
[updated] saw you did have the $access_message defined on your gist (https://gist.github.com/970a951715205c222348)
However:
This will not work
App::uses('Component', 'Controller', 'ClassRegistry', 'Utility');
App::uses() takes two arguments; the 'class' you would like to use and the location it can be found. The line above should be written as:
App::uses('Component', 'Controller/Component');
App::uses('Controller', 'Controller');
App::uses('ClassRegistry', 'Utility');
But I wonder if ClassRegistry needs to be loaded manually
[update 2] You really have a lot 'weird' things going on in your application, so I wonder if we'll be able to sort that out:
public function add($page = null) {
$access = $this->viewVars['access'];
if($this->CustomPage->AccessMessage(4, $access)){
$this->Session->setFlash(__($this->CustomPage->AccessMessage(4, $access)));
$this->redirect(array('action' => 'index', 'page' => $page));
}
// ......
}
Where is 'viewVars['access']' set?
You're passing 'viewVars['access']' as the second parameter ($user_level) to AccessMessage(), but inside AccessMessage() you're trying to use the same viewVar again if the parameter '$user_level' was not set?
$this->CustomPage->AccessMessage() is called twice once to check if it returned anything, then to use it. Not very efficient
.
public function add($page = null) {
// Where does is $this->viewVars['access'] come from? Where is it set?
$access = empty($this->viewVars['access'])? null : $this->viewVars['access'];
$message = $this->CustomPage->AccessMessage(4, $access);
if ($message) {
$this->Session->setFlash(__($message));
$this->redirect(array('action' => 'index', 'page' => $page));
}
// ......
}
On a further note. you're redirecting the user only if a 'message' was found and not empty, NOT based on the current users permissions, you might consider splitting the two;
In your component:
public function HasAccessLevel($required_level, $user_level) {
if(!$user_level || $user_level != $required_level){
return false;
}
return true;
}
public function AccessMessage($required_level) {
return ClassRegistry::init('Access')->field('access_message', array('Access.id' => $required_level));
}
In your controller:
public function add($page = null) {
// Where does is $this->viewVars['access'] come from? Where is it set?
$access = empty($this->viewVars['access'])? null : $this->viewVars['access'];
if($this->CustomPage->HasAccessLevel(4, $access)){
$this->Session->setFlash(__($this->CustomPage->AccessMessage(4)));
$this->redirect(array('action' => 'index', 'page' => $page));
}
// ......
}
Cake 2: At the top of the component: add
public function initialize(Controller $controller) {
$this->Controller = $controller;
}
inside the function you can redirect like so:
$this->Controller->redirect(array('plugin' => false, 'controller' => 'users', 'action' => 'index'));
If the redirect is called, but you are not redirected I guess you have some permission check in your index() action that prevents the access. Can you confirm or post the whole controller code?

SessionComponent::setFlash

I'm using CakePHP 2.
This is my controller.
class GroupsController extends AppController {
public $helper = array('Html', 'Form', 'Session');
public function edit($id = null) {
if (empty($this->request->data)) {
$this->request->data = $this->Group->findByGroupId($id);
} else {
if($this->Group->save($this->request->data)) {
$this->Session.setFlash('Saved!!!');
$this->redirect(array('action' => 'index'));
}
}
}
}
When I pressed the save button on the page groups/edit/1, I got an error.
"Error: Call to undefined function setFlash()"
Fortunately, the changes I made were save to the database, I really don't get it, because setFlash() is a method of SessionComponent.
Please help, thanks.
Kongthap.
try this ::
$this->Session->setFlash('Saved!!!');

Resources