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 ; }
Related
In this codeigniter model i have this query testing if value entered in input exists in database..
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Behold the controller i'd like to display value grabbed in input in view inscription.php
function search()
{
$data['row'] = $this->site_model->get_search_form();
$this->load->view('acceuil/aside');
$this->load->view('acceuil/inscription', $data);
}
My issue is how to display in that view input value and a form if this value exists in database ?
I have tried like this but i need help :
inscription view:
<?=form_open('navigation/search');?>
<input type="text" name="search1" id="search1" required />
<input type='submit' value='Display' />
<?=form_close();?>
I try to display the form like this but i don't know how to display as well the input value entered
<?php
if( $row > 0 )
{
?>
les champs du formulaire ici....
<?php
}else
{ }
?>
In your view you can check if the variable $row is not null (because it will be null when no rows are found):
if ($row !== null) {
// do stuff
}
You can modify the model function to return some other value if no rows are found, for example, by setting the $data to an empty array:
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
$data = array(); // <--- here
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
And then in the view you can simply loop the data:
foreach($row as $r) {
// do stuff
}
or you can implode the array to use as the input value:
<input type="text"
name="search1"
id="search1" required
value="<?php echo implode(' ', $row); ?>" />
You could also use html entities here, in case double quotes are possible to appear in what your model function returns (I have no idea what it returns).
you can access $data global object like this check
<?php
if( isset($row))
{
foreach($row as $v){
//Do the operations here
}
}else
{
//Do the operations here
}
?>
On my view I need to be able to get the hidden banner_image_id and use that in my $this->db->where('banner_image_id', $id) on my model function
When I update the image. It does not update to the correct row. Instead it update all rows with the same filename.
Question: On my model how can I make sure that my $this->db->where('banner_image_id', $id) updates correct rows.
I have done a vardump($id) and result is string(2) "63" which is correct but still updates every row the same. I tried update_batch also no luck.
Model Function
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
if (isset($banner_image_id)) {
foreach ($banner_image_id as $id) {
//var_dump($id);
//exit;
$data = array('banner_id' => $this->uri->segment(4),'banner_image' => $file_name);
$this->db->where('banner_image_id', $id);
//$this->db->where_in('banner_image_id', $id); // Tried No Luck
//$this->db->or_where_in('banner_image_id', $id); // Tried No Luck
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
}
View Table
<table>
<tbody>
<?php foreach ($banner_images as $img) { ?>
<tr>
<td>
<?php echo $img['banner_image_id'];?>
<input type="hidden" name="banner_image_id[]" value="<?php echo $img['banner_image_id'];?>">
</td>
<td>
<input type="file" name="banner_image[]" multiple size="20">
</td>
<td>
<img src="<?php echo base_url() . 'uploads/' . $img['banner_image'];?>" />
<input type="hidden" name="banner_image" value="<?php echo $img['banner_image'];?>">
</td>
</tr>
<?php }?>
<tbody>
</table>
Try to concatenate the id numbers in foreach loop and pass it where function at once.
Assuming that your id numbers are array(1,2,5,6).
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
if (isset($banner_image_id)) {
$bid = 'IN(';
foreach ($banner_image_id as $id) {
$bid .= $id . ',';
}
$bid = substr($bid, 0, -1) . ')'; //remove last comma and add closing paranthesis.
//The content of the variable $bid would be like
//IN(1,2,5,6)
$data = array('banner_id' => $this->uri->segment(4),'banner_image' => $file_name);
$this->db->where('banner_image_id', $id);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
Another Suggestion:
Convert $banner_image_id to a normal array in case of it is an associative array.
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
$bid = array();
if (isset($banner_image_id)) {
foreach ($banner_image_id as $id) {
$bid[] = $id;
}
$data = array('banner_id' => $this->uri->segment(4),
'banner_image' => $file_name);
$this->db->where_in('banner_image_id', $bid);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
I suggest you to make convertion in the controller section, not in model. The lines ending with // should be in the controller. You can easily pass $bid to edit_banner_image($file_name, $bid) function then.
public function edit_banner_image($file_name, $bid) {
$banner_image_id = $this->input->post('banner_image_id'); //
$bid = array();//
if (isset($banner_image_id)) {//
foreach ($banner_image_id as $id) { //
$bid[] = $id;//
}
$data = array('banner_id' => $this->uri->segment(4),
'banner_image' => $file_name);
$this->db->where_in('banner_image_id', $bid);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
Thus, you will have more readable code.
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");
}
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...
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 :)