CodeIgniter validation and checkbox - codeigniter

i have problem with my checkbox i want to add validation but i don't know how should look my name field in validation rule.
My view
<?php
foreach( $tab1 as $row){
?>
<a>
<input type="checkbox" name="<?php echo 'id_user_'.$row->id_user; ?>" value=" <?php echo $row->id_user; ?>" />
</a>
<?php
When i do this i get result (name of the checkbox )for example:
id_user_1
id_user_2
id_user_3
Now i want to add validation but:
$this->form_validation->set_rules(' WHAT SHOULD I WRITE HERE ??? ', 'User','required');
EDIT:
$this->form_validation->set_rules('id_uzytkownika', 'Uzytkownika','required');
if ($this->form_validation->run())
{
$todo = array(
'tytul_projektu'=>$this->input->post('tytul_projektu'),
'opis_projektu'=>$this->input->post('opis_projektu'),
'data_zakonczenia'=>$this->input->post('datepicker')
);
$user_projekty = array(
'id_uzytkownika'=>$this->input->post('id_uzytkownika'),
'id_projektu'=>$this->input->post('id'),
);
$users = array();
foreach($_POST as $key => $value)
{
if(strpos($key, 'id_uzytkownika') === 0)
{
$users[] = $value;
}
}
$this->Todo_model->add($todo,$user_projekty,$users);
VIEW:
<?php
foreach( $tab1 as $row){
?>
<a>
<input type="checkbox" name="<?php echo 'id_uzytkownika['.$row->id_uzytkownika.']'; ?>" value="<?php echo $row->id_uzytkownika; ?>" />
MODEL:
function add($data,$data2,$users)
{
$this->db->insert('projekty', $data);
$id = $this->db->insert_id('projekty');
$data2['id_projektu'] = $id;
$query = $this->db->query("SELECT * FROM uzytkownicy");
foreach($users as $user) {
$data2['id_uzytkownika'] = $user;
$this->db->insert('projekty_uzytkownicy', $data2); }
return $query->result();
}

There are a few approaches you can take with this. Using your existing code, the first would be to create a loop that defines all unique input names.
foreach($users as $user) {
$this->form_validation->set_rules('id_user_'.$user->id_user, 'User','required');
}
However, this logic would require every checkbox to be checked. Which I am not sure in what circumstance this would be used for.
Another approach would be to change your html a little bit.
Instead of
<input type="checkbox" name="<?php echo 'id_user_'.$row->id_user; ?>"
value="<?php echo $row->id_user; ?>" />
you can try using something like
<input type="checkbox" name="<?php echo 'id_user['.$row->id_user.']'; ?>"
value="1" />
This way you could make a form validation rule based on id_user instead of unique names.

Related

submit multiple inputs within a forloop in codeigniter

My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}

how make to form search in CodeIgniter using two fields

I want to make a search form in Codeigniter using two fields.
But I'm confused about making the controller and model.
View:
echo form_open("home/pencarian","class='form-inline navbar-search'");
<input id="srchFld" class="srchTxt" name="keyword" type="text" value=" echo $this->session->userdata("keyword");" />
<select class="srchTxt" name="kategori">
<option>All</option>
foreach ($kat as $kategori){
$id = $kategori['id'];
$nama_kategori = $kategori['nama_kategori'];
$created_at = $kategori['created_at'];
<option value=" echo $id; ?>"><?php echo $nama_kategori; </option>
}
</select>
echo form_submit('action', 'Cari', "class='btn btn-primary'");
echo form_close();
How do I make the controller and model?
Model example_model.php
public function search($search_txt, $search_category) {
$this->load->database();
$sql = "select * from search_table where search_field = ? and search_category = ?;";
$query = $this->db->query($sql, array($search_txt, $search_category));
return $query->result();
}
Controller home
public function pencarian() {
$this->load->model('example_model', 'm');
$search_txt = $this->input->post('srchFld');
$search_category = $this->input->post('kategori');
$data['search_result'] = $this->m->search($search_txt, $search_category);
$this->load->view('example_view', $data);
}
View example_view
<?php foreach($search_result as $r): ?>
<div><?php echo $r->field1 . ' ' . $r->field2; ?></div>
<?php endforeach; ?>

Checkout Observer Modification 1.7+

this is about me tinkering again to see if this modification works:
I modified the Mage/Checkout/Model/Observer.php:
public function salesQuoteSaveAfter($observer)
{
$quote = $observer->getEvent()->getQuote();
Start of added code --- > $post = Mage::app()->getRequest()->getPost();//Mage::app()->getRequest()->getPost();
if(isset($post['shipping']['email'])){
if(isset($_SESSION['emailadd'])){
unset($_SESSION['emailadd']);
$_SESSION['emailadd'] = 'test2#mail.com';//$post['shipping']['email'];
}else{
$_SESSION['emailadd'] = 'test#mail.com';//$post['shipping']['email'];
}
}else{
if(isset($_SESSION['emailadd'])){
unset($_SESSION['emailadd']);
$_SESSION['emailadd'] = 'test3#mail.com';//$post['shipping']['email'];
}else{
$_SESSION['emailadd'] = 'test4#mail.com';//$post['shipping']['email'];
}
} <--End of added code;
/* #var $quote Mage_Sales_Model_Quote */
if ($quote->getIsCheckoutCart()) {
Mage::getSingleton('checkout/session')->getQuoteId($quote->getId());
}
}
the problem is this code: is returning nothing which sets the session['emailadd'] = test4#mail.com
$post = Mage::app()->getRequest()->getPost();
if my code is in the wrong method, how do I add a salesQuoteSaveBefore() method that is called before sending the data in the database? is there an XML to configure before doing so?
because first what I'm aiming at is just to get the input data or post data from the onepage/checkout inputs specially the shipping[email] input, don't tell me that there is none because there is:
<li>
<div class="input-box">
<label for="shipping:emailadd"><?php echo $this->__('Email Address') ?> <span class="required">*</span></label><br />
<input type="text" name="shipping['email']" id="shipping:emailadd" value="<?php echo $this->htmlEscape($this->getAddress()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="validate-email required-entry input-text" />
</div>
<div class="input-box">
<label for="shipping:emailadd"><?php echo $this->__('Confirm Email') ?> <span class="required">*</span></label><br />
<input type="text" name="shipping[emailconfirm]" id="shipping:emailconfirm" value="<?php echo $this->htmlEscape($this->getAddress()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="validate-email required-entry input-text" />
</div>
</li>
all I want to get is this one single shipping[email] input, it's kinda buggy because I'm stuck with for so long already. but I can't find a way to get it's value after onepage/checkout is submitted.
Any help would be appreciated.
First thing is you were editing core files. This is not appreciated.
You can get shipping email easily from controllers. Using Event Absorber is good method than over writing files. But that is hard to compare over writing .
Just overwrite the OnepageController.php at core->Mage->checkout->controllers.
Here is the code,
include_once("Mage/Checkout/controllers/OnepageController.php");
class Pakagename_Modulename_OnepageController extends Mage_Checkout_OnepageController
{
public function saveBillingAction()
{
if ($this->_expireAjax()) {
return;
}
if ($this->getRequest()->isPost()) {
// $postData = $this->getRequest()->getPost('billing', array());
// $data = $this->_filterPostData($postData);
$data = $this->getRequest()->getPost('billing', array());
$customerAddressId = $this->getRequest()->getPost('billing_address_id', false);
if (isset($data['email'])) {
$data['email'] = trim($data['email']);
}
Here the problem is customer may use different email for shipping and billing. So you need to checkout both shipping and billing save actions.
add to session
$email = $data['email'];
Mage::getSingleton('core/session')->setMyValue($email);
Then here I assume that you were trying to edit order e-mail template.
1) Edit sendNewOrderEmail() function located in
app/code/core/Mage/Sales/Model/Order.php
$my_email = Mage::getSingleton('core/session')->getMyValue();
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
'my_email' => "$my_email" //New custom value
));
Then hereafter you can fetch that email like this
{{ var my_email }}
If you want edit invoice template then you should find out corresponding function to define custom email variable. That's all..!

Updating one data on datagrid using checkbox codeigniter

i have some issue when i updating every single or one data using checkbox. i want to do is to update only the selected checkbox updated. How do I stop the foreach from running if a checkbox has not been checked.
this is my model
function save_cargo_details() {
$data = array();
$waybillno = $this->input->post('waybillno');
$quantity = $this->input->post('quantity');
$waybilldate = $this->input->post('waybilldate');
$declared_value = $this->input->post('declared_value');
$consignee = $this->input->post('consignee');
$count = count($waybillno);
if(empty($waybillno)){
}else{
for ($i = 0; $i < $count; $i++) {
$data = array(
'waybillno' => $waybillno[$i],
'quantity' => $quantity[$i],
'waybilldate' => $waybilldate[$i],
'declared_value' => $declared_value[$i],
'consignee' => $consignee[$i],
);
// SUBRACT REMAINING_QUANTITY //
$this->db->select('wd.remaining_qty');
$this->db->where('wd.waybillno',$waybillno[$i]);
$this->db->from(self::WAYBILL_DETAILS_TABLE. " as wd");
$query = $this->db->get()->row();
$qty = $query->remaining_qty;
$remaining = abs($data['quantity'] - $qty);
$this->db->where('waybillno',$waybillno[$i]);
$this->db->set('remaining_qty',$remaining);
$this->db->update(self::WAYBILL_DETAILS_TABLE);
// INSERT DATA //
$this->db->insert('sys_cargodetails', $data);
$this->session->set_flashdata('success', '<p id="success_message">Record has been successfully saved.</p>');
}
}
}
this is my controller
public function create_cargo_manifest(){
$core_model = new Core_m;
$core_model->save_cargo_details();
redirect('core/cargo_lookup/');
}
this is my view
<?php foreach($waybill_header as $waybill_header) { ?>
<?php echo form_open('core/create_cargo_manifest'); ?>
<tr style="text-align: center;">
<td><input type="checkbox" name="waybillno[]" value="<?php echo $waybill_header->waybillno; ?>"></td>
<td><?php echo $waybill_header->waybillno; ?></td>
<td><?php echo $waybill_header->waybilldate; ?><input type="hidden" value="<?php echo $waybill_header->waybilldate; ?>" name="waybilldate[]"></td>
<td><input type="text" size="5" value="<?php echo $waybill_header->remaining_qty; ?>" name="quantity[]">
<input type="hidden" value="<?php echo $waybill_header->declared_value; ?>" name="declared_value[]">
<input type="hidden" value="<?php echo $waybill_header->consignee; ?>" name="consignee[]">
</td>
</tr>
<?php } ?>
You can give an extra field in the database for the checkbox.If the check box is checked it takes 1 as the value and if unchecked 0 as the value.Give the default value as per your requirement.If you want every checkbox to be checked give 1 as default else otherwise.Then you will just need to put a condition before foreach loop,i.e. if value of checkbox is 1 run the foreach loop else not.

Joomla Component not saving data

I have a component that used to work (Without setting HTML tags to the description) and now after trying to get the HTML formatting to work it won't save.
com_lot\views\lot\tmpl\form.php:
<?php defined('_JEXEC') or die('Restricted access');
$document =& JFactory::getDocument();
$document->addScript('includes/js/joomla.javascript.js');
require_once(JPATH_ADMINISTRATOR .DS. 'components' .DS. 'com_jce' .DS. 'helpers' .DS. 'browser.php');
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<script language="javascript" type="text/javascript">
function submitbutton(pressbutton) {
var form = document.adminForm;
if (pressbutton == 'cancel') {
submitform( pressbutton );
return;
}
<?php
$editor =& JFactory::getEditor();
echo $editor->save( 'description' );
?>
submitform(pressbutton);
}
</script>
...
<tr>
<td width="100" align="right" class="key">
<label for="description">
<?php echo JText::_( 'Description' ); ?>:
</label>
</td>
<td>
<?php
$editor =& JFactory::getEditor();
echo $editor->display('description', $this->lotdata->description, '550', '400', '60', '20', false);
?>
</td>
</tr>
...
<input type="hidden" name="option" value="com_lot" />
<input type="hidden" name="lotid" value="<?php echo $this->lotdata->lotid; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="controller" value="lot" />
<?php echo JHTML::_( 'form.token' ); ?>
<button type="button" onclick="submitbutton('save')"><?php echo JText::_('Save') ?></button>
<button type="button" onclick="submitbutton('cancel')"><?php echo JText::_('Cancel') ?></button>
</form>
com_lot\models\lot.php:
function store($data)
{
// get the table
$row =& $this->getTable();
// Bind the form fields to the hello table
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Make sure the hello record is valid
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the web link table to the database
if (!$row->store()) {
$this->setError( $row->getErrorMsg() );
return false;
}
return true;
}
function save()
{
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
// get the model
$model =& $this->getModel();
//get data from request
$post = JRequest::get('post');
$post['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
// let the model save it
if ($model->store($post)) {
$message = JText::_('Success');
} else {
$message = JText::_('Error while saving');
$message .= ' ['.$model->getError().'] ';
}
$this->setRedirect('index.php?option=com_lot', $message);
}
Any help appreciated.
Edit: I have seen stuff about JForms and having XML files... is this applicable? I haven't found anywhere that says what they're used for, just what types there are...
I found the problem (once I'd cleaned up the code a bit) was that in the article I was following (http://docs.joomla.org/How_to_use_the_editor_in_a_component) missed changing store() to store($data).
Because the pages redirect etc it doesn't die and error out. Thanks to for Jan for your help.

Resources