How would I go about inserting the session userdate id into my new table using the form I have in my view so that I may use the id as a foreign key?
Controller:
function validate_credentials() {
$this->load->model('member_model');
$query = $this->member_model->validate();
if ($query) { // if user credentials validate the user session start
$data = array(
'username' => $query->username,
'id' => $query->id,
'first_name'=>$query->first_name,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('members/members_area');
} else {
$this->index();
echo 'Incorrect Password or Username';
}
}
View:
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Length'));
echo form_submit('submit', 'Create Account')
echo validation_errors('<p class="error"/>');
Try this :
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Length'));
**echo form_input('id', set_value('id', $this->session->userdata('id'));**
echo form_submit('submit', 'Create Account')
echo validation_errors('<p class="error"/>');
Note : where 'id' in first parameter of form_input function can be replace by any name you want to pass when form will be submit.
In the method used in the controller banks where you handle the posted data from the from.
add something like this:
$data = array('bank_name' => $this->input->post('bank_name'), // add more post data
'id' => $this->session->userdata('id') ); //this will take the
//value 'id' from session
and pass it to your respective model.
Related
I am trying to get values in select box as dynamic is not working
here is the my controller code below:
public function CreateNewAsset()
{
$data['courselist'] = $this->Dashboard_model->getDashboardCourses();
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('topicname', 'Topicname', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset');
$this->load->view('template/footer');
} else {
//Setting values for tabel columns
$data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
//Transfering data to Model
$this->Dashboard_model->assetInsert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset', $data);
$this->load->view('template/footer');
}
}
Here is the my view below:
<form action="<?php echo base_url();?>Dashboard/CreateNewAsset" method="post">
<div class="form-row">
<div class="col-md-3">Course:</div>
<div class="col-md-9">
<select name="courseid" class="form-control">
<option value="0">Select Course</option>
<?php foreach ($courselist as $course) { ?>
<option value="<?php echo $course->id; ?>"><?php echo $course->coursename; ?></option>
<?php } ?>
</select>
</div>
</div>
</form>
I have added both getting values and insert in the same function. is this the problem I am not getting values in drop-down can anyone help me what is the mistake
and I am getting an error as Undefined variable: courselist
Change the insert part like this since u overriding $data:
$insert_data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
$this->Dashboard_model->assetInsert($insert_data);
The whole code should be like this :
NOTE : make sure u have loaded form_validation library and method getDashboardCourses return some data
public function CreateNewAsset()
{
$data['courselist'] = $this->Dashboard_model->getDashboardCourses();
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('topicname', 'Topicname', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset',$data);
$this->load->view('template/footer');
}
else
{
$insert_data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
$this->Dashboard_model->assetInsert($insert_data);
$data['message'] = 'Data Inserted Successfully';
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset', $data);
$this->load->view('template/footer');
}
}
Your "View" can't find the courseList variable.
You need to do add courseList to your data array before you pass it to the view with the form.
Eg:-
data['courseList'] = $this->getCourseList(); // Fetch the list of rows
I have a site with buddypress and I need to check if current user has a specific value on specific field
I was trying this but it's not working
<?php
$data= bp_profile_field_data( array('user_id'=>get_current_user_id( 'ID' )));
if($data=='Funny Guy') {
echo 'yes';
} else {
echo 'no';
}
?>
Any hints why?
Try using bp_get_profile_field_data instead and provide the name of the field you need. So:
$args = array(
'field' => 'Your field name', // Exact field name or field ID.
'user_id' => bp_loggedin_user_id() // ID of logged in user
);
$data = bp_get_profile_field_data( $args );
if ( $data == 'Funny Guy' ) {
echo 'yes';
} else {
echo 'no';
}
We have two models which are related by a has and belongs to many (HABTM) relationship: Jobs, Tests. We are able to add/edit the relationships successfully (we know because they show up in the join table), but we can't get the existing values to appear in the view. The select/checkboxes (we've tried both) are always empty.
Here are the model relationships:
//Job.php
public $hasAndBelongsToMany = array (
'Test' => array (
'classname' => 'Test',
'foreignKey'=>'job_id',
'joinTable' => 'jobs_tests',
'associatedForeignKey' => 'test_id'
)
);
//Test.php
public $hasAndBelongsToMany = array(
'Job' => array(
'className'=> 'Job',
'joinTable'=>'jobs_tests',
'foreignKey' => 'test_id',
'associatedForeignKey'=> 'job_id'
)
);
Here is the /view/Jobs/edit.ctp
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
//This is always empty (nothing selected/checked).
What are we doing wrong?
Update:
Here is the JobsController action:
public function admin_edit( $id=NULL ) {
$this->layout = 'admin';
if (!$id)
$this->redirect( array('controller'=>'jobs', 'action'=>'index'));
$this->loadModel('Company');
$companies = $this->Company->find('all');
$company_options = array();
foreach ($companies as $company) {
$company_options[ $company['Company']['id'] ] = $company['Company']['name'];
}
$this->set('company_options', $company_options);
$this->loadModel('Test');
$tests = $this->Test->find('all');
$tests_options = array();
foreach ($tests as $test) {
$test_options[ $test['Test']['id'] ] = $test['Test']['name'];
}
$this->set('test_options', $test_options);
$category_options = $this->Job->validCategories;
$this->set('category_options', $category_options);
if ($this->request->isPut() ) {
$data = $this->request->data;
//debug($data);exit;
$save = $this->Job->save( $data );
if ($save) {
$this->Session->setFlash('Job edited');
//$job = $this->Job->findById( $id );
} else {
$this->Session->setFlash('Error editting job');
}
}
$job = $this->Job->findById($id);
$this->request->data = $job;
$this->set('job', $job);
}
Here is the form in the admin_edit.ctp view:
<?php echo $this->Form->create('Job'); ?>
<fieldset>
<?php
echo $this->Form->input('id', array('type'=>'hidden'));
echo $this->Form->input('name', array('class'=>'form-control'));
echo $this->Form->input('email', array('class'=>'form-control'));
echo $this->Form->input('location', array('class'=>'form-control'));
echo '<label>Type</label>';
echo $this->Form->select('type', array('FT'=>'Full Time', 'PT'=>'Part Time', 'IN'=>'Internship'), array('empty'=>false, 'class'=>'form-control'));
echo '<label>Company</label>';
echo $this->Form->select('company_id', $company_options, array('class'=>'form-control'));
echo $this->Form->input('short_description', array('label' => 'Short Description', 'class'=>'form-control'));
echo $this->Form->input('full_description', array('type'=>'textarea', 'label' => 'Full Description', 'class'=>'form-control'));
echo $this->Form->input('is_private', array('label'=>'Is Private?', 'class'=>'form-control') );
echo '<label>Category</label>';
echo $this->Form->select('category', $category_options, array('class'=>'form-control'));
echo '<label>Tests</label>';
//echo $this->Form->select('Test.id', $test_options, array('class'=>'form-control', 'multiple'=>true));
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]=$test['id'];
//$selected[ $test['id'] ] = $test['name'];
}
debug($selected);
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
PHEW! This was a stumper but the solution turned out to be simple... The values in $options['selected'] were strings (of numbers), which was confusing CakePHP. We converted them to ints using intval() and it works perfectly now, using all the original settings...
Here's the revised version of what is in the view (notice the intval()):
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]= intval($test['id']);
}
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
Also, as a sidenote, this is evidence that pretty much everything that was challenged in the comments above works completely fine:
$options['selected'] does not need to be key=>value pairs.
The pattern we're using does not overwrite the request->data and passes the data to the form helper just fine.
non-camelCased variable names passed to the view ($some_variable_name) are still picked up correctly by the form helper.
Hopefully this comes in handy to someone else.
What if you pass set the default values using Model::find('list').
//controller
$this->set('test_options', $this->YourModel->find('list'));
//view
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
I cant seem to update the Phone Number, I am new to Codeigniter and been trying to figure out what I am doing wrong.
This is my MODEL:
function updatePhone($submit_userid, $submit_phone) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
"strPhoneNumber" => $submit_phone
));
}
This is my CONTROLLER:
public function updateAccount() {
$this->load->model('updateModel');
$this->load->model('userModel');
$data['userdata'] = $this->session->userdata('userobject');
$this->form_validation->set_rules('phone', 'Phone', 'required|min_length[8]|max_length[12]|xss_clean');
if ($this->form_validation->run() == false) {
$this->load->view('updateView', $data);
} else {
$submit_userid = $this->input->post('userid');
$submit_phone = $this->input->post('phone');
$this->userModel->updatePhone($submit_userid, $submit_phone);
redirect('updateController/updateAccount');
}
}
This is my VIEW:
<?php
echo validation_errors();
echo form_open('updateController/updateAccount');
echo '<input type="hidden" name="userid" value=' . $userdata->intMemberID . '/> <br/>';
echo "$userdata->strMemberFirstName $userdata->strMemberLastName";
echo "<br>";
echo "Phone Number: <input type='text' name='phone' placeholder='$userdata->strPhoneNumber'/>";
echo '<INPUT type="submit" value="Update" name="submit"/>';
echo form_close();
?>
you can try this update statement, even if this doesnot works out then please check the column type you are using (varchar or whatever and its size if its conflicting or not)
<?php
$data['strPhoneNumber'] = $submit_phone;
$this->db->where('intMemberID', $submit_userid)->update('tblMembers', $data);
?>
You never perform an update to the database. The select statement is not needed in an update, you pass the table name to the update method.
function getUpdate($submit_userid, $submit_phone) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
"strPhoneNumber" => $submit_phone
));
}
And you shouldn't really call the method getUpdate, it's not really semantic since you're not actually getting anything. updatePhone might be a better name.
try to print out the error
return $this->db->update("tblMembers", array );
var_dump the updatePhone result and you will see whether there is an error with table or something else
make sure it returns true before redirecting
$data = array(
"strPhoneNumber" => $submit_phone
);
$where = "intMemberID = ".$intMemberID;
//generate the query string not executing
$str = $this->db->update_string('tblMembers', $data, $where);
echo '<pre>';
echo $str;
die;
Put the above code in your function, verify the query string
i want to validate startdate and endate codeigniter, if stardate > enddate, not saving in my database, or show error message
my controller like this
function buat_lagi() {
if ($this->input->post('IDKategori')) {
$this->MKalender->addEvents();
$id = $_POST[IDKategori];
$this->session->set_flashdata('message', 'Agenda Pimpinan baru telah dibuat !');
redirect('admin/kalenderkategori/lihat/' . $id . '', 'refresh');
} else {
$data['title'] = "Tambah Agenda Pimpinan";
$data['kategori'] = $this->MKalenderKategori->getKategoriDropDown();
$data['main'] = 'admin/kalender/kalender_buat_lagi';
$this->load->vars($data);
$this->load->view('layout/dashboard');
}
}
my model like this
function addEvents() {
$data = array(
'IDKategori' => $this->input->post('IDKategori'),
'TanggalMulai' => $this->input->post('TanggalMulai'),
'TanggalAkhir' => $this->input->post('TanggalAkhir'),
'judul' => $this->input->post('judul'),
'konten' => $this->input->post('konten'),
'create_by' => $_SESSION['username'],
);
$this->db->insert('kalender', $data);
}
my form like this
<form action="<?= base_url(); ?>index.php/admin/kalender/buat_lagi/" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "<label for='ptitle'>Kegiatan / Lokasi :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'judul', 'id' => 'ptitle', 'size' => 80);
echo form_input($data);
echo "<p><label for='long'>Uraian Kegiatan / Keterangan / Catatan :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'konten', 'rows' => '13', 'cols' => '60', 'style' => 'width: 60%');
echo form_textarea($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Mulai :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalMulai', 'id' => 'basic_example_1');
echo form_input($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Akhir :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalAkhir', 'id' => 'basic_example_2', 'onblur' => 'function compareDate()');
echo form_input($data) . "</p>";
echo form_hidden('IDKategori', $this->uri->segment(4));
echo form_submit('submit', 'Tambah Even');
?>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
how to validate my issue ??
You haven't given the format of your dates or even which the date fields are (keep in mind most of the users here speak primarily English) You also haven't stated if you want this check server side or client side. By the compare dates function called in your form I am assuming you want it at least client side, I would suggest though that form validation needs to be done server side as well. Client side is great for immediate notification to the user but it's useless for actually protecting input to the form server side.
jQuery for the client side (since I am not sure which field is which this is pseudo code:
function compareDate()
{
var startDate = Date.parse($("#startDate).val()");
var endDate = Date.parse($("#endDate).val()");
if(startDate>endDate)
{
alert("Your start date must be earlier than your end date.");
}
}
Codeigniter function (the callback should work but I haven't tested it.) You really only have to run the function on one of the date fields, you only want to return one error and it's irrelevant which you return it on since it's comparing the two.
//validation rule
$this->form_validtion->set_rules('endDate', 'End Date','trim|callback_compareDates');
function compareDates()
{
$start = strtotime($this->input->post('startDate'));
$end = strtotime($this->input->post('endDate'));
if($start > $end)
{
$this->form_validation->set_message('compareDates','Your start date must be earlier than your end date');
return false;
}