Using flashdata while posting same controller twice in Codeigniter - php

I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks

save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata

Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.

Related

Form doesn't validate after submitting in moodle

I am trying to create a form whose structure depends on the parameter in the url. If no parameter is specified in the url, an error message should be displayed. Depending on the id, a database query is performed and the form is filled with data.
example url: http://127.0.0.1/local/group/signin.php?groupid=14
Unfortunately, my form doesn't validate after I submit the form via pressing the action button. It jumps to http://127.0.0.1/local/group/signin.php and because there is no parameter present in the url the error message 'No group found' is displayed.
What have I done wrong here?
signinform.php:
class signinform extends moodleform {
public function definition() {
global $DB;
global $USER;
$mform = $this->_form;
$urlid = $this->_customdata['id']; // get the passed group id
$message = 'No group found';
if(is_null($urlid)){
$mform->addElement('html', '<h3>'.\core\notification::error($message).'</h3>');
}
else{
// build the form, sql query etc.
$this->add_action_buttons(true, 'Submit');
}
}
function validation($data, $files) {
return array();
}
}
signin.php:
$PAGE->set_url(new moodle_url('/local/schedule/signin.php?'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_pagelayout('base');
$PAGE->set_title("Sign up");
$PAGE->set_heading("Sign up for a group");
global $DB;
global $USER;
$urlid = $_GET["id"];
$to_form = array('id' => $urlid); // pass group id to form
$mform = new signinform(null, $to_form);
$homeurl = new moodle_url('/');
if ($mform->is_cancelled()) {
redirect($homeurl, 'Cancelled.'); // Just for testing, never enters here
} else if ($fromform = $mform->get_data()) {
redirect($homeurl, 'Validation in process'); // Just for testing, never enters here
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();
You need to add a hidden field to the form that contains the 'id' that has to be passed to the page, otherwise, when the form is submitted, that id will no longer be present in the params for that page.
e.g. (in definition())
$mform->addElement('hidden', 'id', $urlid);
$mform->setType('id', PARAM_INT);
Also, in Moodle, you should never access $_GET directly - use the wrapper functions required_param() or optional_param(), as these:
Clean the parameter to the declared type
Automatically take parameters from either $_GET or $_POST (which will be important in this case, as the 'id' param will be part of the POST data, when you submit the form)
Handle missing parameters by either applying a default (optional_param) or stopping with an error message (required_param)
So your access to $_GET['id'], should be replaced with:
$urlid = optional_param('id', null, PARAM_INT);

Puzzle with PHP using codeigniter

I have a problem using codeigniter, now I have a system that show you a question in a page called start, the question comes random from the database using this code.
$data['question'] = $this->Setting->Loop('challenges_questions', 'ORDER BY RAND() LIMIT 1');
then check the form_validation
if($this->form_validation->run() === TRUE){
foreach($data['question']->result() as $ques){
$query = $this->Challenges_Model->addAnswer($ques->the_answer);
}
}
this is the model
public function addAnswer($answer){
if($this->input->post('answer') == $answer){
if(!$this->session->userdata('is_stopped')){
$this->db->query("UPDATE challenges_scores SET points = points+1 WHERE user_id = ".$this->session->userdata('id').";");
//$this->db->set('points' , 'points+1');
//$this->db->where('user_id', $this->session->userdata('id'));
//$this->db->update('challenges_scores');
}else{
// unSet
$this->session->unset_userdata('is_stopped');
}
return TRUE;
}else{
return FALSE;
}
}
now my problem is when the user post the input (the answer), the query is refreshed, then the answer is changed then the form input answer is wrong.
is there any way to save data to use it after the post ?
The logic is the same as an update form:
Model:
function get() {
return $this->db->get('sometable')->result();
}
Controller:
function index() {
$data['result'] = $this->sommodel->get();
$this->load->view('someview', $data);
}
Here we get the post value if there is any (in case of bad form validation submit) and if not we have the value from the db
<input name="somefield" value="<?php isset($_POST['somefield']) { echo $_POST['somefield'] } else { echo $result->somefield; } ?>">
If it's just one thing just store it in a session variable and do the same logic by instead of $result->somefield you put $this->session->somefield. I wouldn't recommend this approach if it's alot of data.

NULL Value inserted in Database (Codeigniter)

I Am trying to insert data in DB,But somehow NULL is inserted in DB
Here Is My Controller
foreach($this->input->post('resume_id') as $key =>$value ){
$ResumeInsert[$key]['resume_keyid'] = $Resume['resume_id'][$key];
$ResumeInsert[$key]['employer_name'] = $Resume['employer_name'][$key];
$ResumeInsert[$key]['start_Date'] = $Resume['start_Date'][$key];
$ResumeInsert[$key]['end_date'] = $Resume['end_date'][$key];
$ResumeInsert[$key]['type_id'] = $Resume['type_id'][$key];
$ResumeInsert[$key]['position'] = $Resume['position'][$key];
$ResumeInsert[$key]['responsibility'] = $Resume['responsibility'][$key];
$ResumeInsert[$key]['Skills'] = $Resume['Skills'][$key];
if(isset($Resume['id'][$key]) ){
$Key_Resume__ExistIDs[]=$Resume['id'][$key];
$ResumeUpdate[$key]=$ResumeInsert[$key];
$ResumeUpdate[$key]['resume_id']=$Resume['id'][$key];
unset($ResumeInsert[$key]);
}
else{
$ResumeInsert[$key]['resume_id'] = $GetLastID;
print_r ($ResumeInsert[$key]);exit;
$GetLastID++;
}
}
$idsToDelete='';
if(empty($ResumeInsert) && empty($ResumeUpdate)){
$idsToDelete=array_diff($Key_Resume_IDs,$Key_Resume__ExistIDs);
}
$status=$this->Resume_model->ProcessData($idsToDelete,$ResumeUpdate,$user_id,$ResumeInsert,$imgInsert,$imgUpdate);
redirect('Resume','refresh');
Here Is My Code Of Model
function ProcessData($idsToDelete,$tbl_resumeUpdate,$user_id,$tbl_resumeInsert,$imgInsert,$imgUpdate){
$this->db->trans_start();
if(!empty($idsToDelete)){
$this->delete_tbl_resume($idsToDelete);
}
if(!empty($tbl_resumeUpdate)){
//echo "up";exit;
$this->update_tbl_resume($tbl_resumeUpdate);
}
if(!empty($tbl_resumeInsert)){
//echo "int";exit;
$this->insert_tbl_resume($user_id,$tbl_resumeInsert);
}
if(!empty($imgInsert)){
$this->insert_tbl_file_paths($imgInsert);
}
if(!empty($imgUpdate)){
$this->update_tbl_file_paths($imgUpdate);
}
return $this->db->trans_complete();
}
This is Insert Query
function insert_tbl_resume($id,$arrtbl_resume){
$this->db->insert_batch('tbl_resume', $arrtbl_resume);
}
In Above Code,Null Value inserted In DB.
when i Print above query,it displays blank
Any Help Please?
You should use form_validation library. I'm giving you an example, you can edit and use it.
In autoload.php, edit $autoload['libraries'] = array(); line to:
$autoload['libraries'] = array('form_validation');
Then, use form_validation in your controller file. For example:
$this->form_validation->set_rules('resume_keyid', 'Resume ID', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index() // if there is an error, user will redirect to this function
}
else
{
$this->Resume_model->ProcessData();
}
Also please use $this->input->post('resume_keyid', TRUE); structure in your model. "TRUE" means "open XSS filter". Because in CI 3, it comes off as default. If you don't want it, just remove. If you use CI 2, you don't need to add "TRUE".
A few suggestions:
1 - Don't use camelization when you name functions. For example; use process_data() instead of processData()
2 - Check CI Form Validation Document for all details (E.g. all references)
3 - I think you can use $this->db->insert();, just create an array and POST it. If you make it, you'll understand what's wrong.

Unable to get session contents in second function

I am having some issues with sessions.
In the first function queue, I save the session entries I can print this out from this function, so I can see its being set correctly.
In the function remove, I try and save this entries session into a variable and I get the error that entries is an undefined index.
Does anyone have any ideas what I am doing wrong here?
function queue()
{
session_start();
$status = 'Awaiting Moderation';
$channel = '1';
// Find all entries in 'Gallery' channel with 'Awaiting Moderation' status
$this->EE->db->select('entry_id')
->from('exp_channel_titles')
->where('status', $status)
->where('channel_id', $channel);
$query = $this->EE->db->get();
$entries = $query->result_array();
$entries_count = count($entries);
// Set count
$_SESSION['entries_count'] = $entries_count;
// If entries found
if ($entries_count > 0)
{
// Flatten entry ids array
$entriesFlat = array();
array_walk_recursive($entries, function($a) use (&$entriesFlat) { $entriesFlat[] = $a; });
$entriesSerial = serialize($entriesFlat);
// Save in session
$_SESSION['entries'] = $entriesSerial;
}
}
function remove()
{
session_start();
// Get session data + save into variable
$entries = $_SESSION['entries'];
}
You can only have one session and it should be at the top of your file.
Since your using codeigniter why not use codeigniter session and then autoload library and then you can do code like below.
$this->session->set_userdata('entries_count', $entries_count);
To Get Data
$this->session->userdata('entries_count');
And
$this->session->set_userdata('entries', $entriesSerial);
To Get Data
$this->session->userdata('entries');
// Example
if ($this->session->userdata('entries') > 0)
{
User Guide
CI2 http://www.codeigniter.com/userguide2/libraries/sessions.html
CI3: http://www.codeigniter.com/user_guide/libraries/sessions.html
http://www.codeigniter.com/docs
1st of all, there's not need to declare 'session' again at 'remove()' function..
2ndly to set session contents you have to write :
$this->session->set_userdata('entries_count', $entries_count);
Instead of
$_SESSION['entries'] = $entriesSerial;
Save it in session
To get session contents you've to write:
$entries_count = $this->session->userdata('entries_count');
Get session data + save into variable
Then you can write the condition like:
if ($entries_count > 0) {
}
Similarly, you've to write
$this->session->set_userdata('entries', $entriesSerial);
To save in session instead of
$_SESSION['entries'] = $entriesSerial;
And
$entries = $this->session->userdata('entries');
To Get session data + save into variable

cakephp can't update table with set

I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?
Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}
Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);
The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).

Categories