How to submit form with Datatables - forms

I use Datatables to submit answers of questions from a survey. Each question is in new page, and the next is seen with the "Next" button. I want to have only one submit button and it has to appear in the end of all questions. In my code, it's under the table and is visible all the time. My biggest problem is that this submit button insert in db only the last question, but not all questions.
Please can you help me? :)
My view is:
<html>
<head>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.min.css" type="text/css" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#example').dataTable( {
"pagingType": "simple",
"lengthMenu": [[1], [1]],
"bSort": false,
"language": {
"paginate": {
"previous": true
}
}
} );
} );
</script>
</head>
<body>
<?php
echo form_open('index/survey_fill/' .$survey_id ); ?>
<table id="example" >
<thead>
<tr><th>Question</th></tr>
</thead>
<tbody>
<?php
echo validation_errors();
foreach ($survey as $row)
{
?>
<tr>
<td>
<?php echo "$row->question"; ?><br/>
<?php echo "<input type='hidden' name='question_id' value='$row->question_id' />"; ?>
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => '5'
);
echo form_radio($data);
echo " 5 ";
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => ' 4'
);
echo form_radio($data);
echo " 4";
</td></tr>
<?php
}
?>
</tbody>
</table>
<?php echo "<input type='hidden' name='question_id' value='$row->question_id' />"; ?>
<input type="submit" id="button" name = "submit" value="Submit" class="btn btn-success">
</form>
</div>
</body>
</html>
My model is:
public function survey_fill()
{
$answers=($this->input->post('answer'));
if (null !==($this->input->post('submit'))) {
$date = new DateTime("now");
foreach($answers as $question_id=>$answer)
{
$data = array(
'user_id'=>$this->session->userdata['user_id'],
'question_id'=>$question_id,
'answer'=>$answer,
'created_at'=>$date->format('Y-m-d H:i:s')
);
$this->db->insert('survey_answers', $data);
}
if($this->db->affected_rows() > 0)
{
return true;
}
return false;
}
}

I'm thinking Datatables is quite a lot of overkill for what you're trying to do. Personally, I'd output this in a set of divs and do a simple forward-back type button with jQuery toggle, which is a LOT less overhead. There's also very low-overhead paging solutions out there that could suffice. Remember, datatables is not only reformatting the table, but it has an encyclopedia of API calls that are loaded, plus the data model it holds. That's a LOT for a show/hide type test.
Regardless, the solution is pretty straightforward. Wrap your container (whatever it is, datatable or divs) with a <form> tag. Put the submit button at the end, and show/hide or enable/disable it via whatever means you want. Datatables has an API call that can tell you the current page, and you could key off that to enable your button. Since the button will be before you close the <form> it will automatically submit.
Alternative, you could wrap your container in the form, build a jQuery .on('click') event that serializes the form and submits it via Ajax if that was desired. The key if you go this route is to preventDefault() so the form doesn't auto-submit as is standard for html forms.

Related

insert date from datepicker to MySQL database in php

I'm trying to insert date from datepicker but the sql statement is not working imo.
here is the code:
if(isset($_POST['confirm']))
{
$order_finish_time = $_POST['order_finish_time'];
$note = $_POST['note'];
$finish_query = mysqli_query($link, "INSERT INTO orderdetails SET order_finish_time=$order_finish_time AND note=$note WHERE order_id=$order_id");
$order_r = mysqli_fetch_array($finish_query);
if(isset($order_r))
{
$result = mysqli_query($link, "UPDATE orderdetails SET order_status = 'Order_Finished' WHERE order_id=$order_id");
?>
<script>alert('Order confirmed!');</script>
<script>document.location = 'orderdetails.php';</script>
<?php
}
else
{
?>
<script>alert('Something wrong');</script>
<script>document.location = 'orderdetails.php';</script>
<?php
}
}
else part of the code is working and im getting something wrong message. Plese help me out if you can spot error in my code.
The form im using is:
<html>
<head>
</head>
<body>
<form class="form-horizontal" method="post">
<div class="row">
<div class="col-xs-12">
Order will be finished :
<input id="datepicker" class="form-control" name="order_finish_time" required/>
</div>
</div>
<button type="submit" name="confirm" id="confirm" class="btn btn-success btn-lg" style="width: 100%;">
<span class="glyphicon glyphicon-ok-sign"></span>
Confirm
</button>
</form>
<!-- datepicker -->
<script>
$( "#datepicker" ).datepicker({
dateFormat : 'yy-mm-dd'
});
</script>
</body>
</html>
here is the picture of my tables:
enter image description here
Your code seems to be incomplete in many ways. No jQuery and jQuery UI is defined in the head.
Your form is missing the field with the name text.
No database connection is made.
The variable $order_id is not defined in your code.
Use var_dump(mysqli_error_list($link)); after executing statements to see possible errors in your SQL. This is procedural style.
Your query is plain wrong. You cannot insert with a where clause, it is used for select, update and delete.
The correct insert query would be
$finish_query = mysqli_query($link, "INSERT INTO `orderdetails` (`order_finish_time`, `note`) VALUES ('$order_finish_time', '$note')");
Please explain what your program is supposed to do. It does not make sense the way it is written right now. This works, but since I do not know your intentions it may be -logically- wrong.
<?php
if (isset($_POST['confirm'])) {
$order_finish_time = $_POST['order_finish_time'];
$note = $_POST['note'];
$link = mysqli_connect('localhost', 'root', '', 'orderdetails');
$finish_query = mysqli_query($link, "INSERT INTO `orderdetails` (`order_finish_time`, `note`) VALUES ('$order_finish_time', '$note')");
$order_id = mysqli_insert_id($link);
if($finish_query === true)
{
$result = mysqli_query($link, "UPDATE `orderdetails` SET `order_status` = 'Order_Finished' WHERE `id`=$order_id");
?>
<script>alert('Order confirmed!');</script>
<script>document.location = 'orderdetails.php';</script>
<?php
}
else
{
?>
<script>alert('Something wrong');</script>
<script>document.location = 'orderdetails.php';</script>
<?php
}
}
?>

wp shortcode breaks get_post_thumbnail

I'm having some trouble with short code's breaking a featured image I have set on my home page in Wordpress (4.0). For some reason, when I paste in my shortcode in the wp-admin > page > edit > content for the home page, suddenly my featured image stops working. It's working until I paste in the shortcode and update the page, but then the image disappears and the_post_thumbnail() returns false. I've also tried get_the_post_thumbnail() without success.
Here's my code excerpt from "front-page.php":
<div class="small-12 medium-6 columns">
<?php while ( have_posts() ) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div class="small-12 medium-6 columns">
<?php if (has_post_thumbnail()) {the_post_thumbnail();} ?>
</div>
And here's the shortcode function from "functions.php":
// [random_testimonial]
function short_code_get_random_testimonial(){
$args = array( 'post_type' => 'testimonial', 'posts_per_page' => 1, 'orderby' => 'rand' );
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
$random_testimonial = get_the_content();
$author = get_the_title();
$rt = '<p class="quote">' . $random_testimonial;
$rt .= '</p><p class="right">– ' . $author . '</p>';
endwhile;
return $rt;
}
// Register the shortcodes.
add_shortcode( 'random_testimonial', 'short_code_get_random_testimonial' );
// Allow text widgets to contain shortcodes.
add_filter('widget_text', 'do_shortcode');
add_filter('the_content', 'do_shortcode');
Any ideas would be greatly appreciated.
I think I may have solved this one. It seems to have something to do with the fact that I was calling a custom post type with the shortcode, so by the time the_post_thumbnail() was called, the query had changed to refer to the custom post type included in the shortcode ("testimonial") rather than the parent post (in this case the home page). I revised my code as follows to catch the image before the shortcode is called, and all is working again:
<div class="small-12 medium-6 columns">
<?php while ( have_posts() ) : the_post(); ?>
<?php
// go ahead and get the post image in case [random_testimonial]
// shortcode is used in page content which will break the query.
if (has_post_thumbnail()) {$image = get_the_post_thumbnail();} ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div class="small-12 medium-6 columns">
<?php
// Echo post image from above.
if(isset($image)){echo $image;}
?>
</div>

Zend form elements coming from a database

Currently I'm stuck writing a edit function for an order page using zend framework
Here is the situation:
One order consist of multiple items
Eg Order Number 1
Consists of Items
OrderListId OrderId title Sent dateSent trackingNumber
1 1 Book A 0 12/12/12 44444
2 1 Book B 1 10/01/12 51223
3 1 Book C 0 01/02/12 33353
and so on...
Please notes: the table are stored in a database
I need to have a page where the user can edit title, Sent, dateSent and trackingNumber fields.
How can I use zend form to populate these fields for edit. Since I want to have one page they can edit all these orderlist items. Rather then the user have to click back and forward to edit each order list item individually.
What's the best approach to this situation?
Thanks so much in advance!
I suggest using ZF Data Grid.
I had a problem similar to this awhile back and I came up with a solution where I just appended an update link to the end of the table row and populated a form for update while still displaying current information.
The following code samples were built before I knew what I was doing with ZF so they may be a little messy. I ended up with what amounts to single view that handles all of my CRUD operations.
**All css selectors removed for clarity
The display view:
<?php if (isset($this->leadtracks)): ?>
<form method="post" action="/admin/track/deletetrack">
<table>
<tr>
<th colspan="5"><?php $this->tableHeader() ?></th>
</tr>
<tr>
<th>Select</th>
<th>Shift</th>
<th>Days Off</th>
<th>Slots</th>
<th> </th>
</tr>
<tr>
<?php
//begin foreach loop using alternate syntax
foreach ($this->leadtracks as $lt):
?>
<td><input type="checkbox" name="trackid[]"
value="<?php
//trackid as value for checkbox
echo $lt->trackid
?>" style="width: 2px" /></td>
<td><?php
//find and display shift name
$lt->getShift();
?></td>
<td><?php $lt->getDays(); ?></td>
<td><?php echo $this->escape($lt['qty'])?></td>
<td><a href="<?php
//link to update action passing trackid and bidlocationid values
echo $this->url(array('module' => 'admin',
'controller' => 'track',
'action' => 'updatetrack',
'trackid' => $lt['trackid'],
'bidlocationid' => $lt['bidlocationid']))
?>">Update</a></td>
</tr>
<?php endforeach ?>
<tr>
<th colspan="5">
<input type="submit" name="submit" value="Delete Selected" />
</th>
</tr>
</table>
<?php endif; ?>
<!-- further code removed for brevity -->
</form>
The updateAction(), only one action for demonstration:
public function updatetrackAction() {
//get form set new label and assign to view
$form = new Admin_Form_Track();
$form->submit->setLabel('Update Track');
$form->addTrack->setLegend('Update A Track');
$this->view->form = $form;
try {
//check is post and is valid and get values from form
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$trackId = $data['trackid'];
//save update data to database
$update = new Model();
$update->update($trackId, $data);
//generate meesage
$this->_helper->flashMessenger->addMessage(Zend_Registry::get('config')
->messages->trackupdate->successful);
$this->getHelper('Redirector')->gotoSimple('addtrack');
} else {
//if form is not vaild populate form for resubmission
$form->populate($this->getRequest()->getPost());
}
} else {
//if form is not posted populate form with data from database
$trackId = $this->_getParam('trackid', 0);
if ($trackId > 0) {
$z = new Model();
$y = $z->getTrack($trackId)->toArray();
$form->populate($y);
}
}
} catch (Zend_Exception $e) {
$this->_helper->flashMessenger->addMessage($e->getMessage()->getTrace());
$this->_redirect($this->getRequest()->getRequestUri());
}
}
The addAction() and the deleteAction() are very similar and use the same view script called through the action() helper. The result is a page in which add, update and delete actions are performed from what the user perceives as one page(check box for multiple deletes and a link for update, every refresh displays current data). Although I do move the form from side to side as a sort of visual clue, though it really doesn't matter as all actions are available on each page.
the update view:
<div>
<h3><?php echo ucwords($this->escape(strtoupper($this->station) . ' - ' . $this->bidloc)); //page header ?></h3>
<?php echo $this->form //edit/add form ?>
</div>
<div>
<?php echo $this->action('displaytrack', 'track', 'admin') //display view ?>
</div>
I'm sure this can be done with the partial() view helper, without using the action() helper and I'm sure it can be done inline, I just haven't taken the time to figure out how to do it.
good Luck.

Zend Framework Custom Forms with viewScript

I am having some problems working out how to use custom forms in Zend Framework.
I have followed various guides but none seem to work. Nothing at all gets rendered.
Here is the bits of code that I am trying to use (All code below is in the default module). I have simplified the code to a single input for the test.
applications/forms/One/Nametest.php
class Application_Form_One_Nametest extends Zend_Form {
public function init() {
$this->setMethod('post');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Box Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Submit Message');
$submit->setAttrib('id', 'submitbutton');
$submit->setAttrib('class', 'bluebutton');
$this->addElements(array($name, $submit));
}
}
application/views/scripts/one/formlayout.phtml
<form action="<?= $this->escape($this->form->getAction()) ?>" method="<?= $this->escape($this->form->getMethod()) ?>">
<p>
Please provide us the following information so we can know more about
you.
</p>
<? echo $this->element->name ?>
<? echo $this->element->submit ?>
</form>
application/controllers/IndexController.php
public function formtestAction() {
$form = new Application_Form_One_Nametest();
$form->setDecorators(array(array('ViewScript', array('viewScript' => 'one/formlayout.phtml'))));
$this->view->form = $form;
}
application/views/scripts/index/formtest.phtml
<h1>Formtest</h1>
<?
echo $this->form;
?>
The above code does not throw any errors or render any part of formlayout.phtml including the form tags or text between the p tags.
Can anybody tell me what I might be doing wrong?
I think the problem is your form element's decorator. You should set the decorator to ViewHelper and Error only. It works for me at least.
Here is the code I used and it should work
applications/forms/Form.php
class Application_Form_Form extends Zend_Form {
public function loadDefaultDecorators() {
$this->setDecorators(
array(
array(
'ViewScript',
array(
'viewScript' => 'index/formlayout.phtml',
)
)
)
);
}
public function init() {
$this->setAction('/action');
$this->setMethod('post');
$this->addElement('text', 'name', array(
'decorators' => array('ViewHelper', 'Errors')
));
}
}
application/views/scripts/index/formlayout.phtml
<form action="<?php echo $this->element->getAction(); ?>" method="<?php echo $this->element->getMethod(); ?>">
<div>
<label for="name">Box Name</label>
<?php echo $this->element->name; ?>
</div>
<input type="submit" value="Submit Message" id="submitbutton" class="bluebutton">
</form>
application/views/scripts/index/index.phtml
<!-- application/views/scripts/index/index.phtml -->
<?php echo $this -> form; ?>
application/controllers/IndexController.php
public function indexAction() {
$form = new Application_Form_Form();
$this -> view -> form = $form;
}
Here is a very simple example to get you going adapted from this article.
The form:-
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('POST');
$this->setAction('/');
$text = new Zend_Form_Element_Text('testText');
$submit = new Zend_Form_Element_Submit('submit');
$this->setDecorators(
array(
array('ViewScript', array('viewScript' => '_form_test.phtml'))
)
);
$this->addElements(array($text, $submit));
$this->setElementDecorators(array('ViewHelper'));
}
}
The order in which setDecorators(), addElements() and setElementDecorators() are called is very important here.
The view script _form_test.phtml can be called anything you like, but it needs to be in /views/scripts so that it can be found by the renderer.
/views/scripts/_form_test.phtml would look something like this:-
<form id="contact" action="<?php echo $this->element->getAction(); ?>"
method="<?php echo $this->element->getMethod(); ?>">
<p>
Text<br />
<?php echo $this->element->testText; ?>
</p>
<p>
<?php echo $this->element->submit ?>
</p>
</form>
You instantiate the form, pass it to the view and render it as usual. The output from this example looks like this:-
<form id='contact' action='/' method='post'>
<p>
Text<br />
<input type="text" name="testText" id="testText" value=""></p>
<p>
<input type="submit" name="submit" id="submit" value="submit"></p>
</form>
That should be enough to get you started creating your own forms.
Usually, if you don't see anything on the screen it means that some sort of error happened.
Maybe you have errors turned off or something, maybe not. I'm just trying to give you ideas.
The only things I could spot where the following.
In the below code, you have to still specify the form when trying to print out the elements.
<form>
action="<?php $this->escape($this->element->getAction()) ?>"
method="<?php $this->escape($this->element->getMethod()) ?>" >
<p>
Please provide us the following information so we can know more about
you.
</p>
<?php echo $this->element->getElement( 'name' ); ?>
<?php echo $this->element->getElement( 'submit' ) ?>
</form>
As vascowhite's code shows, once you are inside the viewscript, the variable with the form is called element. The viewscript decorator uses a partial to do the rendering and thus it creates its own scope within the viewscript with different variable names.
So, although in your original view it was called $form, in the viewscript you'll have to call it element.
Also, maybe it was copy/paste haste, but you used <? ?> tags instead of <?= ?> or <?php ?> tags. Maybe that caused some error that is beyond parsing and that's why you got no output.

accessing request parameters inside paginator partial

1)how do i access the search $keyword inside the paginator partial to create search freindly urls ? clearly, passing the keyword as $this->view->paginator->keyword doesnt work.
2) currently, the search button's name is also send as param . for eg when searching for 'a' the url becomes http://localhost/search/index/search/a/submit//page/2. any way to stop this ?
Search Form:
<form id="search" method="get" action="/search">
<input id="searchfield" onClick="this.value=''" type="text" name="search" value="Search wallpapers"/>
<input id="searchbutton" type="submit" value="" name="submit"/>
</form>
Action inside searchController:
public function indexAction()
{
$keyword=$this->_request->getParam('search');
$alnumFilter=new Zend_Filter_Alnum();
$dataModel=new Model_data();
$adapter=$dataModel->fetchPaginatorAdapter("title LIKE '%".$keyword."%'", '');
$paginator=new Zend_Paginator($adapter);
$paginator->setItemCountPerPage(18);
$page=$this->_request->getParam('page', 1);
$paginator->setCurrentPageNumber($page);
$this->view->paginator=$paginator;
$this->view->keyword=$keyword;
}
index.phtml (view) file:
partialLoop('wallpaper/table-row.phtml',$this->paginator) ;?>
<div id="page-links">
<?= $this->paginationControl($this->paginator,'Sliding','partials/search-pagination-control.phtml');?>
</div>
search-paginator-control.phtml file:
if ($this->pageCount){
$params=Zend_Controller_Front::getInstance()->getRequest()->getParams();
if(isset($this->previous)){
?>
Previous
<?php
}
else{
?> Previous <?php
}
foreach($this->pagesInRange as $page){
if($page !=$this->current){
?>
<?=$page;?>
<?
}
else{
echo $page;
}
}
if(isset($this->next)){
?>
Next
<?php
}
else{
?> Next <?php
}
}
The paginationControl view helper accepts a 4th parameter, that is a array of parameters, so in your case you could do something like this:
<div id="page-links">
<?= $this->paginationControl($this->paginator,'Sliding','partials/search-pagination-control.phtml', array('keyword' => $this->keyword));?>
</div>
Then you access it inside your pagination using $this->keyword.