Wordpress refresh table after insert new data - javascript

I really don't have any idea with this problem. I create new plug-in. Structure is easy:
div FreeQuotation_wrap2 (display the table), div FreeQuotation_wrap3 (insert new data). But after write new data and click submit page is refresh with old data.
When I click refresh I see information that it will resend data to database. It's ok- I prevent it with unique. Now I see new table with new record. How can I make it automatically?
I try 3 methods: onSubmit="" (doesn't work) and javascript (window.location = "...") and trick with session (i get error - headers already sent by...).
<?php
global $FreeQuotation_version;
global $wpdb;
echo $table_name;
global $today_date;
$table_name = $wpdb->prefix . 'free_quotation_kic';
?>
<div class="FreeQuotation_wrap">
<h2><div class="FreeQuotation_header"></div> FreeQuotation <?php echo $FreeQuotation_version; ?></h2><br>
</div>
<div class="FreeQuotation_wrap2">
<table class="widefat">
<?php
$FreeQuotation_table = $wpdb->get_results(
"
SELECT *
FROM $table_name
ORDER BY adding_date DESC
LIMIT 0 , 10
"
);
//nagłówek
echo '<thead><tr><th> ID </th><th> Quotation </th><th> Author </th><th> Display Date </th><th> Delete </th></tr></thead>';
//treść
foreach ( $FreeQuotation_table as $ogresults )
{
echo '<tr><td>';
echo $ogresults->id;
echo '</td><td>';
echo $ogresults->quotation;
echo '</td><td>';
echo $ogresults->author;
echo '</td><td>';
echo $ogresults->display_date;
echo '</td></tr>';
}
echo '<tfoot><tr><th> ID </td><th> Quotation </td><th> Author </td><th> Display Date </th><th> Delete </td></tr></tfoot>';
?>
</table>
</div>
<div class= "FreeQuotation_wrap3">
<form method="post" action="options.php">
<?php settings_fields('FreeQuotation_settings_filed'); ?>
<?php $options = get_option('FreeQuotation_options'); ?>
</form>
<?php
global $current_user;
$ufUserID = $current_user->ID;
$quotation = $_POST["quotation_textarea"];
$author = $_POST["autor_text"];
$display_date = $_POST["display_date"];
$url = $_SERVER['PHP_SELF'];
$adding_date = $today_date;
echo $url;
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'updateFeedback' ) {
$FreeQuotation = $wpdb->insert( 'wp_free_quotation_kic', array( 'quotation' => $quotation, 'author' => $author, 'display_date' => $display_date, 'adding_date' => $adding_date,) );
}?>
TUTAJ
<h3 class="widget-title">Add quotation</h3>
<form id='reloader' method='post' onSubmit="<?php echo $url;?>">
<table class="widefat" >
<thead>
<tr><th>Quotation</th><th>Author</th><th>Display Date</th></tr>
</thead>
<tbody>
<tr><td>
<textarea rows="1" cols="100" name="quotation_textarea" required></textarea>
</td>
<td>
<input type="text" name="autor_text" required></input>
</td>
<td>
<input type="text" name="display_date" required></input>
</td></th>
</tbody>
<tfoot>
<tr><th>
<input class="button button-primary" type="submit" name="submit" value="submit"/>
<?php wp_nonce_field( 'updateFeedback' ); ?>
<input name="action" type="hidden" id="action" value="updateFeedback"/>
</th></td>
</tfoot>
</table>
</form><br>
</div>
<div class="FreeQuotation_wrap4">
<h3>Zmiany:</h3>
</div>
<?php
?>
Can you help me? It's my first question hire (and I believe that the last...). Usually when I try to write a question I find the answer quickly :) Now I spend few hours with this problem and I doesn't see any solution...

I find simple solution - it's very easy and it's work. Maybe it's not professional but I don't have any other idea...
I change the order on the page. First is the form to add new position, the second is now the table with output. It means that I change two order:
<div class= "FreeQuotation_wrap3">
...
</div>
<div class="FreeQuotation_wrap2">
...
</div>
And this is my first answer on stackoverflow.com ;-)

Related

How to delete values from JSON object array in php?

I have a PHP code and JSON as shown below:
PHP Code:
<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
$output = array();
$output['en_desc']=$_POST['en_desc'];
$output['code']=$_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
}
?>
<?php if($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<input type="hidden" id="savechanges" name="savechanges" value="1">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
JSON:
{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
The following DOM is generated through the PHP/JSON code above:
DOM (HTML):
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
<input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
<input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.
JS code:
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
Problem Statement:
The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.
I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.
Step 1: User delete the row from the DOM on click of a delete button.
Step 2: On saving the form and rendering the page, that deleted row should not be present.
I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.
unset($data->code);
unset($data->en_desc);
You have a typo here:
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
it should be
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
Look at the "s" :)
Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:
<?php
if (isset($_POST['submit'])) {
$output = array();
$output['en_desc'] = $_POST['en_desc'];
$output['code'] = $_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}
?>
<?php if ($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit" name="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else {
echo 'Cannot read JSON settings file';
} ?>
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>

PHP programmatically navigate to new form using post [duplicate]

This question already has answers here:
PHP Redirect with POST data
(13 answers)
Closed 5 years ago.
I'm fairly new to PHP. I have a form that a user is filling in with various details (start date, end date, etc), called purchaseLicence.php. When it is submitted, the form action reloads itself to use PHP to validate the data.
If validation is passed, I want it to navigate to purchaseLicence2.php using the post method, as though the form had originally posted directly to purchaseLicence2.php.
I don't mind involving Javascript to do this, and I'm guess that it would need to be involved as it will end up looking at a different form to the one it would otherwise expect to be on.
This is my current purchaseLicence.php, the problem I get is that both purchaseLicence2.php and purchaseLicence.php are rendered after the form has been posted, and the browser is still pointing to purchaseLicence.php, rather that purchaseLicence2.php.
<?php
include_once('php/strings.php');
include_once('php/sprocs.php');
include_once('php/dates.php');
$encounteredValidationError = false;
$navigateAway=false ;
if (isset($_POST['process']))
{
if ($_POST['process'] == 1)
{
// if here, form has been posted
$ProductCode = $_POST['ProductCode'];
$StartDate = $_POST['StartDate'];
$EndDate = $_POST['EndDateHidden'];
// standardise the date formats to ISO8601
$StartDate = date("Y-m-d", strtotime($StartDate));
$EndDate = date("Y-m-d", strtotime($EndDate));
echo "<descriptive>" . PHP_EOL;
echo "ProductCode:" . $ProductCode . "<br/>" . PHP_EOL;
echo "StartDate:" . $StartDate . "<br/>" . PHP_EOL;
echo "EndDate:" . $EndDate . "<br/>" . PHP_EOL;
echo "</descriptive>" . PHP_EOL;
// validation to happen here
if (!$encounteredValidationError)
{
// so we're happy with the values. The form has just reloaded, so we need to put these back from $_POST into the input fields, so
// that we can call NavigateToPurchaseLicence2(), which will get them out of the input fields and post them to purchaseLicence2.php
// What a faff!
$data = array('ProductCode'=>$ProductCode, 'StartDate'=>$StartDate, 'EndDate'=>$EndDate);
$options = array(
'http'=>array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents('purchaseLicence2.php', false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
}
else
{
// hilite errors in the form here, how? form is not yet loaded
}
}
}
?>
</head>
<body>
<form method="post" action="purchaseLicence.php" id="form1">
<input type="hidden" name="process" value="1">
<table border=0 width=800px align=left style="margin: 0px auto;">
<tr> <!-- Product > -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Product</descriptive></td>
<td width="500px" bgcolor="lightgray">
<?php
// creates a dropdown of products
OutputSelectFromSQL("SELECT * FROM Product ORDER BY Description", "ProductCode", "ProductCode", "Description", "");
?>
</td>
</tr>
<tr> <!-- Licence Period -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Licence Period</descriptive></td>
<td width="500px" bgcolor="lightgray"><descriptive>1 year</descriptive></td>
</tr>
<tr> <!-- Start Date -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Start/End Dates</descriptive></td>
<td width="500px" bgcolor="lightgray">
<input type="date" style="font-family:verdana;font-size:12px;" name="StartDate" id="StartDate" onchange="updateEndDate(this.value);"></input>
<descriptive> to <a id="EndDate"></a></descriptive>
<input type="hidden" name="EndDateHidden" id="EndDateHidden"></input> <!-- this is used so we can post the end date to $_POST -->
</td>
</tr>
<tr> <!-- Next > -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive></descriptive></td>
<td width="500px" bgcolor="lightgray" align="right"><input type="submit" value="Next"></input></td>
</tr>
</table>
</form>
</body>
A simple example for a standard pattern to follow would be really useful.
I suggest you use $_SESSION to hold state between your forms, below is a very crude example, with 1 field on the first form which if good (numeric) , the entire form state is set into the session, then redirects to the second form to fill out additional fields. Very simple but you get the idea.
dataentry1.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// define form state
$form = [
'value' => $_POST,
'error' => []
];
// validate a_field
if (empty($form['value']['a_field'])) {
$form['error']['a_field'] = 'a_field is a required field!';
} elseif (!is_numeric($form['value']['a_field'])) {
$form['error']['a_field'] = 'a_field should be a number!';
}
// all good
if (empty($form['error'])) {
$_SESSION['form'] = $form;
exit(header('Location: dataentry2.php'));
}
}
?>
<?= (!empty($form['error']['global']) ? $form['error']['global'] : null) ?>
<form action="/dataentry1.php" method="post">
<lable>a_field:</lable>
<input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>">
<?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
<br>
<input type="submit" value="Submit">
</form>
dataentry2.php - requires the previous form to be filled out.
<?php
session_start();
// set form into scope from session
if (!empty($_SESSION['form'])) {
$form = $_SESSION['form'];
} else {
$_SESSION['form']['error']['global'] = 'You must fill out dataentry1 form first';
exit(header('Location: dataentry1.php'));
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// define form state
$form = [
'value' => array_merge($form['value'], $_POST),
'error' => []
];
// validate a_field
if (empty($form['value']['b_field'])) {
$form['error']['b_field'] = 'b_field is a required field!';
} elseif (!is_numeric($form['value']['b_field'])) {
$form['error']['b_field'] = 'b_field should be a number!';
}
// all good
if (empty($form['error'])) {
exit('Do something cool!');
}
}
?>
<form action="/dataentry2.php" method="post">
<lable>a_field:</lable>
<input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>" readonly="readonly">
<?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
<lable>b_field:</lable>
<input type="text" name="b_field" value="<?= (isset($form['value']['b_field']) ? htmlentities($form['value']['b_field']) : null) ?>">
<?= (!empty($form['error']['b_field']) ? '<br>'.$form['error']['b_field'] : null) ?>
<br>
<input type="submit" value="Submit">
</form>

Pass form variables to php. Prevent page refresh

I am working on a web site which displays some data that is retrieved from a database using php. Now, there are also other chekcboxes, which are included in a form. Based on the user input on these checkboxes, i wanted the div displaying the data to reload. For example, after a user checks one of the boxes and clicks apply, the div displaying should recompute the results. I realise that the form data must be passed onto an ajax function. Which would convert this form data into a json object and send it across to a php file. The php file can then access the form variables using $_POST['var']. I hope i have got the theory correct. Nevertheless, i have a number of problems during execution.
Firstly, the php code that deals with the form variables in on the same page as the form. I want to know how to direct the form data from the ajax function to this code.
Secondly, the ajax function is getting executed alright, the form is getting submitted, the page isn't reloading (as desired) but however, I am not able to access the submitted variables in the php code.
Here is my code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#filter_form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
<div style="float: left;margin-left: -175px;" class="box2">
<h2>Filter by :</h2>
<form id="filter_form" name="filter_form" href="#">
<!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
<h3>Location</h3>
<?php
//Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
//store them in arrays and use the arrays to display on screen.
$query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
$result = mysqli_query($con,$query);
$filter_array = array(5);
for($i=0; $i<5; $i++){
$filter_array[$i] = array();
}
while($row = mysqli_fetch_array($result)){
array_push($filter_array[0],$row['LOCATION']);
array_push($filter_array[1],$row['PARTY_TYPE']);
array_push($filter_array[2],$row['GENRE']);
array_push($filter_array[3],$row['HAPPY_HOURS']);
array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
}
for($i=0; $i<5; $i++){
$filter_array[$i] = array_unique($filter_array[$i]);
}
?>
<ul>
<?php
foreach($filter_array[0] as $location){
?>
<li>
<input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
<label for="f1"><?php echo $location?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Party Type</h3>
<ul>
<?php
foreach($filter_array[1] as $party_type){
?>
<li>
<input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
<label for="f2"><?php echo $party_type?></label>
</li>
<?php
}
?>
</ul>
<br><h3>Genre</h3>
<ul>
<?php
foreach($filter_array[2] as $genre){
?>
<li>
<input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
<label for="f3"><?php echo $genre?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Happy Hours</h3>
<ul>
<?php
foreach($filter_array[3] as $happy_hours){
?>
<li>
<input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
<label for="f4"><?php echo $happy_hours?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Outdoor/Rooftop</h3>
<ul>
<?php
foreach($filter_array[4] as $outdoor_rooftop){
?>
<li>
<input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
<label for="f5"><?php echo $outdoor_rooftop?></label>
</li>
<?php
$i=$i+1;
}
?>
</ul>
<br><br><br>
<div id="ContactForm" action="#">
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
</div>
<!--
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
-->
</form>
</div>
<div class="wrapper">
<h2>Venues</h2>
<br>
<div class="clist" id="clublist" href="#">
<?php
?>
<table id = "venue_list">
<tbody>
<?php
//Functions
//This function builds the query as every filter attribute is passed onto it.
function query_builder($var_name){
$append = strtoupper($var_name)." in (";
$i=0;
foreach($_POST[$var_name] as $array){
$append = $append."'{$array}'";
$i=$i+1;
if($i < count($_POST[$var_name])){
$append = $append.",";
}
else{
$append=$append.")";
}
}
return $append;
}
//We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
//We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
//The below 2 variables do the same.
$filter_set = 0;
$filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
$map_array = array();
if(isset($_POST['location'])){
$filter_set = 1;
}
if(isset($_POST['party_type'])){
$filter_set = 1;
}
if(isset($_POST['genre'])){
$filter_set = 1;
}
if(isset($_POST['happy_hours'])){
$filter_set = 1;
}
if(isset($_POST['outdoor_rooftop'])){
$filter_set = 1;
}
if($filter_set == 1){
$query = "Select * from venue_list where ";
$append_query=array(5);
$j=0;
foreach($filter_variables as $var){
if(isset($_POST[$var])){
$append_query[$j] = query_builder($var);
$j=$j+1;
}
}
$h=0;
//Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
//sequentially accessed.
foreach($append_query as $append){
$query=$query.$append;
$h=$h+1;
if($h < $j){
$query=$query." AND ";
}
}
}
else{
$query = "Select * from venue_list";
}
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</td>
<td>
<?php echo $name?>
</td>
<td style="display:none;">
<?php echo $location?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<br>
</div>
All the 3 components are part of index.php. Kindly notify me if the code is unreadable or inconvenient I will edit it. Awaiting a solution. Thank you.
in this case change your javascript code to
var submiting = false;
function submitmyforum()
{
if ( submiting == false )
{
submiting = true;
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
submiting = false;
}
});
}else
{
alert("Still working ..");
}
}
and change the form submit button to
<input name="filter_button" type="button" onclick="submitmyforum();" value="Apply" id="filter_button" class="button"/>
don't forget to change submit button type="submit" to type="button"

Concrete5 - Save array to DB

I created block wchich you can add in it dynamically a multiple names. When I cick save, and return to the block editing, I dont see my new added names. I think that is problem with save to database. Please can someone help me with it?
Here is my code:
controller.php:
<?php defined('C5_EXECUTE') or die("Access Denied.");
Loader::block('library_file');
class MultipleBlockController extends BlockController {
protected $btName = 'Multiply TEST';
protected $btDescription = 'Multiple add. TEST';
protected $btTable = 'btDCMultiple';
protected $btInterfaceWidth = "700";
protected $btInterfaceHeight = "450";
}
db.xml:
<?xml version="1.0"?>
<schema version="0.3">
<table name="btDCMultiple">
<field name="bID" type="I">
<key />
<unsigned />
</field>
<field name="inputs" type="C" size="16"></field>
</table>
</schema>
edit.php:
<?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<?php
$remove_row_icon = '<img src="'.ASSETS_URL_IMAGES.'/icons/remove_minus.png" class="remove_row" height="14" width="14" >';
$add_row_icon = '<img src="'.ASSETS_URL_IMAGES.'/icons/add_small.png" class="add_row" height="14" width="14" >';
?>
<!-- Zakladki -->
<ul id="ccm-autonav-tabs" class="ccm-dialog-tabs">
<li class="ccm-nav-active"><a id="ccm-autonav-tab-add" href="javascript:void(0);"><?php echo t('Edit')?></a></li>
</ul>
<!-- Odstep konfiguracja -->
<div style="padding: 10px">
<div class="ccm-autonavPane" id="ccm-autonavPane-add">
<h2>debug</h2>
<table>
<tr><td><?php echo 'Name';?></td><td></td></tr>
<?php
foreach($inputs as $a_name) { ?>
<tr>
<td><input type="text" size="10" name="inputs" value="<?php echo $a_name ?>" ></td>
<td><?php echo $add_row_icon; echo (' '); echo $remove_row_icon;?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.add_row').live('click',function(){
var copy_of_row = $(this).closest('tr').clone();
$(copy_of_row).find('input').val('');
$(this).closest('tr').after(copy_of_row);
});
$('.remove_row').live('click',function(){
$(this).closest('tr').remove();
});
});
</script>
view.php:
<?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<div>
<?php echo $inputs ?>
</div>
Another question: How can I load an array from the DB?
You have several problems in your code:
if your field inputs is going to repeat itself, you need to add
brackets [] to its name so it becomes name="inpust[]"
In your database table, the field bID contains the block ID and it's a key
field meaning only one row in your db can have that value. In your
case, if you have 3 inputs, you will have 3 rows with the same bID
which is impossible.
I suggest you look at the core slideshow block for an example of saving multiple values for one block by using 2 separate tables.
Concerning your other question once you load the database helper you can do
$rows = $db->getArray($sql,$vals);
Where $rows will contain your array of values, $sql is your sql call (SELECT * FROM whatever_table...) and $vals (optional) contains filtering values to use in your sql.

handling multiple buttons with same name and value in one form

I have multiple submit buttons on a site. They used to move elements up and down and I want to be them in one whole form in case of the user changes meanwhile some other values so everything is saved. The Problem now is I need the element ID of the button which was clicked.
So here is the code in the loop :
div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
And onclick of that specific button in the for loop he should write this code first so I know which element has to be moved
echo '<input type="hidden" name="change_element_id" value="'.$elements[$z]['element_id'].'" >';
I'm also open for another solution of this problem.
Ok I solved it like that now
Here you process the input:
// Select Operation
if(isset($_POST['edit_form_operation_up'])) {
echo "move up id ";
$operation = array_keys($_POST['edit_form_operation_up']);
echo $operation['0'];
}
else if(isset($_POST['edit_form_operation_down'])) {
echo "move down id ";
$operation = array_keys($_POST['edit_form_operation_down']);
echo $operation['0'];
}
And this is in the for loop for infinite Elements the input with same value and name.
<?php $elements = $fdb->get_elements($form[$i]['form_id']);
for($z = 0; $z < sizeof($elements); $z++) {
?>
<tr>
<td><div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation_up[<?php echo $elements[$z]['element_id']; ?>]" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation_down[<?php echo $elements[$z]['element_id']; ?>]" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
</td>
<td><?php echo $elements[$z]['element_id']; ?> </td>
<td></td>
<td></td>
</tr>
<?php } ?>
In case of somebody finds this topic and want to find a good solution.
Greetings

Categories