load different views according to select option - codeigniter

VIEW:
Payment Method:
<select name="payment" id="payment">
<option value=""> --- Select ---</option>
<option value="cash">Cash on Delivery</option>
<option value="online">Digital/Online Payment</option>
</select>
</label><?php echo form_error('payment'); ?></td>
</tr>
CONTROLLER:
public function save_order()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required|trim|max_length[50]');
$this->form_validation->set_rules('phone', 'phone', 'required|trim|is_numeric|min_length[9]');
$this->form_validation->set_rules('time', 'time', 'required');
$this->form_validation->set_rules('location', 'location', 'required');
$this->form_validation->set_rules('address', 'address', 'required|trim|xss_clean|max_length[300]');
$this->form_validation->set_rules('payment', 'payment', 'required');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == TRUE && ($payment = "cash"))
{
$this->load->view('billing_view');
else
{
$this->load->view('billing_view2');
}
I am trying to load different pages according to the select options in the form and it doesn't seem to be working.
Suggestions please??

public function save()
{
//If form validation returns false,
//call the index method(form) and return from the method
//so nothing else gets executed
if(!$this->form_validation->run()){
return $this->index();
}
$payment = $this->input->post("payment");
//If payment type is == cash
//load the view called cash and return from method
//so nothing else gets executed
if($payment == "cash"){
return $this->load->view('cash');
}
//default method behaviour if none of the above
//are true.
return $this->load->view("digital");
}

Related

undefined variable in codeigniter view which is already defined in the controller

This is my controller. here i declared current_company.
public function index($id='')
{
$this->load->model('Company_model');
($id!='') ? $data["company_details"]=$this->Company_model->get_company($id) :'';
($id!='') ? $data ["current_company"]=$this->Company_model->get_currentcomp($id) :'';
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',($id!='') ? $data : '');
$this->load->view('includes/footer');
}
This is my model. Here i declared the function
class Company_model extends CI_Model{
protected $strTableName = 'suc_company';
function __construct(){
parent::__construct ();
$this->db->from($this->strTableName);
}
function get_currentcomp($intPkId){
$this->db->where('pk_bint_company_id',$intPkId);
$q1 = $this->db->get($this->strTableName);
return $q1->result_array()[0];
}
This is the view part. here i called the $current_company !== FALSE then
<div class="form-group">
<label for="company_package" class="col-sm-3 control-label"> Package</label>
<div class="col-sm-9 col-xs-12">
<?php if ($current_company !== FALSE ) {?>
<select name="company_package" class="form-control select2" disabled="">
<option value="<?php echo $company_package;?>" selected=""><?php echo $packagename;?></option>
</select>
<?php } else { ?>
<?php } ?>
Error
an error is occurring... undefined data current_company
Change your controller code like this.
public function index($id='')
{
$this->load->model('Company_model');
$data["company_details"] = false;
$data["current_company"] = false;
if($id != ''){
$data["company_details"] = $this->Company_model->get_company($id);
$data["current_company"] = $this->Company_model->get_currentcomp($id);
}
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',$data);
$this->load->view('includes/footer');
}
As said in comment, you are leaving possibility that maybe $data wouldn't be passed to view file. You have to restrict this kind of oscillations.
Try this way:
public function index($id='')
{
if ((int)$id < 1) {
redirect('some/generic/place', 'refresh');
}
// we have integer in parameter
// so we will check if data by that parameter exists
$data = [];// initialization of array so we are sure $data is set
$this->load->model('Company_model');
$data['company_details'] = $this->Company_model->get_company($id);
if ($data['company_details']) {
$data['current_company'] = $this->Company_model->get_currentcomp($id) :'';
} else {
// in this point $data is an empty array
}
// $this way variable will be available in all view files
$this->load->var($data);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage');
$this->load->view('includes/footer');
// so now, in your view you would have wether company with details wether an empty array
// *first line of code assumes parameter would be an integer
// **also assumed that $this->Company_model->get_company($id) would return false/null/anEmptyArray if data doesn't exist
}

How to add "route action" into response content with Ajax Zend2?

I am new to zend framework and trying to test my first app about ajax with zend2.
I want to show a link when I return a response from my controller ! I try anyways but cann't view !
I try this:
Here my HTML:
<select id="my_list" onChange="showlist(this.value);" name="my_list">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here my Ajax Script:
function showlist(id){
$.post("user/list", {
content: id
},function(data){
if(data.response == true){
$('#div_show').html(data['html']);
}
}, 'json');
}
And my controller:
public function listAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost()) {
$post_data = $request->getPost();
$id = $post_data['content'];
if($id){
/* $html = $group; It's Ok ! I can view group value !*/
$html = 'Test !';
$response->setContent(\Zend\Json\Json::encode(array('response' => true,'html'=>$html)));
}
else{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
I can view group value when I select listbox, but I cann't see the link when I want to view its detail !
It's my first question ! Please help me.
var url = '<?php echo $this->url('user', array('action' => 'list')); ?>';
function showlist(id){
$.post(url, {
content: id
},function(data){
if(data.response == true){
$('#div_show').html(data['html']);
}
}, 'json');
}

Codeigniter validation, passing form data from controller function recipient to another

Im currently, exploring the validation library that is offered by ci.. and im currently having some trouble. ive tried to do some workarounds but to my disappoint it further messed up my codes. So ill just ask the pro's what i should do.
My view:
<?php echo validation_errors(); ?>
<?php echo form_open('bookstore/validateinsert');?>
<table cellpadding='4' align='center'>
<th>Title</th>
<tr>
<td><input type="text" name="bkname" value="<?php echo set_value('bkname');?>"/></td>
</tr>
<th>Author</th>
<tr>
<td><input type="text" name="bkauthor" value="<?php echo set_value('bkauthor'); ?>"/></td>
</tr>
<th>Released Year</th>
<tr>
<td><input type="text" name="bkyear" value="<?php echo set_value('bkyear'); ?>"/></td>
</tr>
<th>ISBN</th>
<tr>
<td><input type="text" name="bkisbn" value="<?php echo set_value('bkisbn'); ?>"/></td>
</tr>
<tr>
<td><input type='submit' value='insert'/></td>
</tr>
<?php echo form_close();?>
</table>
My controller:
public function validateinsert()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('bkname', 'Book Name', 'required|is_unique[books.book_name]');
$this->form_validation->set_rules('bkauthor', 'Book Author', 'required');
$this->form_validation->set_rules('bkyear', 'Year Published', 'required|max_length[4]');
$this->form_validation->set_rules('bkisbn', 'Book ISBN', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->insertbook();
}
else
{
$this->load->view('showbooks');
}
}
public function insertbook()
{
if($_POST)
{
$data = array(
'book_id' => null,
'book_name' => $_POST['bkname'],
'book_author' => $_POST['bkauthor'],
'book_year' => $_POST['bkyear'],
'book_isbn' => $_POST['bkisbn']
);
$duplicate = $this->_searchbook('book_name',$data['book_name']);
if(!$duplicate)
{
$insertid = $this->books_model->insert_books($data);
if($insertid)
{
$data['success'] = TRUE;
$data['message'] = "The book title was successfully added.";
}
else
{
$data['success'] = FALSE;
$data['message'] = "An error was encountered.";
}
}
else
{
$data['success'] = FALSE;
$data['message'] = "The book title is already in the system";
}
}
$this->load->view('book_entry');
}
I think that is all there is a need to know about..
The validations work perfect, although i have a question, what is the syntax for all numbers only as i want it included on my isbn and bkyear rules.(P.S. I still prefer javascript with its onblur feature)
THE PROBLEM:
The validations work as i said above, but my insert does not. If there are no rules broken, i calIed the insertbook function but it inserted nothing, as i assumed when i first made the validationfunction as the recipient of the form and i was right, the insertbook probably did not recieve the data in the form. What should i do? P.S. I have an idea in mind that i should just merge those 2 functions together but that would make a mess(or does it matter?). Ill just consult ur opinion on this.
Your php logic is wrong:
if ($this->form_validation->run() == FALSE)
{
// If validation fails load view
// $this->insertbook();
$this->load->view('showbooks');
}
else
{
//If validation pass insert book
// $this->load->view('showbooks');
$this->insertbook();
}
Also this $duplicate = $this->_searchbook('book_name',$data['book_name']); you can replace with validation rule:
$this->form_validation->set_rules('book_name', 'Name of book', 'is_unique[table.column]');
For your "only numbers problem" ->
$this->form_validation->set_rules('bkyear', 'Year', 'numeric');
Furthermore you can find a lot of build-in rules here:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#rulereference
If you need some custom rule you can write your own function. See manual here:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks
try this
public function validateinsert()
{
$this->load->library('form_validation');
if($this->input->post()) {
$this->form_validation->set_rules('bkname', 'Book Name', 'required|is_unique[books.book_name]');
$this->form_validation->set_rules('bkauthor', 'Book Author', 'required');
$this->form_validation->set_rules('bkyear', 'Year Published', 'required|max_length[4]');
$this->form_validation->set_rules('bkisbn', 'Book ISBN', 'required');
if ($this->form_validation->run() != FALSE)
{
$data = array(
'book_id' => null,
'book_name' => $this->input->post('bkname'),
'book_author' => $this->input->post('bkauthor'),
'book_year' => $this->input->post('bkyear'),
'book_isbn' => $this->input->post('bkisbn')
);
$this->insertbook($data);
}
}
else
{
$this->load->view('showbooks');
}
}
public function insertbook($data)
{
$duplicate = $this->_searchbook('book_name',$data['book_name']);
if(!$duplicate)
{
$insertid = $this->books_model->insert_books($data);
if($insertid)
{
$data['success'] = TRUE;
$data['message'] = "The book title was successfully added.";
}
else
{
$data['success'] = FALSE;
$data['message'] = "An error was encountered.";
}
}
else
{
$data['success'] = FALSE;
$data['message'] = "The book title is already in the system";
}
$this->load->view('book_entry');
}
you should look at the other answers because they have pointed out a number of mistakes. if you are doing a database operation - you always have to error check. databases are volatile. its also very easy to make a mistake so you want to isolate database methods.
just wrap an IF around it. whenever possible check for the negative condition first.
if ( $this->insertbook() == false )
{ echo 'omg there is an error something is wrong with my insert code' ;
$this->showError() ;
}
else
{ // no problem
$this->showSuccess() ; }
another way to do this is to return the id of the newly created record.
if ( ! $id = $this->insertbook() ) { echo 'insert failure' ; }
else { echo 'my new id is:' . $id ; }

CodeIgniter - I can't update row in my table

I can't find the correct way update one row in my table.
My view:
...
<?php echo form_open('ImenikController/verify_editing_phonebook/'.$this->uri->segment(3)); ?>
Ime i prezime*:
<input type='text' name='ime_prezime' value=""> <br><br>
Ulica i broj: <input type='text' name='ulica' value=""> <br><br>
Mesto: <input type='text' name='mesto' value=""> <br><br>
Telefon*: <input type='text' name='telefon' value=""> <br><br>
<u>Napomena: Polja sa zvezdicom su obavezna.</u> <br /> <br />
<input background:url('images/login-btn.png') no-repeat; border: none;
width='103' height='42' style='margin-left:90px;' type='submit' value='Izmeni'>
<?php echo form_close(); ?>
...
My Controller:
function verify_editing_phonebook()
{
if ($this->session->userdata('logged_in'))
{
if ($this->session->userdata('admin') == 1)
{
$this->form_validation->set_rules('ime_prezime', 'Ime i prezime', 'trim|required|xss_clean');
$this->form_validation->set_rules('telefon', 'Telefon', 'trim|required|xss_clean');
if ($this->form_validation->run() == TRUE)
{
$id = $this->uri->segment(3);
if (isset($id) and $id > 0)
{
$this->load->model('LoginModel');
$this->LoginModel->edit_phonebook($id);
redirect(site_url().'ImenikController/', 'refresh');
}
}
else {
$temp = $this->session->userdata('logged_in');
$obj['id'] = $temp['id'];
$data['records'] = $this->LoginModel->get_Username($obj);
$this->load->view('ErrorEditing', $data);
}
}
else {
$this->load->view('restricted_admin');
}
}
else {
$this->load->view('restricted');
}
}
My Model:
function edit_phonebook($id)
{
$data = array ('ime_prezime' => $this->input->post('ime_prezime'),
'ulica' => $this->input->post('ulica'),
'mesto' => $this->input->post('mesto'),
'telefon' => $this->input->post('telefon'));
$this->db->where('id', $id);
$this->db->update('pregled', $data);
}
That solution doesn't work.
I get the url: localhost/imenik114/ImenikController/verify_editing_phonebook
It is a blank (white) page. And not editing row in table.
Basic Debugging Strategies
(1) Have you created all the view files?
(2) Have you tested edit_phonebook($id) independently?
(3) What does redirect(site_url().'ImenikController/', 'refresh'); display?
Did you define the index function for ImenikController?
(4) What URL did you use when you say 'That solution doesn't work.' ?
(5) If your URL is: "localhost/imenik114/ImenikController/verify_editing_phonebook"
you did not type in id in your 3rd segment
(6) If you are not logged in, do you see the correct restricted view?
(7) If you are logged in and NOT admin, do you see the correct restricted_admin view?
Potential Bug
Looking at this part of your code:
if ($this->form_validation->run() == TRUE)
{
$id = $this->uri->segment(3);
if (isset($id) and $id > 0)
{
$this->load->model('LoginModel');
$this->LoginModel->edit_phonebook($id);
redirect(site_url().'ImenikController/', 'refresh');
}
// You need to handle the case of $id not set
else
{
// load a view with error page saying $id is missing...
}
}
if your form validates, and you don't pass in segment(3), your controller will not load a view, therefore, you will get a blank page.
You need to check the case of $id not present, see code.
Code Fix
One more detail: the statement $id = $this->uri->segment(3); will set $id either to the id number or FALSE, therefore, you don't need isset($id) in your if statement. I would write $id = $this->uri->segment(3,0); to set the default to 0 instead of FALSE to keep the logic a bit clearer.
Thanks for answer but I solved my problem somehow.
I made a link in my view:
Edit
And in view for editing:
<?php echo form_open('Controller/verify_editing_phonebook/'.$this->uri->segment(3)); ?>
Function verify_editing_phonebook passed trough validation and loading view.
Thanks once again and sorry for my English...

joomla 2.5 saving multiple select lists?

I'm trying to add a multiple select list to my backend component, but I can't seem to get it to work. I've tried searching the joomla forums and have tried what they've suggested, but it still doesn't work.
Here is what I have done:
/models/fields/categories.php
foreach ($result as $item) {
$options[] = JHtml::_('select.option', $item->id, $item->title);
};
$drawField = '';
$drawField .= '<select name="'.$this->name.'" id="'.$this->name.'" class="inputbox" size="10" multiple="multiple">';
$drawField .= JHtml::_('select.options', $options, 'value', 'text', $strVal, true);
$drawField .= '</select>';
return $drawField;
/models/forms/edit.xml
<field name="catid" type="categories" multiple="true" size="40" class="inputbox" label="COM_PRODUCTS_FORM_LBL_EDIT_CATID" description="COM_PRODUCTS_FORM_DESC_EDIT_CATID" required="true" filter="safehtml" />
/models/edit.php
protected function loadFormData()
{
$data = JFactory::getApplication()->getUserState('com_products.edit.edit.data', array());
if (empty($data)) {
$data = $this->getItem();
$data->catid = explode(',',$data->catid);
}
return $data;
}
/tables/edit.php
public function check() {
if (property_exists($this, 'ordering') && $this->id == 0) {
$this->ordering = self::getNextOrder();
}
$this->catid = implode(',',$this->catid);
return parent::check();
}
It saves the field catid as "Array" in the backend. Yet when I put in manually 143,148 as the field value, it doesn't highlight those fields, so obviously my implode/explode aren't working.. Any help would be appreciated!!
Thanks :)
Ok figured it out.. The issue was this: filter="safehtml" in the xml file if anyone else is having issues with the same thing... All is good now :)

Resources