How do I make it so that when I go through with error validation on my post form, it doesn't only send back the default values from the database, but if I were to edit the values and hit submit, it would save the data I tried to update with. I'm stuck where I can only do one or the other.
<? if (isset($update)) { ?>
<?php echo set_value ('fname'); ?>
<?= form_open("Phonebook/updateentry/" . $entry['id']) ?>
<?= form_fieldset("Update Entry"); ?>
<?= form_label('First Name: ', 'fname'); ?> <br>
<?= form_input(array('name' => 'fname', 'id' => 'fname', 'value' => $entry['fname'])); ?> <br>
<?= form_label('Last Name: ', 'lname'); ?> <br>
<?= form_input(array('name' => 'lname', 'id' => 'lname', 'value' => $entry['lname'])); ?> <br>
<?= form_label('Phone Number: ', 'phone'); ?> <br>
<?= form_input(array('name' => 'phone', 'id' => 'phone', 'value' => $entry['phone'])); ?> <br>
<?= form_label('Email: ', 'email'); ?> <br>
<?= form_input(array('name' => 'email', 'id'=>'email', 'value' => $entry['email'])); ?> <br>
<?= form_submit('phonebooksubmit', 'Submit'); ?>
<?= form_fieldset_close(); ?>
<?= form_close() ?>
<? } ?>
private function display()
{
$query = $this->db->query("SELECT * FROM phonebook ORDER BY id ASC;");
$this->TPL['listing'] = $query->result_array();
$this->load->view('phonebook_view', $this->TPL);
}
public function updateentry($id)
{
$this->form_validation->set_rules('fname', 'First Name', 'required|alpha|min_length[5]|max_length[15]',
array(
'required' => 'You have not provided the %s. ',
'alpha' => '%s must only compose of alphanumeric letters.',
'max_length' => 'You exceeded max char of 20 . ',
'min_length' => 'The min length must be 5 . '
));
$this->form_validation->set_rules('lname', 'Last Name', 'required|alpha|min_length[5]|max_length[20]',
array(
'required' => 'You have not provided %s .',
'alpha' => '%s must only compose of alphanumeric letters.',
'max_length' => 'You exceeded max char of 20 . ',
'min_length' => 'The min length must be 5 . '
));
$this->form_validation->set_rules('phone', 'Phone Number', 'required|regex_match[/^([0-9]{3})[-. ]([0-9]{4})$/]',
array(
'required' => 'You have not provided %s .',
'regex_match' => 'Please use the correct phone format.'
));
$this->form_validation->set_rules('email', 'Email', 'required|valid_email',
array(
'required' => 'You have not provided %s .',
'valid_email' => 'Please provide valid email. '
));
$this->form_validation->set_error_delimiters('<p class = "errorlist">' , '</p>');
if ($this->form_validation->run() == FALSE) {
$query = $this->db->query("SELECT * FROM phonebook where id = '$id';");
$this->TPL['entry'] = $query->result_array()[0];
$this->TPL['update'] = true;
$this->TPL['memory'] = true;
$this->display();
}
else
{
$fname = $this->input->post("fname");
$lname = $this->input->post("lname");
$phone = $this->input->post("phone");
$email = $this->input->post("email");
$query = $this->db->query("UPDATE phonebook " .
"SET fname = '$fname'," .
" lname = '$lname'," .
" phone = '$phone'," .
" email = '$email'" .
" WHERE id = '$id';");
$this->display();
}
}
I know I have to use the set_value() but i'm not sure how to make it so that it can do both.
set_value has a second parameter, which is the default. In the case of you pulling up records and editing them, it looks like this:
// $data is from your database
set_value('name', $data['name'])
I used "name" as an example, but this could be any field in your record.
But back in your controller, you'd want something like this:
if( $this->input->method == 'POST' )
// Do your validation and updating to the record
// Then pull in the record for your view
$view_data['data'] = $this->db->query('... ... ...');
By doing this, you're always pulling in the fresh data
Your code looks pretty solid.
I would suggest to try adding a
$this->db->update(.......)
at the end of your function.
Then the database gets updated with up-to-the-second info.
Hope this helps.
Related
I am currently doing a project. I have a checkbox( where the user will choose type of services provided by the company). When I try to post the service that was selected(for example 2 services is checked) in my controller, I am only getting one service. The question is how can I get the multiple values in my checkbox?
Note: I also tried to use foreach within my controller, I am getting some error like "Invalid argument supplied for foreach()".
View
<label>Desired Service</label> <br>
<?php foreach($services as $s):?>
<label><input type="checkbox" name="service_name[]" value="<?= $s->service_name?>"><?= $s->service_name?></label>
<br>
<?php endforeach?>
Controller
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('full_name', 'Fullname', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('zip_code', 'Zip Code', 'numeric|required');
$this->form_validation->set_rules('province', 'Province', 'required');
$this->form_validation->set_rules('date', 'Date', 'required');
$this->form_validation->set_rules('service_name', 'Service', 'required');
if ($this->form_validation->run() == FALSE) {
$this->index();
}
else {
$service_name = implode(', ', $_POST['service_name']);
$event = array(
'full_name' => $this->input->post('full_name'),
'email' => $this->input->post('email'),
'contact' => $this->input->post('contact'),
'address' => $this->input->post('address'),
'zip_code' => $this->input->post('zip_code'),
'state_province' => $this->input->post('province'),
'date' => $this->input->post('date'),
'service' => $service_name
);
$this->EventModel->add_event($event);
echo "<script>
window.alert('Your Desired Date is being Proccessed!');
location.href = '".site_url('/')."';
</script>";
}
Change from
$service_name = $_POST['service_name'];
foreach($service_name as $key =>$value)
{
echo $value;
}
die;
to
$service_name = implode(',',$_POST['service_name']);
echo $service_name;
I hope it will solve your problem
if (!empty($this->input->post('service_name'))) {
foreach ($this->input->post('service_name') as $key => $val) {
$data[] = array(
'service_name' => $_POST['service_name'][$key]
);
}
foreach ($data as $item) {
echo $item['service_name'];
}
Try:
$service_name = $this->input->post('service_name');
for($i=0;$i < count($service_name);$i++){
echo $service_name[$i];
}
I want to make a validation form in cakephp my code form is:
view
<div class="well">
<?php
echo $this->Form->create(false);
echo $this->Form->input('name', array('label' => 'name '));
echo $this->Form->input('PHONE_NUMBER', array('label' => 'PHONE_NUMBER '));
echo $this->Form->input('EMAIL', array('label' => 'EMAIL '));
echo $this->Form->input('ISSUE', array('label' => 'ISSUE '));
echo $this->Form->input('IP', array('label' => 'IP '));
echo $this->Form->submit('Send.');
?>
Controller
<?php
class ContactController extends AppController {
public function index() {
if (empty($_POST) === FALSE) {
$message = '';
$message .=$_POST['data']['EMAIL'] . ' <br/>';
$message .=$_POST['data']['name'] . ' <br/>';
$message .=$_POST['data']['PHONE_NUMBER'] . ' <br/>';
$message .=$_POST['data']['ISSUE'] . ' <br/>';
$message .=$_SERVER['REMOTE_ADDR'] . ' <br/>';
mail('mohmed#lcegy.com', 'Support From Website ', $message);
$this->Session->setFlash("Thanks , an email just sent .");
}
}
}
My question is how to implement validation in this form and how to get the IP address of the visitor?
You may want to update your index() function to look something similar to this: I think it's more of the cakePHP convention.
public function index() {
if ($this->request->is('post')) {
$message = '';
$message = $this->request->data['EMAIL'];
...
}
}
For validation, you can add that to your model. You could do something similar:
public $validate = array(
'EMAIL' => 'email',
'name' => array(
'rule' => 'alphaNumeric',
'required' => true
)
);
For more validation, you can look at the documentation: http://book.cakephp.org/2.0/en/models/data-validation.html
You can use $_SERVER['REMOTE_ADDR'] to get the client's IP Address.
You Can Do Validation From Your Model by setting Rules as follows
public $validate =
array(
'Email' => array
(
'rule' => 'notempty'
),
);
Best way to do it by model as above given answers but you can also do it at view page by simply adding attributes "require" and define proper types like emails, numbers. eg. in your form:
<?php
echo $this->Form->create(false);
echo $this->Form->input('name', array('label' => 'name ', 'required' => true));
echo $this->Form->input('PHONE_NUMBER', array('label' => 'PHONE_NUMBER ', 'required' => true,'type'=>'number'));
echo $this->Form->input('EMAIL', array('label' => 'EMAIL ', 'required' => true, 'type' => 'email'));
echo $this->Form->input('ISSUE', array('label' => 'ISSUE ', 'required' => true));
echo $this->Form->input('IP', array('label' => 'IP ', 'required' => true));
echo $this->Form->submit('Send.');
?>
I am using Ionauth library in codeigniter and edited edit_user() method in Auth controller to enable individual user updating his/her own user settings. So when a logged in user goes to : siteurl/auth/edit_user it shows the user settings just fine. But when I hit the save button I got an error: "This form post did not pass our security checks". Though the default url (siteurl/auth/edit_user/userID) works fine, For individual non-admin user I want to keep the url without userID at the end.
here is my edit_user() method:
//edit a user
function edit_user($id=NULL)
{
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !($this->ion_auth->user()->row()->id == $id) && !($id==NULL )))
//if (!$this->ionauth->logged_in() || !$this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
if($id==NULL){
$user = $this->ion_auth->user()->row();
}else{
$user = $this->ion_auth->user($id)->row();
}
$groups=$this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
/**if (isset($user->phone) && !empty($user->phone))
{
$user->phone = explode('-', $user->phone);
} **/
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
if(!($this->input->post('email')==$user->email)){
$this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'required|valid_email|is_unique[users.email]');
}else{
$this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'required|valid_email');
}
/** $this->form_validation->set_rules('phone2', $this->lang->line('edit_user_validation_phone2_label'), 'required|xss_clean|min_length[3]|max_length[3]');
$this->form_validation->set_rules('phone3', $this->lang->line('edit_user_validation_phone3_label'), 'required|xss_clean|min_length[4]|max_length[4]');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean'); **/
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
//$this->form_validation->set_message('is_unique[users.email]','Email already exists or Invalid');
if (isset($_POST) && !empty($_POST))
{
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
{
show_error($this->lang->line('error_csrf'));
}
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
/** 'phone' => $this->input->post('phone1') . '-' . $this->input->post('phone2') . '-' . $this->input->post('phone3'), **/
);
//if($this->ion_auth->is_admin()){
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
}
}
//}
//update the password if it was posted
if ($this->input->post('password'))
{
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
}
if ($this->form_validation->run() === TRUE)
{
$this->ion_auth->update($user->id, $data);
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth", 'refresh');
}
}
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
//if($this->ion_auth->is_admin()){
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
//}
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email', $user->email),
);
/** $this->data['phone1'] = array(
'name' => 'phone1',
'id' => 'phone1',
'type' => 'text',
'value' => $this->form_validation->set_value('phone1', $user->phone[0]),
);
$this->data['phone2'] = array(
'name' => 'phone2',
'id' => 'phone2',
'type' => 'text',
'value' => $this->form_validation->set_value('phone2', $user->phone[1]),
);
$this->data['phone3'] = array(
'name' => 'phone3',
'id' => 'phone3',
'type' => 'text',
'value' => $this->form_validation->set_value('phone3', $user->phone[2]),
); **/
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->load->view('header');
$this->_render_page('auth/edit_user', $this->data);
$this->load->view('footer');
}
and this is my view file (edit_user.php):
<h1><?php echo lang('edit_user_heading');?></h1>
<div id="body">
<p><?php echo lang('edit_user_subheading');?></p>
<div id="infoMessage"><?php echo $message;?></div>
<?php echo form_open(uri_string());?>
<p>
<?php echo lang('edit_user_fname_label', 'first_name');?> <br />
<?php echo form_input($first_name);?>
</p>
<p>
<?php echo lang('edit_user_lname_label', 'last_name');?> <br />
<?php echo form_input($last_name);?>
</p>
<p>
<?php echo lang('edit_user_email_label', 'email');?> <br />
<?php echo form_input($email);?>
</p>
<!--
<p>
<?php echo lang('edit_user_phone_label', 'phone');?> <br />
<?php echo form_input($phone1);?>-<?php echo form_input($phone2);?>-<?php echo form_input($phone3);?>
</p>
-->
<p>
<?php echo lang('edit_user_password_label', 'password');?> <br />
<?php echo form_input($password);?>
</p>
<p>
<?php echo lang('edit_user_password_confirm_label', 'password_confirm');?><br />
<?php echo form_input($password_confirm);?>
</p>
<?php //if($this->ion_auth->is_admin()){ ?>
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php foreach ($groups as $group):?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php endforeach?>
<?php //} ?>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<p><?php echo form_submit('submit', lang('edit_user_submit_btn'));?></p>
<?php echo form_close();?>
The csrf check is failing.
Try taking out $id = NULL in the method declaration (you don't need it anyway if you're sending the id via POST). Or explicitly set $id = $this->input->post('id'); before doing the csrf check.
In my case I was using relative URLs for the images and css files used in the site. Using base_url() to all the URLs present in the site fixed the problem. No issue now.
i want to validate 2 date input in codeigniter, with the conditions, if the end date is greater than the start date, will appear warning [javascript warning or something] or data can't be input
my form like this,
<h1><?php echo $title; ?></h1>
<form action="<?= base_url(); ?>index.php/admin/kalender/buat" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "<p><label for='IDKategori'>Tingkatan Pimpinan :</label><br/>";
echo form_dropdown('IDKategori', $kategori) . "</p>";
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');
echo form_input($data) . "</p>";
echo form_submit('submit', 'Tambah Even');
?>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
how to validate in form "Waktu Akhir & Waktu Mulai" ?
Try this. It is by using CI validation library.
It uses callback type of validation.
Put this in if(isset($_POST['submit_button_name'])) {} section.
First, load validation array,
$validation = array(
array('field' => 'startDate', 'label' => 'StartDate', 'rules' => 'required|callback_compareDate'),
array('field' => 'endDate', 'label' => 'endDate', 'rules' => 'required|callback_compareDate'),
);
Then load CI validation library as,
$this->form_validation->set_rules($validation);
$this->form_validation->set_message('required', '%s is required.');
This is the called back function.
function compareDate() {
$startDate = strtotime($_POST['startDate']);
$endDate = strtotime($_POST['endDate']);
if ($endDate >= $startDate)
return True;
else {
$this->form_validation->set_message('compareDate', '%s should be greater than Contract Start Date.');
return False;
}
}
The "required" validation makes the fields mandatory to be filled with something.
The callback function, in this case, compares the dates, and further processes the form if start date is less than from date OR flags error otherwise.
Meanwhile, if you want in Jquery you can use this.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate > endDate){
alert("Start Date should be less than End Date");
return false;
}
This is working code
$params['toDate'] = $this->input->post('toDate', TRUE);
$params['fromDate'] = $this->input->post('fromDate', TRUE);$this->load->model('your_model');
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$startDate = strtotime($params['fromDate']);
$endDate = strtotime($params['toDate']);
if ($endDate >= $startDate):
$this->form_validation->set_rules('fromDate', 'From Date', 'required|trim');
$this->form_validation->set_rules('branchCode', 'Branch Code', 'required|trim');
else:
$json = array(
"success" => false,
"msg" => "Start date must be greater than end date"
);
echo json_encode($json);
die();
endif;
Disclaimer: I'm new to web develoment.
Scenario: I've created a contact form, and I'm trying to pass the input into the email class functions used in CodeIgniter. I am receiving undefined variable errors when the form is submitted. Email library is autoloaded for reference. It's late, and I may be overlooking something easy, but it doesn't hurt to post. Thanks a lot for all of your help!
Controller:
public function index()
{
//form validation
$this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['subject'] = array(
'name' => 'subject',
'id' => 'subject',
'type' => 'text',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['message'] = array(
'name' => 'message',
'id' => 'message',
'type' => 'text',
'value' => $this->form_validation->set_value('message'),
);
if ($this->form_validation->run() == true)
{
$this->email->from($email);
$this->email->to('support#example.com');
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
redirect('contact/success');
}
else
{
$this->data['error_message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error_message');
$title['title'] = 'Contact';
$this->load->view('public/head_view', $title);
$this->load->view('public/header_view');
$this->load->view('public/contact_view', $this->data);
$this->load->view('public/footer_view');
}
View:
<div id="infoMessage"><?php echo $error_message;?></div>
<?php $attritubes = array('class' => 'nice'); ?>
<?php echo form_open('contact'); ?>
<p>Email Address:<br />
<?php echo form_input($email); ?>
</p>
<p>Subject:<br />
<?php echo form_input($subject); ?>
</p>
<p>Message:<br />
<?php echo form_textarea($message); ?>
</p>
<p><?php echo form_submit('submit', 'Submit'); ?></p>
<?php echo form_close(); ?>
Well, you barely define any variable here:
if ($this->form_validation->run() == true)
{
$this->email->from($email);
$this->email->to('support#example.com');
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
redirect('contact/success');
}
Where do $email, $subject, $message come from?
You might want to use something like (but I suggest you do better :))
$email = $this->input->post('email');
$subject = $this->input->post('subject');
$message = $this->input->post('message');
Also, make sure you've loaded the email library before calling it, and that you load the view in your else{} part (since you omitted it I cannot tell)