Checking if Post author is equal to logged in user - session

A user can post a 'Tutorial', each tutorial is associated with its author via their 'user_id'.
My problem is I want to alter the view if the logged in user is viewing their own post (Tutorial).
CONTROLLER:
public function view($id = null)
{
$tutorial = $this->Tutorials->get($id, [
'contain' => ['Users','Courses', 'TutorialComments.Users']
]);
$tutorialComment = $this->Tutorials->TutorialComments->newEntity();
$this->set(compact('tutorial', 'tutorialComment'));
}
VIEW:
<? if (($tutorial->user->id) === ($this->request->session()->read('Auth.User.id'))): ?>
<p> hello </p>
<? endif; ?>

you should access the logged in the controller through the Auth component and pass the user to the view
controller
$logged_user_id = $this->Auth->user('id');
$this->set(compact('tutorial', 'tutorialComment', 'logged_user_id '));
view
if($tutorial->user->id == $logged_user_id) {
// your code here
}

Related

Get specific row from database with codeigniter

I'm new to this so i have this silly question.I want to make a login form and when the user logs in i want to show all his information in the screen(username attack defence...).The thing is i don't know how to call the specific function i've made because in my controller calls function index() by default and not the function guser().
login view
<h2>Login</h2>
<?php if($error==1){ ?>
<p>Your Username/password did not match </p>
<?php } ?>
<form action="<?=base_url()?>index.php/Users/login" method="post">
<p>Username: <input name="user" type="text" /> </p>
<p>Password: <input name="password" type="password" /> </p>
<p><input type="submit" value="Login" /></p>
</form>
users controller
<?php
class Users Extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('User');
}
function index(){
$data['users']=$this->User->get_users();//sto model post tha kalesei tin sinartisi get_posts
$this->load->view('Post_index',$data);
}
function guser($id){
$data['user']=$this->User->get_user($id);
$this->load->view('Post_index',$data);
}
function login(){
$data['error'] = 0; // simenei oti den exei errors
if($_POST){
$user=$this->input->post('user',true);//pairnei to username p edose o xristis(einai idio me to $_POST)
$password=$this->input->post('password',true);//pairnei to password p edose o xristis
//$type=$this->input->post('charact',true);
$user1=$this->User->login($user,$password);//,$type);
if(!$user1){
$data['error']=1;
}else{
$this->session->set_userdata('id',$user1['id']);
$this->session->set_userdata('user',$user1['user']);
$this->session->set_userdata('name',$user1['name']);
$this->session->set_userdata('money',$user1['money']);
$this->session->set_userdata('attack',$user1['attack']);
$this->session->set_userdata('defence',$user1['defence']);
$this->session->set_userdata('level',$user1['level']);
$this->session->set_userdata('xp',$user1['xp']);
redirect(base_url().'index.php/Users');
}
}
$this->load->view('Login',$data);
}
function registerSam(){
if($_POST){
$data=array(
'user'=>$_POST['user'],
'name'=>$_POST['name'],
'password'=>$_POST['password'],
'charact'=>"Samurai",
'money'=>400,
'attack'=>10,
'defence'=>5,
'level'=>0,
'xp'=>0
);
$userid=$this->User->create_user($data);
}
}
function registerKnight(){
if($_POST){
$data=array(
'user'=>$_POST['user'],
'name'=>$_POST['name'],
'password'=>$_POST['password'],
'charact'=>"Knight",
'money'=>400,
'attack'=>5,
'defence'=>10,
'level'=>0,
'xp'=>0
);
$userid=$this->User->create_user($data);
}
}
}
?>
user model
<?php
class User Extends CI_Model{
function create_user($data){
$this->db->insert('unityusers',$data);
}
function login($user,$password){
$where=array(
'user'=>$user,
'password'=>$password,
);
$this->db->select()->from('unityusers')->where($where);
$query=$this->db->get();
return $query->first_row('array');
}
function get_user($id){
$this->db->select()->from('unityusers')->where(array('id'=>$id));
$query=$this->db->get();
return $query->first_row('array');
}
function get_users($num=20,$start=0){// tha paroume 20 posts k tha arxisoume apo to proto
$this->db->select()->from('unityusers')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
}
?>
Although you have accepted the answer I like to point out some basic functionality for you to more improved code.
Different technique to load the data to view from controller:
function index(){
$users = $this->User->get_users();
$this->load->view('Post_index',['users' => $users, 'any_other_data' => $any_other_data ... and so on]);
}
When you get post data in the controller then you should check for a validation first inside your login function. And in login functionality it will be more useful. setting-validation-rules
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
Loading a model and it's function. You don't need to use uppercase in this as give below.
$this->load->model('user');
$this->user->get_users();
Your registration Function registerSam you don't need to create an array of post data Codeigniter will provide the functionality to get all your post data at once. To remove unnecessary data from that array use unset.
$your_post_array = $this->input->post();
To call a specific function made, you can access it via a browser using the link
BASE_URL/index.php/ControllerName/MethodName
So, in your case to call the guser method, the url would be
BASE_URL/index.php/users/guser
Hope that helps.
You have an error in guser function on the controller. You don't need to passs any argument to the function. You can get ID of user from the session, which was actually added in session once the user has entered correct credentials.
Also after login, you need to redirect user to guser function instead of users. Because as per your controller users function dosen't exist.
Change From
redirect(base_url().'index.php/Users');
To
redirect(base_url().'index.php/guser');
Please check below for solution.
function guser(){
$data['user']=$this->User->get_user($this->session->userdata('id'));
$this->load->view('Post_index',$data);
}
Let me know if it not works.

after login display client first name in the top of my header page in codeigniter

i have registration page after user register goes to login page,i want to display a user first name in the top pf my header page when we click username i want a dropdown logout after click on logout user shuold be logout..
here is my controller code:
public function login()
{
$data['error'] ="Invalid Login";
$this->load->view('auth/header');
if($this->input->post())
{
$user = $this->UserModel->login($this->input->post());
if(count($user)>0)
{
$array = array(
'client_id' => $user['client_id'],
'first_name' => $user['first_name'],
'client_type_id'=>$user['client_type_id'],
'email' => $user['email'],
'password' => $user['password'],
);
$this->session->set_userdata('userdata',$array);
if($user['client_id'] == $user['client_id'])
{
redirect(base_url('dashboard/dashboard'));
}
}
else
{
$data["error_message"]="Invalid User Name and Password combination";
}
logout
function logout()
{
$this->session->unset_userdata(userdata);
$this->session->sess_destroy();
redirect('Auth/login','refresh');
}
view:
<a href="javascript:;" data-toggle="dropdown" class="right_color">
<?php
echo $this->session->userdata('userdata');
?>
<!-- <img src="<?php echo base_url();?>images/admin.jpg" alt="admin-pic">-->
</a>
Logout
Your current session is in a nested array format
array(userdata=>array(your session))
in your controller replace your session set code
to this
$this->session->set_userdata($array);
and in your view
echo $this->session->userdata('first_name');
You are setting array of data in session. You are trying to print array of data. It will throw array to string conversion error. Change this following and try :-
For creating session:-
$this->session->set_userdata($array);
Now you print:-
<?php
echo $this->session->userdata('client_id');
echo $this->session->userdata('first_name');
echo $this->session->userdata('email');
?>
For more about Session refer this link https://www.codeigniter.com/user_guide/libraries/sessions.html

Yii Framework: validate checkbox on view page

I'm new to the Yii Framework. Currently, I'm having a project which require me to use Yii framework. I would like to ask, is it possible for me to validate an attribute which is not save inside the database?
case:
I have a checkbox which require the user to tick on it in order to move to the next page. If the user doesn't tick on it, then it will prompt an error. How to I validate it in Yii format?
Can someone teach me how to change the validation below to fit Yii Format? where should the validation locate?
content in model.php
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
content in view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<p class="cb_pdpa" style="font-weight:bold"><?php echo $form->checkbox($data,'pdpa_agree'); ?> I have read and understood the above policies and hereby give consent for CTES to use my <pd>*personal data</pd> in accordance to the policies listed out above.</p>
<div class="form-actions">
<?php
/*$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'submit',
'type' => 'primary',
'label'=>$model->isNewRecord ? 'PolicyAgreement' : 'Continue Registration',
));*/
?>
<input type="button" name="submit" value="Continue Registration" onclick="validateAgreement()">
</div>
<?php $this->endWidget(); ?>
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
How to turn to validation below to fit Yii Format?
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
Yeah you can validate
Model.php
Delclare the variable you want to use
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
public function attributeLabels()
{
return array(
'pdpa_agree' => 'I have read and understood the above policies and hereby give consent for CTES to use my *personal data in accordance to the policies listed out above',
);
}
MyController.php
public function actionRegistration(){
$model = new Model();
if(isset($_POST['Model'])){
//Stuff to save Goes here
}
$this->render('registration');
}
view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<div class="form-actions">
$form->checkBox($model,'checkBox');
$form->labelEx($model,'checkBox');
$form->error($model,'checkBox');
</div>
<?php $this->endWidget(); ?>

Yii ClinkPager doesn't work on Ajax Request

Firstly, when the page gets loaded, ClinkPager works properly with all the paging correctly displayed.
But when Ajax Request is sent, the results get populated correctly with all the paging.
But clicking on the next or another page in the Paging, the previous data gets loaded and also paging shows different sequence.
/*Controller action to fetch the records and apply the pagination*/
//---------------------------------------------------------------
public function actionGetUser($user_id=null)
{
$user_domain= (isset($_POST['user_domain'])?$_POST['user_domain']: null);
$model=new UserSearch();
$criteria=new CDbCriteria();
//If Category/Title are also specified for search, then its an Ajax request.
if((isset($_POST['ajax_search'])) && ($_POST['ajax_search']==1))
{
//Change the search criteria accordingly
$criteria->select="*";
if($user_domain!= null)
{
//Adding criteria to search for ideas of specific domain
$criteria->addCondition("user_domain=".$usr_domain);
}
}
//Retrieve the users.
$searchData = $model->search();
//Count the no. of results retrieved.
$count=UserSearch::model()->count($criteria);
//Enable pagination
$pages=new CPagination($count);
$searchData->setPagination($pages);
$pages->applyLimit($criteria);
//Search for ideas satisfying that criteria
$models=userSearch::model()->findAll($criteria);
if((isset($_POST['ajax_search'])) && ($_POST['ajax_search']==1))
{
//Rendering the respective page
$this->renderPartial('renderOnAjax', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
));
}
else
{
//Rendering the respective page
$this->render('render', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
));
}
}
//------------------------------------------------------------
/*render page*/
//------------------------------------------------------------
<div>
<div class="userInfo" id="user_search_result">
<?php $this->renderPartial("renderOnAjax",array('user'=>$user, 'pages'=>$pages));?>
</div>
</div>
//------------------------------------------------------------
/*renderOnAjax Page*/
//------------------------------------------------------------
<?php
$i=0;
$count=count($user);?>
<?php while($i!=$count) {?>
<?php $row=$count[$i];?>
<div class="Box">
/*Some contain to display...*/
</div>
<?php $i++;?>
<?php } ?>
<div class="row">
<?php $this->widget('CLinkPager', array(
'pages' => $pages
));
?>
</div>
//---------------------------------------------------------
try
<?php $this->renderPartial("renderOnAjax",array('user'=>$user, 'pages'=>$pages),false,true);?>
Here is official documentioan for renderPartial
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
$view=string name of the view to be rendered. See getViewFile for details about how the view script is resolved.
$data=array data to be extracted into PHP variables and made available to the view script
$return=boolean whether the rendering result should be returned instead of being displayed to end users
$processOutput=boolean whether the rendering result should be postprocessed using processOutput.
{return} string the rendering result. Null if the rendering result is not required.
EDIT:
The above scheme works for ajax call renderPArtials. You should try this where you are rendering ajax request in controller action like
$this->renderPartial('renderOnAjax', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
),false,true);

KO3 - Kohana 3 - How can I pass $_POST data from a controller/action back to the view/form that called it?

I am trying to validate a form submission in Kohana 3. I have the form::open point to my action_create in my controller which successfully validates the data posted to it from the form in my view. If the data passes validation, a new item is created as intended, and the user is redirected to the item that was just created. This works correctly. If the data fails validation, however, I would like the user to be directed back to the originating view/page while retaining a variable containing the data that was posted so that I can repopulate the form and display errors.
In short, how can I pass data from a view -> controller -> original view?
Thank you, everyone!
The user also posed this question on the Kohana forums.
Those seeking an answer to this should have look over there.
I assume you're using Controller_Template.
File views/form.php:
// Set default variables if variables not passed to this view
$username = isset($username) ? $username : '';
echo Form::open('login');
// Input: username
echo Form::label('username', 'Username');
echo Form::input('username', $username);
echo isset($errors['username']) ? $errors['username'] : '';
// Input: username
echo Form::label('password', 'Password');
echo Form::input('password', $password);
echo isset($errors['password']) ? $errors['password'] : '';
echo Form::close();
File views/template.php
<html>
<head><title>My Website</title></head>
<body>
<?php echo isset($content) ? $content : ''; ?>
</body>
</html>
File classes/controller/user.php
Class Controller_User extends Controller_Template {
public $template = 'template';
public function index()
{
$this->template->content = $this->display_form('form');
}
public function login()
{
// Setup validation & rules here
// Check validation, assume $validation is Validation object
if ($validation->check()
{
// Validation succeeded. Do anything you want here
}
else
{
// Validation failed. Display form with entered values
$form_vars = $_POST;
$form_vars['errors'] = $validation->errors();
// Display form
$this->template->content = $this->display_form('form', $form_vars);
}
}
// Displaying form
private function display_form($form_file, $form_vars=NULL)
{
$form = View::factory($form_file);
if ($form_vars != NULL)
{
foreach($form_vars as $key => $value)
{
$form->$key = $value;
}
}
return $form;
}
}
Hope that helps!

Resources