I want to know how I go about selecting a voter in the database table and edit the information with a form in Codeigniter. I already created a search table for it and will post the code below.
Model:
public function search_voters($search_term){
$this->db->select('*');
$this->db->from('voterinfo');
$this->db->like('firstName', $search_term['firstName']);
$this->db->like('lastName', $search_term['lastName']);
$this->db->like('street', $search_term['street']);
$this->db->like('dob', $search_term['dob']);
$query = $this->db->get();
return $query->result_array();
}
Controller:
public function search(){
$this->load->model('reg_model');
$search_term = array(
'firstName' => $this->input->post('firstName'),
'lastName' => $this->input->post('lastName'),
'street' => $this->input->post('street'),
'dob' => $this->input->post('dob')
);
$data['query'] = $this->reg_model->search_voters($search_term);
$this->load->view("reg_header");
$this->load->view("reg_nav");
$this->load->view("reg_search", $data);
}
View:
echo form_open("reg/search");
echo form_label("First Name: ", "firstName");
$data = array(
"name" => "firstName",
"id" => "firstName",
"value" => set_value("firstName")
);
echo form_input($data);
//last name
echo form_label("Last Name: ", "lastName");
$data = array(
"name" => "lastName",
"id" => "lastName",
"value" => set_value("lastName")
);
echo form_input($data);
echo form_label("Street: ", "street");
$data = array(
"name" => "street",
"id" => "street",
"value" => set_value("street")
);
echo form_input($data);
echo form_label("Date of Birth: ", "dob");
$data = array(
"name" => "dob",
"id" => "dob",
"value" => set_value("dob")
);
echo form_input($data);
echo form_submit("searchSubmit", "Search");
echo form_close();
$this->table->set_heading(array('', 'Voter Number', 'First Name', 'Last Name',
'mid Initial', 'Home Number', 'Street',
'Apt', 'Zip', 'DOB',
'Local District', 'State District'));
foreach ($query as $row){
$this->table->add_row($row);
}
echo $this->table->generate();
Update
I've been working on this and came up with something but I am still having issues
Updated View:
foreach ($query as $row){
$this->table->add_row(anchor('reg/view_form/' , $row, 'title="VoterNum"'), $row);
}
echo $this->table->generate();
You shuold probably see jquery and ajax. If certain row from search results is clicked, get a new table with ajax and update the table with new data. ajax will pass your new edited information to controller and in controller, use $htis->input->is_ajax_request() test to get the data from ajax, and update the result to database from your model.
Lets say you have the following.
So using the controller function like so you would.
class Whatever extends CI_Controller {
function whatever() {
// use whatever code to update data
}
}
Related
i want to insert records of fifty persons to the database at one time(this can be increase).when user click the save button data should be save at the database.what is the best way to do it?
Here is my controller
function month_end_data()
{
$data_save = array(
'employee_id' => $emp,
"annual" => $annual,
"casual" => $casual
);
$id = $this->monthend_mod->savemonthenddata($data_save);
echo json_encode(array("status" => TRUE, "id" => $id));
}
Model
class monthend_mod extends CI_Model
{
public function savemonthenddata($data_save = array())
{
if ($this->db->insert_batch('pay_monthend', $data_save)) {
return true;
} else {
return false;
}
}
}
view
<button onclick="month_end_data()" class="btn btn-danger">Save</button>
Try to send in a multidimensional array:
$data = array(
array(
'employee_id' => 'xx',
//... more fields
),
array(
'employee_id' => 'yy',
//... more fields
),
array(
//... and so on
),
);
...and then send that to your savemonthenddata()-method.
I'am trying to implement a dropdownlist inside the gridview, but it is not working.
Here's my code
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->roadies_search(),
'filter' =>$model,
'columns'=>array(
array(
'name'=>'hname_search',
'header'=>'Hospital Name',
'value'=>'($data->AssociatedHospitals) ? $data->AssociatedHospitals : ""',
),
array(
'type'=>'raw',
'header'=>'Users',
'id' => 'test',
'value'=>function(){
$res=Yii::app()->db->createCommand("SELECT name,id FROM med_user WHERE rank>3")->queryAll();
$html = '<select name="user" style="width:100%;">
<option selected>Select User</option>
';
foreach ($res as $key) {
$html.='<option value="'.$key['id'].'">'.$key['name'].'</option>
';
}
$html.='</select>';
return $html;
},
),
)
));
I have tried it using the following function too:
public function getUsername(){
$res=Yii::app()->db->createCommand("SELECT name,id FROM med_user WHERE rank>3")->queryAll();
return CHtml::dropDownList('usersselectlist'.$this->id,'user_id',CHtml::listData($res, 'id', 'name'));
}
I want to show all the users as a dropdown, for every row in the gridview.
EDIT
I figured out that the dropdown works fine for firefox, but the problem is with chrome. It is not showing the selected values.
Here's an example
Chrome: http://i.imgur.com/eAvBRwO.png
Firefox: http://i.imgur.com/7wBc1GX.png
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->roadies_search(),
'filter' =>$model,
'columns'=>array(
array(
'name'=>'hname_search',
'header'=>'Hospital Name',
'value'=>'($data->AssociatedHospitals) ? $data->AssociatedHospitals : ""',
),
array(
'type'=>'raw',
'header'=>'Users',
'id' => 'test',
'value'=>function(){
// but better prepare data in model and set here from controller
$dataReader = Yii::app()
->db
->createCommand("SELECT name,id FROM med_user WHERE rank>3")
->query();
$dropList = array();
foreach ($dataReader as $row) {
$id = $row['id'];
$dropList[$id] = $row['name'];
}
return CHtml::dropDownList('my', null/* or selected id */, $dropList);
},
),
)
));
It's really bad way. You will do SQL query for each row, why not use it outside of grid?
$res=Yii::app()->db->createCommand("SELECT name,id FROM med_user WHERE rank>3")->queryAll();
$select_data = CHtml::listData($res, 'id', 'name');
......
array(
'type'=>'raw',
'header'=>'Users',
'id' => 'test',
'value'=>function($data) use ($select_data){
return CHtml::dropDownList('usersselectlist'.$data->id','',$select_data);
},
),
.......
Something like this should work.
I'm a bit confused about this error when I am updating the data. Can anyone help me with this? My codes are the following:
Controller:
public function show_student($id)
{
$data['single_student'] = $this->student_view_model->get_student_id($id);
$this->load->view('view_student_update', $data);
}
public function student_update_info($id, $data)
{
$data = array(
'student_fname' => $this->input->post('first'),
'student_lname' => $this->input->post('last'),
'student_gender' => $this->input->post('gender'),
'student_course' => $this->input->post('course'),
'student_company' => $this->input->post('company')
);
$data['results'] = $this->student_view_model->update_student($this->input->post('hid'), $data);
$this->load->view('view_student_list', $data);
}
Model:
public function get_student_id($id)
{
$query = $this->db->get_where('tbl_student', array('student_id' => $id));
return $query->row_array();
}
public function update_student($id, $data)
{
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
return $this->get_student_id($id);
}
My View ( edit page )
<?php echo form_open('student_update/student_update_info');
$data = array(
'id' => 'input',
'name' => 'hid',
'value' => $single_student['student_id']
);
echo form_hidden($data);
echo form_label('First Name: ', 'first');
$data = array(
'id' => 'input',
'name' => 'first',
'placeholder' => 'Enter First Name',
'value' => $single_student['student_fname']
);
echo form_input($data);
echo form_label('Last Name: ', 'last');
$data = array(
'id' => 'input',
'name' => 'last',
'placeholder' => 'Enter Last Name',
'value' => $single_student['student_lname']
);
echo form_input($data);
echo form_label('Male ', 'gender');
$data = array(
'id' => 'radio',
'name' => 'gender',
'checked' => 'checked',
'value' => $single_student['student_gender']
);
echo form_radio($data);
echo form_label('Female ', 'gender');
$data = array(
'id' => 'radio',
'name' => 'gender',
'value' => $single_student['student_gender']
);
echo form_radio($data);
echo "<br />";
echo form_label('Course', 'course');
$data = array(
'id' => 'input',
'name' => 'course',
'placeholder' => 'Enter Student Course',
'value' => $single_student['student_course']
);
echo form_input($data);
echo form_label('Company', 'company');
$data = array(
'id' => 'input',
'name' => 'company',
'placeholder' => 'Enter Company Name',
'value' => $single_student['student_company']
);
echo form_input($data);
$data = array(
'id' => 'update',
'name' => 'update',
'value' => 'Update'
);
echo form_submit($data);
echo form_close(); ?>
My View ( list of data )
<?php foreach ($results as $row) { ?>
<tr>
<td><?php echo $row->student_fname . " " . $row- >student_lname; ?></td>
<td><?php echo $row->student_course; ?></td>
<td><?php echo $row->student_company; ?></td>
<td>delete
update
</td>
</tr>
<?php } ?>
And this error occurs
error message
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/view_student_list.php
Line Number: 27
Can anyone help me solve this problem?
Please check if any value is present in your variable $results This error comes only when there is no value in the variable with foreach loop.
To avoid these situations always use :
<?php if($results && !empty($results)){ foreach ($results as $row) { ?>
<tr>
<td><?php echo $row->student_fname . " " . $row- >student_lname; ?></td>
<td><?php echo $row->student_course; ?></td>
<td><?php echo $row->student_company; ?></td>
<td>delete
update
</td>
</tr>
<?php } } ?>
Also your result variable will not contain any data to loop since your method update_students does not returns anything.
The main reason you are not getting any results back from your update method is because you are not returning anything.
Secondly, I would change your get_student_id() method as it doesn't quite fit with MVC principals. It works for this particular task, however, you should really be getting the uri value in the controller and then passing it through to your model:
Controller method:
public function show_student($id)
{
$data['single_student'] = $this->student_view_model->get_student_id($id);
$this->load->view('view_student_update', $data);
}
Assuming that "show_student" would be the 2nd uri segment you can do the above.
Model method:
public function get_student_id($id)
{
$query = $this->db->get_where('tbl_student', array('student_id' => $id));
return $query->row_array();
}
This way you can get the row for the student without depending on the student_id always being the 3rd uri segment.
So, with you're results method, you could:
Controller Meothod
public function update_student()
{
$data = array(
'student_fname' => $this->input->post('first'),
'student_lname' => $this->input->post('last'),
'student_gender' => $this->input->post('gender'),
'student_course' => $this->input->post('course'),
'student_company' => $this->input->post('company')
);
$data['results'] = $this->student_view_model->update_student($this->input->post('hid'), $data);
$this->load->view('view_student_list', $data);
}
Model Method:
public function update_student($id, $data)
{
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
return $this->get_student_id($id);
}
Again, with models you should always pass data to them (for quite a few reasons)!
Lastly, I would also think about change the name of get_student_id() to something like get_student_by_id or get_student as get_student_id() suggests t me that you are just going to be getting the id. Also, you really should look at using the Form Validation in codeigniter as your code is very, Very vulnerable at the minute.
Hope this helps!
Hello i created a separate search form having input box and button.
in my model i want to search products by category wise...
but problem is that when input box is empty and clicking on search buttons it displays all entries from the database table..
controller code is-
class AddController extends Controller
{
public function actionAddsearch()
{
$model_form = new Add("search");
$attributes = Yii::app()->getRequest()->getPost("Add");
if(!is_null($attributes))
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
}
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
}
model code--
class Add extends CActiveRecord
{
public function searchAdd()
{
$criteria = new CDbCriteria();
$criteria->compare("addname", $this->category, TRUE, "OR");
$criteria->compare("category", $this->category, TRUE, "OR");
return Add::model()->findAll($criteria);
}
view code- addsearch.php
<div class="search-bar">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
"action"=>$this->createUrl("add/addsearch"),
'type'=>'search',
)
);
echo $form->textFieldRow($model,'category');
echo "        ";
$this->widget('bootstrap.widgets.TbButton',array(
'buttonType'=>'submit',
'type'=>'success',
'size'=>'large',
'label'=>'Search For Products ',
));
$this->endWidget();
?>
</div>
searchResults.php
<?php
echo "<h4>Results for Your Search</h4>";
foreach($models as $model):
$this->beginWidget('bootstrap.widgets.TbDetailView',array(
'type'=>'bordered condensed',
'data' => array(
'Shop Name' =>CHtml::link(CHtml::encode($model->addname),array('add/view','id'=> $model->addid)),
'Category' => $model->category
),
'attributes' => array(array('name' => 'Shop Name', 'label' => 'Name of Shop','value'=>CHtml::link(CHtml::encode($model->addname),
array('add/view','id'=>$model->addid)),'type'=>'raw'),
array('name' => 'Category', 'label' => 'Category of Shop'),
),
)
);
echo "<br><hr><br>";
$this->endWidget();
endforeach;
?>
what is wrong in the code??
I want to display no any product when text box is empty..
thanks in advance
change this
if(!is_null($attributes))
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
}
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
To
if($attributes)
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
}
1) Is the 'caterory' attribute safe on search scenario ? (in rules)
2) category is an attribute of the table schema ?
I have a form that requires the user to enter some information. If they fail to complete the required fields they are re-presented with the form; the top of the page notifying them what fields are required and I've enabled sticky forms (set_value()) so their input is not lost.
I'm using flashdata to display messages to the user (i.e., if what they've entered already exists in the database).
My form is in the index method of my controller.
When submit is clicked from my view it calls the add() method in my controller.
The add() method performs the validation and depending on the results either submits to the database or kicks back out to the user to get more data.
I have several issues with the way that i've done this.
1. If validation fails I'm using $this->index() to get back to my form and display the validation errors. If I try using redirect, I lose my validation errors and my $_POST[] data so my sticky forms end up blank.
2. Using $this->index() appends the 'add' to the end of my url
3. Using $this->index() causes issues with the flashdata. Random results.
Any ideas?
<?php
class Restaurant extends Controller {
function Restaurant() {
parent::Controller();
}
function index() {
// Load libraries and models
$this->load->model('/restaurant/mRestaurantTypes');
$this->load->model('/restaurant/mRestaurant');
$this->load->model('/utilities/mUtilities');
// Get states
$stateSelect = array();
$getStates = $this->mUtilities->getStates();
if($getStates->num_rows() > 0) {
foreach($getStates->result() as $row) {
$stateSelect[$row->abbr] = $row->name;
}
}
// Get restaurant types
$restaurantTypes = array();
$getRestaurantTypes = $this->mRestaurantTypes->getRestaurantTypes();
if($getRestaurantTypes->num_rows() > 0) {
foreach($getRestaurantTypes->result() as $row) {
$restaurantTypes[$row->restaurant_types_id] = $row->type;
}
}
// Create form elements
$data['name'] = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name'),
'maxlength' => '200',
'size' => '50'
);
$data['address'] = array(
'name' => 'address',
'id' => 'address',
'value' => set_value('address'),
'maxlength' => '200',
'size' => '50'
);
$data['city'] = array(
'name' => 'city',
'id' => 'city',
'value' => set_value('city'),
'maxlength' => '50',
'size' => '25'
);
$data['state'] = $stateSelect;
$data['zip'] = array(
'name' => 'zip',
'id' => 'zip',
'value' => set_value('zip'),
'maxlength' => '10',
'size' => '10'
);
$data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'value' => set_value('phone'),
'maxlength' => '15',
'size' => '15'
);
$data['url'] = array(
'name' => 'url',
'id' => 'url',
'value' => set_value('url'),
'maxlength' => '255',
'size' => '50'
);
$data['type'] = $restaurantTypes;
$data['tags'] = array(
'name' => 'tags',
'id' => 'tags',
'value' => set_value('tags'),
'maxlength' => '255',
'size' => '50'
);
$data['active'] = array(
'name' => 'active',
'id' => 'active',
'value' => 'Y',
'maxlength' => '1',
'size' => '2'
);
// Set page variables
$data_h['title'] = "Add new restaurant";
// Load views
$this->load->view('/template/header', $data_h);
$this->load->view('/restaurant/index', $data);
$this->load->view('/template/footer');
}
/**
* Add the the new restaurant to the database.
*/
function add() {
// Load libraries and models
$this->load->library('form_validation');
$this->load->model('/restaurant/mRestaurant');
// Define validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[255]|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[100]|xss_clean');
$this->form_validation->set_rules('city', 'City', 'trim|required|max_length[128]|xss_clean');
//$this->form_validation->set_rules('state', 'State', 'trim|required');
$this->form_validation->set_rules('zip', 'Zip', 'trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|max_length[10]|xss_clean');
$this->form_validation->set_rules('url', 'URL', 'trim|required|max_length[255]|xss_clean');
$this->form_validation->set_rules('tags', 'Tags', 'trim|xss_clean');
// Form validation
if ($this->form_validation->run() == FALSE) {
// On failure
$this->index();
} else {
// On success, prepare the data
$data = array(
'name' => $_POST['name'],
'address' => $_POST['address'],
'city' => $_POST['city'],
'state' => $_POST['state'],
'zip' => $_POST['zip'],
'phone' => $_POST['phone'],
'url' => $_POST['url'],
'type' => $_POST['type'],
'tags' => $_POST['tags'],
'active' => $_POST['active'],
);
// Check if the restaurant already exists
$check = $this->mRestaurant->getRestaurant($data['name'], $data['zip']);
// If no records were returned add the new restaurant
if($check->num_rows() == 0) {
$query = $this->mRestaurant->addRestaurant($data);
if ($query) {
// On success
$this->session->set_flashdata('status', '<div class="success">Added New Restaurant!</div>');
} else {
// On failure
$this->session->set_flashdata('status', '<div class="error">Could not add a new restaurant.</div>');
}
redirect('restaurant/confirm', 'refresh');
} else {
// Notify the user that the restaurant already exists in the database
$this->session->set_flashdata('status', '<div class="notice">This restaurant already exists in the database.</div>');
redirect('restaurant/index');
}
}
}
function confirm() {
$data['title'] = "Confirm";
$this->load->view('/template/header');
$this->load->view('/restaurant/confirm', $data);
$this->load->view('/template/footer');
}
}
?>
I will try to help with the logic in the controller that I always use:
function index()
{
//set some default variables
$data['error_message'] = '';
//if this is to edit existing value, load it here
// from database and assign to $data
//...
//set form validation rules
$validation = array();
$validation['field_name'] = array(
'field' => 'field_name',
'label' => 'Field label',
'rules' => 'trim|required'
);
//more rules here
//...
$this->load->library('form_validation');
$this->form_validation->set_rules($validation);
//run validation
if ($this->form_validation->run() == FALSE)
{
$data['error_message'] .= validation_errors();
}
else
{
//do insert/update
//
//it's better to do redirection after receiving post request
//you can use flashdata for success message
if ( $success )
{
$this->session_set_flashdata('success_message', MESSAGE_HERE);
}
redirect(RESULT_PAGE);
}
//reaching this block can have 2 meaning, direct page access, or not have valid form validation
//assign required variables, such as form dropdown option, etc
//...
//load view
$this->load->view(VIEW_FILE, $data);
}
View file:
...
<?php if ( $error_message ): ?>
<?php echo $error_message; ?>
<?php endif; ?>
<?php echo form_open(current_url, array('id' => 'some_form_id')); ?>
<!-- form field here -->
<label for="field_name">Field label</label>
<input name="field_name" value="<?php echo set_value('field_name', $DEFAULT_FIELD_NAME_IF_NEEDED); ?>" />
<!-- more form field here -->
<?php echo form_close(); ?>
...
I hope this will help you.
For the $DEFAULT_FIELD_NAME_IF_NEEDED in the view file, I use this to pass the default value if this form page is to edit existing data from database. You can load the data in the controller, then pass it to view file and display it in the form field.
-------controller-------
$data['post'] = $_POST;
$this->load->view('view/view', $data);
then in your view
<input type="text" value="><?=$post['username'];?>" name="username">
I had a similar problem and I ended up doing:
My form is to create new user but you should get the idea.
if($this->form_validation->run() == FALSE)
{
$this->data['title'] = "Add User";
$this->load->vars($this->data);
$this->load->view('head');
$this->load->view('header');
$this->load->view('admin/sidebar');
$this->load->view('admin/add_user');
$this->load->view('footer');
}
So effectively instead of calling new function I was showing new view from the same function.
Not the nicest solution but it works.
Also you might want to use something like this to check if the restaurant already exists:
function _check_username($str)
{
$this->db->where('username', $str);
$query = $this->db->get('sm_users');
if($query->num_rows() == 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('_check_username', "User '$str' already exists!");
return FALSE;
}
}
And use callback validation function:
$this->form_validation->set_rules('userName','User Name','trim|required|min_length[3]|callback__check_username');
You could try having the form post to index, and in the index method, do validation if the form has been submitted. Then either render the index view (if there are errors) or add the restaurant and render the confirm view.