submit multiple inputs within a forloop in codeigniter - 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();
}

Related

Search is not working in codeigniter

i did search like this but it is not taking passed value in text box,can any one help me to solve this issue..thanks in advances........my model query is correct or any error is there......
if i enter in search term it is redirecting to search results page but it is showing blank results.......and it is saying invalid argument supplied for foreach()
if i print last_query() in that it is showing Like below.....
SELECT * FROM (`clients`) WHERE `clientName` LIKE '%%'
This is My Controller:
class Client extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("client_model");
$this->load->model("interview_model");
$this->load->model("candidate_model");
$this->load->model("requirement_model");
}
function search()
{
$search_term = $this->input->post('search');
$data['query'] = $this->client_model->search_client($search_term);
echo "<pre>"; print_R($this->db->last_query()); exit;
$data['page_title'] = "Search Results";
$this->layout->view("client/search",$data);
}
}
Model:
function search_client($search_term)
{
$this->db->select('*');
$this->db->from('clients');
$this->db->like('clientName',$search_term);
// Execute the query.
$query = $this->db->get();
// Return the results.
return $query->result_array();
}
This is form in index.php(View):
<form action="<?php base_url();?>client/search">
<input type="text" name="search" id="search" style="width:180px" placeholder="Search here..." />
<input type="submit" value="Search" name="submit" class="btn btn-primary btn-sm" /></form>
This is search.php(view):
<?php foreach($query as $client){ ?>
<tr>
<td><?php echo $client->clientName;?></td>
<td><?php echo $client->clientSName; ?></td></td>
<td>
<?php } ?>
change this line:
<form method="POST" action="<?php base_url();?>client/search">
to this:
<form action="<?php echo base_url();?>client/search">
and try the following approch:
function search_client($search_term){
$this->db->select('*');
$this->db->from('clients');
$this->db->like('clientName',$search_term);
// Execute the query.
$query = $this->db->get();
if($query->num_rows()>0)
return $query->result();
else
return false;
}

CodeIgniter validation and checkbox

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.

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..!

can't POST data from <textarea> in codeigniter

I have been trying to retrieve this data from a textarea using post, but i keep geeting no data back. any help would be appreciated.
Here is my form
<?php echo validation_errors(); ?>
<?php echo form_open('s2e/contactValidation'); ?>
<ul>
<li><label>Subject<input type="text" id="emailsubject" name="subject" placeholder="example#site.com" width="200"></label></li>
<li><label>From<input type="email" id="emailfrom" name="from" ></label></li>
<li><label>Message</label><textarea id="message" name="message" rows="6" cols="200" form="contact" ></textarea></li>
</ul>
<button type"submit" name="sendemail">Send</button>
</form>
My controller looks like this
public function contactValidation(){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div id="rerror">', '</div>');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
$this->form_validation->set_rules('from', 'From', 'trim|required|valid_email');
$this->form_validation->set_rules('message', 'Message', 'trim|required');
$subject = $this->input->post('subject');
$from = $this->input->post('from');
$message = $this->input->post('message');
if($this->form_validation->run() == FALSE)
{
print_r('failed');
} else {
print_r('good');
}
var_dump($subject);
var_dump($from);
var_dump($message);// this is the culprit that's failing
}
Any help would be appreciated
Why don't you use Codeigniter's Form Helper:
<?php
echo validation_errors();
echo form_open('s2e/contactValidation');
echo form_labe('Subject', 'subject');
echo form_input('subject', 'Value Here', 'id="" placeholder=""');
echo form_label('Email', 'email');
echo form_input('email', '', 'attributes=""');
echo form_textarea('msg', '')
echo form_submit('submit', 'Send Form');
echo form_close();
?>

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