how to save id in controller? - php

I have a action which i am calling it two time
Controller.php
UserController extends Controller {
public actionCopy($id = false){
if($id){
//redireting to a view
}
else{
//rediredtion to a differnet view
}
}
}
I am getting a id first then from first view i am again coming to Copy action with no id so else part is running nw but in this i want to get the $id which i get from first request.
I have tried to define a global variable in controller like
Controller.php
UserController extends Controller {
public $user;
public actionCopy($id= false){
if($id){
$this->user = $id;
//redireting to a view
}
else{
echo $this->user ;// but it has nothing
//rediredtion to a differnet view
}
}
}
and set it like this.
I know that if condition is not executing so $id has no value but i set $this->user first time then why it has no value.
Any help is appreaciated

Just try this,
class UserController extends Controller {
public actionCopy($id = false){
if($id){
//set up a session here
Yii::app()->session['_data_id'] = $id;
//remaining code here
}
else{
$id=isset(Yii::app()->session['_data_id'])?Yii::app()->session['_data_id']:NULL; // the id you want from previous request
if($id!=NULL){
//remaining code
unset(Yii::app()->session['_data_id']); //clear it after use
}
}
}
}

Related

PHP - MVC, is my aproach correct?

So I have Model, View and Controller, my code works but i have no one to educate me if I do work with it properly.
I won't copy paste the whole code, so therefor I've drawed how it works:
THE PICTURE: MVC
The part of code:
class Site {
protected $config;
function __construct() {
$this->config = include("resources/config.php");
}
private function connect() { /*database connection*/ }
public function getData($var) {
/* connecting, $var = amout of rows, and storing the data in array() */
}
}
class SiteView {
private $data;
function __construct(Site $data) {
$this->model = $data;
}
public function output() {
if(!empty($this->model->data)) { /* displays the data */ }
}
public function render($template) {
return include("$template");
}
}
class SiteController {
public function __construct(Site $respond) {
$this->model = $respond;
}
public function condition() {
$view = new SiteView($this->model);
$view->render("header.php");
if(!isset($_GET['action'])) {
$view->render("body.php");
} else if($_GET['action'] === "report" AND isset($_GET['id'])) {
$view->render("report_body.php");
} else if ...
}
So the model and view is used in templates, and I'm not sure if it is a good thing or bad. Thanks for any kind of help or showing me the way.
The MVC or Model, View and Controller approach is Model is for data which used by user, Controller is the backend logic and View is the output in HTML or the User Interface (UI).
Normally every request come to the controller first. Controller is connected with the Model and View. Controller collect the data according to the request from Model and send the data to the View for show. View can not able to connect with model.
For more details see this link, Click Here

How to pass data from controller to models in codeigniter

I passed parameter from view to controller via URL. Now I want to send it from controller to model so that I can use it to pick data from tables. Here is my code:
controller:
function view(){
if(isset($_GET['r'])) {
$rank = $_GET['r'];
}
$rank=$this->uri->segment($rank);
$this->load->model('names_rank');
$data=$this->names_rank->get_names($rank);
print_r($rank);
}
model:
function get_names($rank){
$this->db->select('u.*,v.*');
$this->db->from('unit_member u, Vyeo v');
$this->db->where('v.fno = u.fno');
$this->db->where('u.present = ""');
$this->db->where('v.rank', $rank);
$this->db->where('v.date_of_end="0000-00-00"');
$query = $this->db->get();
return $query->result_array();
}
this is the result:
A PHP Error was encountered Severity: Warning Message: Missing
argument 1 for Names_rank::get_names(), called in
C:\xampp\htdocs\unit\application\controllers\names.php on line 32 and
defined
This will work to send to model but your code isn't understandable for me, you re-declare the variable after setting it in the IF? are you trying to print_r() the output from the model?
I think you are trying to achieve this maybe?
function view() {
if(isset($_GET['r'])) {
$rank = $_GET['r'];
}else{
$rank = $this->uri->segment($rank);
}
$this->load->model('names_rank');
$data = $this->names_rank->get_names($rank);
print_r($data);
}
You can pass a Parameter to your model. First you have to call your model within your controller if you not enable it on autoload.
Your Model:
<?php
class AwesomeModel extends CI_Model
{
publif function do_work($param, $anotherParam)
{
//code here
}
}
Then your controller:
<?php
class AwesomeController extends CI_Controller
{
public function __construct()
{
/*
* load in constructor so not need to recall every time you want use it
* second parameter is model renaming (optional)
*/
$this->load->model('AwesomeModel', 'awe');
}
public function pass_data()
{
$this->awe->do_work($param1, $param2);
}
?>
Thats all.

How to call yii component useridentity class from controller

I am trying to create a simple login using Yii Here is my auth controller
class AuthController extends Controller
{
/**
* Declare class-based actions.
*/
public function actionLogin()
{
$model = new LoginForm;
$post = Yii::app()->request->getPost('LoginForm');
// If form is submitted
if($post) {
$identity = new UserIdentity($post['username'], $post['password']);
echo $identity->testing();
if($identity->authenticate()) {
echo 'yes';
} else {
echo 'no';
}
exit;
}
$this->render('login', array('model' => $model));
}
}
And here is my UserIdentity
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{ echo 'testing';
$user = LoginForm::model()->findByAttributes(array('username' => $this->username));
if(is_null($user)) {
%this->errorCode=self::ERROR_USERNAME_INVALID;
} else if($user->password != $this->password) {
$this->errorCode=self::ERROR_PASSWORD_INVALID;
} else {
$this->_id = $user->id;
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
function getId()
{
return $this->_id;
}
}
I have mentioned echo 'yes' and echo 'no' but both are not displaying. How to correct it
Well first of all, you won't even see those echo statements, the only things that are rendered visually for an end-user to see in Yii are the "views". For my login code, which is just a little bit different from yours, after confirming authentication, my app is redirected to home page. Your custom UserIdentity file looks fine, but again, that echo statement won't even be seen. This UserIdentity file is just for performing custom user authentication behind the scenes.
In my UserController (as opposed to your AuthController), my actionLogin is:
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
$this->render('/user/login',array('model'=>$model));
}
From the above, for example, you could redirect to the previous page you were at or redirect to your main site view at "/site/index" and under that have some code that does some arbitrary functions or print out HTML depending on if you're logged in or not. An overly simple site view example:
<?php
/* #var $this SiteController */
if (Yii::app()->user->isGuest)
{
// Do stuff here if user is guest.
echo 'User is a guest.';
}
else
{
// Do stuff here if user is authenticated.
echo 'User is authenticated.';
}
?>

Give access priviliges in codeigniter

In codeigniter, I have function to restrict controller,
private function controllerAccess(){
$sessionArray = $this->session->userdata('logged_in');
if($sessionArray['type'] == 'ADMIN' || $sessionArray['type'] == 'SUPERVISOR'){
return true;
}
else{
return false;
}
}
I am preventing my index controller by doing this,
public function index(){
$system = new SYSTEM();
$this->controllerAccess() ? $this->dashboard() : $system->container('No Access');
}
The problem is, Do I need to do the same thing with each public method (controller)?
Because, by doing this: I can access child controllers. For example, I can not access index page for agent. but I can access: agent/dashboard, agent/validate, etc...
Is there any method to block entire controller?
Thanks.
I have no clue what you actually mean and I've been using CI for 2 years now. It might be me but.. You might want to use an authex library since you request the userdata in your controller, that's no good in my eyes.
You should be something like
$user = $this->authex->getSession();
And to check if the user is appropriate to view the page you just use this function
private function verifyUser() {
$user = $this->authex->getSession();
if ($user == null)
redirect('hub/notauthorized/', 'refresh');
}
and you call it in every public function where you want to check the user rights like this
$this->verifyUser();
just run the function in the constructor of your controller, and then the function will run everytime your controller is hit
class YourController extends CI_Controller {
public function __construct()
{
parent::__construct();
if(!$this->controllerAccess(){
//you got a false so redirect or whatever you want to do on negative
}
}
private function controllerAccess(){
$sessionArray = $this->session->userdata('logged_in');
if($sessionArray['type'] == 'ADMIN' || $sessionArray['type'] == 'SUPERVISOR'){
return true;
}
else{
return false;
}
}
public function index(){
$system = new SYSTEM();
$this->controllerAccess() ? $this->dashboard() : $system->container('No Access');
}
}

passing data from controller to model in Joomla 2.5

I am developing a joomla 2.5 component where I need to pass data from controller to model. The controller is receiving data from url. I find that controller is getting the value properly. Now I need to move that value to model from controller. From different post I have found a snippet of code for controller like below.
$datevalue = JRequest::getVar('day',$day); //receiving value from view
$item = JRequest::setVar('day',$datevalue); //setting variable
$model =& $this->getModel('WeeklyProgram'); //assign model
$model->setState('dayVar', $item); // assign value for model
The problem is that I don't know how to receive this value 'dayVar' from model. Can anybody help me on this issue? Thanks.
Use following things
In Modal
class CommunityModelCevent extends JCCModel
{
var $membersCount = null;
function getMembersCount($value) {
$this->membersCount = $value // set your value here 15
// Now you can access this variable into model
}
}
In controller
$ceventModel = CFactory::getModel( 'cevent' );
$membersCount = $ceventModel->getMembersCount(15);
You can do like this . First you make get and set function in the model.Second load the model in the controller and simply pass the values to setter function.Example as follows:
updateratings.php---this is my model
class RatingManagerModelUpdateRatings extends JModelLegacy
{
public $data;
public function get_data(){
$data=$this->data;
return $data;
}
public function set_data($data){
$this->data=$data;
}
}
Controller.php
class RatingManagerController extends JControllerLegacy
{
public function save_ratings(){
$tips = JRequest::getVar('tips'); //get data from front end form
$model = $this->getModel('UpdateRatings'); //load UpdateRatings model
$model->set_data($tips); //update setter function of model
$res=$model->get_data(); // retrieve getter function
//print_r($res);
}
}

Categories