Codeigniter Hidden Form Becomes NULL - php

I've got a really weird issue that I can't seem to figure out or understand. So essentially I have a to grab the ID passed through the Codeigniter URI, have it populate a hidden form, and then submitted. However when I submit the form as hidden, it comes back saying the data is NULL. I have tried and changed it to form_input and it works fine. Can anyone help me or explain to me why this is the case?
I have tried the following solutions.
URL
http://localhost/list/players/add/1/
where I want URI 3 ('1') to pass on to the form and submitted.
Solution 1 - Having the URI pass straight to data array
Controller
function add() {
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$league_id = $this->uri->segment(3);
$data = array(
'leagues_id' => $league_id,
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
Solution 2 - Grabbing the URI and fill a hidden form
Controller
function add() {
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data)){
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open('players/add/');
?>
<?php
echo "<br>";
echo "<br>";
echo "League Name";
echo "<br>";
foreach ($leagues_list->result() as $row) {
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
$data = array( 'name' => 'leagues_id',
'value' => $league_id,
);
echo form_hidden($data);
}
echo "<br>";
echo "<br>";
$data = array( 'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
In both scenarios, on submit it comes back with an error saying leagues_id is NULL. Now I have tried in Solution 2 to change from 'form_hidden' to 'form_input' and straight away clicking submit and it works fine.
Can anyone help me or advise why this is the case?
Many thanks.

If you want to add a parameter to your controller's function, you have to add it to: function func($parameter = 0) (= 0 is optional for default value).
In this case you can access the parameter by $parameter.
In your View file, you can open your form to post to the current url. For this you need to load the url helper in your controller: $this->load->helper('url'); (or you can autoload it in application/autoload.php).
Your form_hidden declaration was bad too. If you want to declare it with array(), then you have to use this syntax:
$data = array(
'name' => 'John Doe',
'email' => 'john#example.com'
);
echo form_hidden($data);
// Would produce:
<input type="hidden" name="name" value="John Doe" />
<input type="hidden" name="email" value="john#example.com" />
More information on Form helper: https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
For the right solution, try this:
Controller
function add($league_id = 0)
{
if($league_id != 0)
{
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
if($this->form_validation->run() == FALSE)
{
$data['view_file'] = 'add';
$this->load->module('template');
$this->template->cmslayout($data);
}
else
{
$data = array(
'leagues_id' => $this->input->post('leagues_id'),
);
if($this->_insert($data))
{
return $query;
}
redirect ('/players/');
}
}
View
<?php
echo form_open(current_url());
echo "<br /><br />";
echo "League Name <br />";
foreach ($leagues_list->result() as $row)
{
$league_id = $row->id;
$league_name = $row->league_name;
echo $league_name;
echo form_hidden('leagues_id', $league_id);
}
echo "<br /><br />";
$data = array(
'value' => 'Set Player',
'name' => 'submit',
'class' => 'submit-btn'
);
echo form_submit($data);
echo form_close();
?>

Related

Can't update my Database using Codeigniter

I've just started to learning about CodeIgniter. But I stuck some point. After 7+ hours work and googling I decided to ask here. I am trying to update the database but I couldn't get out of it. After I enter data my data don't update. Here's my code ;
Takvim_Model.php
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert('takvim', $data)) {
return true;
}
}
public function delete($roll_no) {
if ($this->db->delete('takvim', 'roll_no = '.$roll_no)) {
return true;
}
}
public function update($data,$old_roll_no) {
$this->db->set($data);
$this->db->where('roll_no', $old_roll_no);
$this->db->update('takvim', $data);
}
}
?>
Takvim_View.php
<!DOCTYPE html> <html lang = "en"> <head>
<meta charset = "utf-8">
<title>Takvim Example</title> </head> <body>
Add
<table border = "1">
<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>Name</td>";
echo "<td>Start Time</td>";
echo "<td>Stop Time</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
echo "<tr>";
foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td>".$r->start_time."</td>";
echo "<td>".$r->stop_time."</td>";
echo "<td><a href = '".base_url()."index.php/takvim/update/"
.$r->roll_no."'>Update</a></td>";
echo "<td><a href = '".base_url()."index.php/takvim/delete/"
.$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>
Takvim_Controller.php
<?php
class Takvim_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index() {
$query = $this->db->get("takvim");
$data['records'] = $query->result();
$this->load->helper('url');
$this->load->view('Takvim_view', $data);
}
public function add_event_view() {
$this->load->helper('form');
$this->load->view('Takvim_add');
}
public function add_event() {
$this->load->model('Takvim_model');
$data = array (
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'start_time' => $this->input->post('start_time')
);
$this->Takvim_model->insert($data);
$query = $this->db->get("takvim");
$data['records'] = $query->result();
$this->load->view('Takvim_view',$data);
}
public function update_event_view() {
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("takvim",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data = array('records' => $data['records']);
$this->load->view('Takvim_update',$data);
}
public function update_event(){
$this->load->model('Takvim_Model');
$data = array (
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'start_time' => $this->input->post('start_time'),
'stop_time' => $this->input->post('stop_time')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Takvim_Model->update($data,$old_roll_no);
$query = $this->db->get("takvim");
$data['records'] = $query->result();
$this->load->view('Takvim_view',$data);
}
public function delete_event() {
$this->load->model('Takvim_Model');
$roll_no = $this->uri->segment('3');
$this->Takvim_Model->delete($roll_no);
$query = $this->db->get("takvim");
$data['records'] = $query->result();
$this->load->view('Takvim_view',$data);
}
} ?>
Takvim_Update.php
<!DOCTYPE html><html lang = "en"> <head> <meta charset = "utf-8">
<title>Takvim Example</title> </head> <body>
<form method = "" action = "">
<?php
echo form_open('Takvim_controller/update');
echo form_hidden('old_roll_no',$records[0]->roll_no);
echo form_label('Roll No.');
echo form_input(array('id'=>'roll_no',
'name'=>'roll_no','value'=>$records[0]->roll_no));
echo "
";
echo form_label('Name');
echo form_input(array('id'=>'name','name'=>'name',
'value'=>$records[0]->name));
echo "
";
echo form_label('Start Time');
echo form_input(array('id'=>'name','name'=>'name',
'value'=>$records[0]->start_time));
echo "
";
echo form_label('Stop Time');
echo form_input(array('id'=>'name','name'=>'name',
'value'=>$records[0]->stop_time));
echo "
";
echo form_submit(array('id'=>'submit','value'=>'Edit'));
echo form_close();
?>
</form>
Routes.php
$route['takvim'] = "Takvim_controller";
$route['takvim/add'] = 'Takvim_controller/add_event';
$route['takvim/add_view'] = 'Takvim_controller/add_event_view';
$route['takvim/update/(\d+)'] = 'Takvim_controller/update_event_view/$1';
$route['takvim/delete/(\d+)'] = 'Takvim_controller/delete_event/$1';
The name of model is not recomanded for Codeigniter
When you name a model use _model not _Model (This create conflit in your code)
In Takvim_Update.php you are submitting the form to 'Takvim_controller/update' and I can't see the update method in your Takvim_controller or the Takvim_controller/update route in your routes.php file.
First edit your Routes.php and add new route to your update method in Takvim_controller.
$route['takvim/update'] = 'Takvim_controller/update_event';
Then in Takvim_Update.php file submit your from to takvim/update url.
echo form_open('takvim/update');
try this:i hope it will help.
define routes.
$route['takvim/update/(:any)'] = 'Takvim_controller/update_event_view/$1';
//controller
first get data from table.and then update by whatever paramete's you want to update. for example i am giving primary key id of table.
$data=array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
'start_time' => $this->input->post('start_time'),
'stop_time' => $this->input->post('stop_time')
);
$this->Takvim_Model->update($id);
//model
function update($id){
return $this->db->where('id',$id)->update('table_name',$data);
}

A Php Error was encountred Severity: Warning Message in_array() expect parameter 2 to be array CODEIGNITER

I'm programming with Codeigniter.
I have an error.
A Php Error was encountered Severity: Warning Message in_array() expect parameter 2 to be array
I have compared the code with another that works but I have not found the error.
public function update($post_id)
{
if(!in_array('updatePost', $this->permission)) {
redirect('dashboard', 'refresh');
}
if(!$post_id) {
redirect('dashboard', 'refresh');
}
$data = array(
'name' => $this->input->post('post_name'),
'summary' => $this->input->post('summary'),
'date' => $this->input->post('date'),
'description' => $this->input->post('description'),
'subject_id' => json_encode($this->input->post('subjects')),
'tag_id' => json_encode($this->input->post('tag')),
'category_id' => $this->input->post('categories'),
'availability' => $this->input->post('availability'),
);
if($_FILES['post_image']['size'] > 0) {
$upload_image = $this->upload_image();
$upload_image = array('image' => $upload_image);
$this->model_posts->update($upload_image, $post_id);
}
$update = $this->model_posts->update($data, $post_id);
if($update == true) {
$this->session->set_flashdata('success', 'Successfully updated');
redirect('posts/', 'refresh');
}
else {
$this->session->set_flashdata('errors', 'Error occurred!!');
redirect('posts/update/'.$post_id, 'refresh');
}
}
else {
$this->data['subjects'] = $this->model_subjects->getActiveSubjects();
$this->data['tag'] = $this->model_tag->getActiveTag();
$this->data['categories'] = $this->model_categories->getActiveCategory();
$post_data = $this->model_posts->getPostData($post_id);
$this->data['post_data'] = $post_data;
$this->render_template('posts/edit', $this->data);
}
}
edit //Post form
<div class="form-group">
<label for="tag">Tag</label>
<?php $tag_data = json_decode($post_data['tag_id']); ?>
<select class="form-control select_group" id="tag" name="tag[]" multiple="multiple">
<?php foreach ($tag as $k => $v): ?>
<option value="<?php echo $v['id'] ?>" <?php if(in_array($v['id'], $tag_data)) { echo 'selected="selected"'; } ?>><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
</div>
PHP is telling you exactly what is wrong. In your case, because your second parameter is $tag_data, and $tag_data is the result of json_decode, it's likely that json_decode had a problem trying to decode $post_data['tag_id'].
The PHP documentation for json_decode states:
NULL is returned if the json cannot be decoded or if the encoded data
is deeper than the recursion limit.
See here for details: http://php.net/manual/en/function.json-decode.php
You could do something like this to get around the warning:
if( is_array( $tag_data ) && in_array($v['id'], $tag_data) )
But the bigger question here is why are you doing this? There's probably a better way.
the tag_id in database need to be an actual array in this form ["1","2",..]

Add Variables to an array?

I want to add variables to an array, what I'm trying to do is to check if there is an error from the view within the controller and the variable will be added to an array here is an example.
$error = array ();
if (input1 == null)
{
$errormessage1 = '*';
$error[] = $errormessage1;
}
if (input2 == null)
{
$errormessage2 = '*';
$error[] = $errormessage2;
}
if (input1 != null AND input2 != null)
{
//insert to database or something
}
else
$this->load->view("view", $error);
The problem is that the values are not being inserted to the array. And the array is not printing anything after I return it to the view.php
Here is an example of my view.php
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
if(isset($errormessage1 ))
echo $errormessage1 ;
Thank you for any help that you can give me.
I see you are trying to tell the user that username is required. right? then why don't you utilize Codeigniter form_validation library? to display the errors you use form helper method validation_errors()
Your View
<?php echo validation_errors();
echo form_label('User Name:', 'input1 ' );
$data= array(
'name' => 'input1 ',
'placeholder' => 'Please Enter User Name',
'class' => 'input_box'
);
echo form_input($data);
Your Controller
public function your_method(){
$this->load->library('form_validation');
$this->form_validation->set_rules('input1','Username','required');
//and so on for other user inputs
if($this->form_validation->run()===TRUE){
//send to model may be
}else{
$this->load->view('view');
}
}

Yii radioButtonList: always takes the default value as the selected value

I have Yii radio button list as follows.
forgotpassword1.php
<?php echo $form->radioButtonList($model, 'send_option', $email_exist); ?>
This is the action for forgotpassword1.
public function actionForgotpwd2() {
$model = new User;
$email_exist = array('mobile' => 'Send SMS to Mobile');
$model -> setScenario('forgotpwd2');
$model -> send_option='mobile';
$postvars = array('conn' => Yii::app()->session['mobile']);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'CheckAccount', $postvars);
$out_arr = json_decode($postRes, true);
//print_r($out_arr);
if ($out_arr['success'] == true && $out_arr['email'] == true) {
$email_exist['email'] = 'Send an E-mail';// = array('mobile' => 'Send SMS to Mobile', 'email' => '');
} else if ($out_arr['success'] == false) {
Yii::app()->user->setFlash('error', $out_arr['error']);
$this->redirect(array('forgotpwd1'));
}
if (!empty($_POST['User'])) {
$model->attributes = $_POST['User'];
echo Yii::app()->session['mobile'];
//print_r($_POST);
if(isset($_POST['User']['send_option'])) {
//Yii::app()->session['send_option'] = $model->send_option;
echo Yii::app()->session['send_option'];
$postvars = array('conn' => Yii::app()->session['mobile'], 'send_type' => $model->send_option);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'ChangePassword', $postvars);
$out_arr = json_decode($postRes, true);
// print_r($out_arr);
if ($out_arr['success'] == true) {
$this->redirect(array('forgotpwd3'));
} else {
Yii::app()->user->setFlash('error', $out_arr['error']);
}
}
}
$this->render('forgotpwd2', array(
'model' => $model, 'email_exist' => $email_exist
));
}
Here I call a function named "ChangePassword()" from my backend application. One of the parameters passed to the backend is send_type: mobile or email. The problem is it will always takes mobile as the send_type.
I've used
$model -> send_option='mobile';
to set the default value as mobile.
Why it always takes mobile as the send type.
Any suggestions are appreciated.
Thank you in advance
Try with this :
<?=$form->radioButtonList($model,'send_option',array(1=>'Mobile',2=>'Email'))?>
In your Acion :
To set the default value :
$model -> send_option=1;
To get the checked value (check whether it's 1 or 2) :
$_POST['send_option']

Very Strange Input issue

I have got a very strange input issue in which it seems that my seo description box and main content box are linked due to if I input any data into the seo input box it changes in the database in the content area as well but not the otherway around.
View:
<?php
//Setting form attributes
$formpageEdit = array('id' => 'pageEdit', 'name' => 'pageEdit');
$formInputTitle = array('id' => 'title', 'name' => 'title');
$formSEODescription = array('id' =>'seoDescription', 'name' => 'seoDescription');
$formTextareaContent = array('id' => 'textContent', 'name' => 'textContent');
?>
<?php print_r($page);?>
<div id ="formLayout" class="editPage">
<?php echo form_open('admin/editpage/index/'.$page[0]['id'].'/'.url_title($page[0]['name'],'dash', TRUE),$formpageEdit); ?>
<?php echo form_fieldset(); ?>
<h4>You are editing: <?= $page[0]['name']; ?> </h4>
<section id = "validation"><?php echo validation_errors();?></section>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<label><?php echo form_label ('SEO Description:', 'description');?><span class="small">Required Field</span></label>
<?php echo form_input($formSEODescription, $page[0]['description']); ?>
<label><?php echo form_label ('Content:', 'content');?><span class="small">Required Field</span></label>
<?php echo form_textarea($formTextareaContent, $page[0]['content']); ?>
<script type="text/javascript">CKEDITOR.replace('textContent');</script>
<?php echo form_submit('submit','Submit'); ?>
<?php echo form_fieldset_close();
echo form_close(); ?>
</div>
Model
<?php
/**
* This model handles the sql for the checking of the username in the database
*/
class Page_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function Page_model(){
parent::Model();
}
function getCMSContent($id = NULL) {
$this->db->where('id', $id);
$query = $this->db->get('pages', 1);
if($query->num_rows() > 0) {
$row = $query->result_array();
return $row;
}else{
return FALSE;
}
}
function updatePage($id = NULL, $data = NULL){
#set the $data passed to the function into an array, content being the column name.
$data = array('content' => $data, 'description' => $data);
$this ->db->where('id',$id);
$this->db->update('pages', $data);
return TRUE;
}
}
?>
Controller
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Editpage extends CI_Controller {
function __construct(){
parent::__construct();
}
function index($id){
if(!$this->session->userdata('logged_in'))redirect('admin/home');
if ($this->input->post('submit')){
#The User has submitted updates, lets begin!
#Set The validation Rules
$this->form_validation->set_rules('textContent', 'Content', 'trim|required|xss_clean');
$this->form_validation->set_rules('seoDescription', 'SEO Description', 'trim|required|xss_clean');
#if the form_validation rules fail then load the login page with the errors. Otherwise continue validating the user/pass
if ($this->form_validation->run() == FALSE){
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSCotent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['sales_pages'] = $this->sales_model->getSalesPages();
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}
#Form Validation passed, so lets continue updating.
#lets set some variables.
$content = $this->input->post('textContent', TRUE);
$content = $this->input->post('seoDescription', TRUE);
$this->db->escape($content);
#Now if updatePage fails to update hte database then show "there was a problem", you could echo the db error itself
if($this->page_model->updatePage($id, $content)) {
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSContent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['success'] = TRUE;
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}//END if updatePage
}else{
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
$data['sales_pages'] = $this->sales_model->getSalesPages();
#connect to getCMSCotent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}//END if post submitted
} //END function index()
}
Found it:
$content = $this->input->post('textContent', TRUE);
$content = $this->input->post('seoDescription', TRUE);
[update below]
You are overwriting the $content variable with the content of seoDescription so textContent never reaches your db.
You need to update your updatePage function:
function updatePage($id = NULL, $content = NULL, $description = NULL){
#set the $data passed to the function into an array, content being the column name.
$data = array('content' => $content, 'description' => $description);
$this ->db->where('id',$id);
$this->db->update('pages', $data);
return TRUE;
}
and call it appropriately:
[...]
#Form Validation passed, so lets continue updating.
#lets set some variables.
$content = $this->input->post('textContent', TRUE);
$description = $this->input->post('seoDescription', TRUE);
$this->db->escape($content);
$this->db->escape($description);
#Now if updatePage fails to update hte database then show "there was a problem", you could echo the db error itself
if($this->page_model->updatePage($id, $content, $description)) {
[...]
By the way are you sure you are using db->escape correctly? The way you're calling it will only work if the escape function accepts parameters by reference (e.g. using & in front of the parameter name, and setting this value to the escaped value). I'd expect this code to be the correct version, but I don't know your db class so I may be wrong:
$content = $this->db->escape($this->input->post('textContent', TRUE));
$description = $this->db->escape($this->input->post('seoDescription', TRUE));

Categories