Here is my function
function yyy_hero_image_option_callback() {
$hero_options = get_option( 'hero_options' );
$count=count($hero_options);
$totalimg=$count-4;
$html = '<div id="upload_yyy_sets">';
for($i=1;$i<=$totalimg;$i++){
if( isset( $hero_options['upload_yyy_link_1'] ) && $hero_options[ 'upload_yyy_link_1' ] ) {
$html .= '<div id="yyyclonedInput'.$i.'" class="yyyclonedInput">';
$html .= '<input id="cs_product_menu_yyy_src_'.$i.'" type="text" size="36" name="hero_options[upload_yyy_link_'.$i.']" value="' . $hero_options['upload_yyy_link_'.$i.''] . '" /> <input id="cs_product_menu_yyy_src_'.$i.'_yyybutton" type="button" value="Add / Change" class="button-secondary yyy-upload-button" /> <div class="button yyyremove">-</div>';
$html .= '</div>';
}
}
$html .= '</div>';
echo $html;
?> <div class="button yyyclone">Add an Image</div> <?php
}
Along with a little jquery, this worked out the amount of arrays, deleted the number by 4 and then displayed the amount of divs based on the resulting number. This has been working fine but now i've added another slideshow and it needs to be worked out differently.
Now here is my new function
function yyy_hero_image_option_callback() {
$hero_options = get_option( 'hero_options' );
foreach($hero_options as $key => $value){
if (strpos($key, 'yyy')) {
var_dump($value);
}
}
}
This new function just find the arrays that have the characters yyy in them.
How can I count the amount of arrays and then display them like before?
Thanks
UPDATE: Here's an image of what i'm trying to display
for every array that has the value zzz, i want it to display that amount of boxes, this image will show 3 boxes, that means there are 3 arrays with zzz in them.
Here's the array
array(9) {
["show_hero_options"]=> string(1) "1"
["hero_height"]=> string(5) "600px"
["hero_width"]=> string(4) "100%"
["hero_buttons"]=> string(4) "show"
["upload_zzz_link_1"]=> string(105) "http://www.blahblah.com/image_link.jpg"
["upload_zzz_link_2"]=> string(79) "http://www.blahblah.com/image_link.jpg"
["upload_zzz_link_3"]=> string(79) "http://www.blahblah.com/image_link.jpg"
["upload_yyy_link_1"]=> string(79) "http://www.blahblah.com/image_link.jpg"
}
UPDATE 2a:
Here's the query just incase
jQuery(document).ready(function($){
// Hero Image zzz upload
function zzz_updateClonedInput(index, element,param) {
$(element).appendTo("#upload_zzz_sets").attr("id", "zzzclonedInput" + index);
$(element).find(">:first-child").attr("id", "cs_product_menu_zzz_src_" + index);
$(element).find(">:first-child").attr("name", "hero_options[upload_zzz_link_" + index + "]");
if(param)
$(element).find(">:first-child").attr("value", "");
$(element).find(">:first-child").next().attr("id", "cs_product_menu_zzz_src_" + index + "_zzzbutton");
}
$(document).on("click", ".zzzclone", function(e){
e.preventDefault();
var zzztoappend='<div id="zzzclonedInput1" class="zzzclonedInput"><input id="cs_product_menu_zzz_src_1" type="text" size="36" name="hero_options[upload_zzz_link_1]" value="" /><input id="cs_product_menu_zzz_src_1_zzzbutton" type="button" value="Add / Change" class="button-secondary zzz-upload-button" /><div class="button zzzremove">-</div>'
if( $(".zzzclonedInput").length < 1){
// create div
$('#upload_zzz_sets').append(zzztoappend);
}
else {
// clone div
var zzzcloneIndex = $(".zzzclonedInput").length + 1;
var zzznew_Input = $(this).closest('.zzzclonedInput').length ? $(this).closest('.zzzclonedInput').clone() : $(".zzzclonedInput:last").clone();
zzz_updateClonedInput(zzzcloneIndex, zzznew_Input,true);
}
});
$(document).on("click", ".zzzremove", function(e){
e.preventDefault();
$(this).parents(".zzzclonedInput").remove();
$(".zzzclonedInput").each( function (zzzcloneIndex, zzzclonedElement) {
zzz_updateClonedInput(zzzcloneIndex + 1, zzzclonedElement,false);
})
});
jQuery(document).ready(function($){
$(document).on("click", ".zzz-upload-button", function(e){
e.preventDefault();
upload_image($(this));
return false;
});
});
function upload_image(el){
var $ = jQuery;
var custom_uploader;
var button = $(el);
var id = button.attr('id').replace('_zzzbutton', '');
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Add Image',
button: { text: 'Add Image' },
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#'+id).val(attachment.url);
$('#'+id).prev().attr('src', attachment.url);
//console.log(attachment);
console.log(id);
//custom_uploader.close();
});
//Open the uploader dialog
custom_uploader.open();
}
});
UPDATE 2b:
I've also managed to display the right amount of fields, it just doesn't add the value. Here's my new code
function tl_hero_image_option_callback() {
$hero_options = get_option( 'hero_options' );
foreach ($hero_options as $key => $value) {
if (strpos($key, '_zzz_')) {
$html = '<div id="upload_zzz_sets">';
if( isset( $hero_options['upload_zzz_link_1'] ) && $hero_options[ 'upload_zzz_link_1' ] ) {
$html .= '<div id="zzzclonedInput'.$i.'" class="zzzclonedInput">';
$html .= '<input id="cs_product_menu_zzz_src_'.$i.'" type="text" size="36" name="hero_options[upload_zzz_link_'.$i.']" value="' . $hero_options['upload_zzz_link_'.$i.''] . '" /> <input id="cs_product_menu_zzz_src_'.$i.'_zzzbutton" type="button" value="Add / Change" class="button-secondary zzz-upload-button" /> <div class="button zzzremove">-</div>';
$html .= '</div>';
}
$html .= '</div>';
echo $html;
}
}
}
try:
function yyy_hero_image_option_callback() {
$hero_options = get_option( 'hero_options' );
$i=1;
$html = '<div id="upload_zzz_sets">';
foreach($hero_options as $key => $values){
if (strpos($key, 'zzz')) {
$html .= '<div id="zzzclonedInput'.$i.'" class="zzzclonedInput">';
$html .= '<input id="cs_product_menu_zzz_src_'.$i.'" type="text" size="36" name="hero_options[upload_zzz_link_'.$i.']" value="' . $values . '" /> <input id="cs_product_menu_zzz_src_'.$i.'_zzzbutton" type="button" value="Add / Change" class="button-secondary zzz-upload-button" /> <div class="button zzzremove">-</div>';
$html .= '</div>';
$i++;
}
}
$html .= '</div><div class="button zzzclone">Add an Image</div>';
echo $html;
}
The way you changed your code, $i is not set anymore, try this :
foreach ($hero_options as $key => $value) {
if (strpos($key, '_zzz_')) {
$i = substr($key, -1); // This will retrieve the last char of $key, which is corresponding to your previous $i
$html = '<div id="upload_zzz_sets">';
$html .= '<div id="zzzclonedInput'.$i.'" class="zzzclonedInput">';
$html .= '<input id="cs_product_menu_zzz_src_'.$i.'" type="text" size="36" name="' . $value . '" value="' . $value . '" /> <input id="cs_product_menu_zzz_src_'.$i.'_zzzbutton" type="button" value="Add / Change" class="button-secondary zzz-upload-button" /> <div class="button zzzremove">-</div>';
$html .= '</div>';
$html .= '</div>';
echo $html;
}
}
I also replaced the $hero_options[key] parts by $value, since you already get it from the foreach.
Related
I have use this form for uploading multiple files. But i have used jQuery for append multiple file input. I have try multiple method for validate in laravel but its not working. If we used only single file validate its working. But if we used multi file validation its not working.
If we use this and upload all file at a time in with multiple attribute file input its working.
If we upload multiple file one by one after that its not working.
// My View
#include('flash.flash_message')
<form action="{{route('company.upload')}}" method="post" id="formUpload">
<div id="newinput">
<input type="file" name="files[]" class="form-control" />
</div>
<input type="submit" value="uplaod" />
</form>
<div class="btn btn-info" id="add_btn">Add</div>
// My jQuery
$(document).on('click','#add_btn',function(){
var newRowAdd =
'<input type="file" name="files[]" class="form-control" />';
$('#newinput').append(newRowAdd);
});
// My Controller
<?php
public function store(Request $request)
{
$request->validate([
'files' => 'required',
'files.*' => 'mimes:doc,docx|max:15720',
] );
try
{
$array = [
'created_at'=>date('Y-m-d H:i:s')
];
$data = Company::create($array);
// there my uplaoding code
if($request->hasFile('file'))
{
$newData = Company::findOrFail($data->id);
$docs = array();
$files = $request->file('file');
if($files){
foreach($files as $file) {
$fileName = time().rand(100000,999999).'_'.$data->id.'.'.$file->extension();
$docs[] = $fileName;
$file->move(public_path('company'), $fileName);
}
}
$newData->doc = !empty($result) ? serialize($result) :'';
$newData->updated_at = date('Y-m-d H:i:s');
$newData->save();
}
}
catch(\Exception $e)
{
return redirect()->back()->with('error',$e->getMessage());
}
}
// I Also used this
$input_data = $request->all();
$validator = Validator::make(
$input_data, [
'files.*' => 'required|mimes:jpg,jpeg,png,bmp|max:20000'
],[
'files.*.required' => 'Please upload an image',
'files.*.mimes' => 'Only jpeg,png and bmp images are allowed',
'files.*.max' => 'Sorry! Maximum allowed size for an image is 20MB',
]
);
if ($validator->fails()) {
// Validation error..
}
var i = 1;
jQuery("#addRow").click(function () {
var html = '';
var scr = '';
html += '<div id="addedRow" class="form-row mb-4">';
html += '<div class="form-group col-md-4">';
html += '<label for="filename[' + i + ']">File type</label>';
html += '<span class="text-danger">*</span>';
html += '<select class="form-control" id="filename' + i + '" name="filename[' + i + ']" required><option selected="selected" value="">Select file type</option><option value="claim">Claim</option><option value="reimbursements">Reimbursements</option><option value="policy">Policy</option><option value="ecards">Ecards</option><option value="data">Data</option><option value="others">Others</option></select>';
html += '<span class="badge">';
html += '<small id="sh-text4" class="form-text mt-0">Select the file type you are uploading/linking</small>';
html += '</span>';
html += '</div>';
html += '<div id="Other' + i + '" class="form-group col-md-4">';
html += '<label for="other[' + i + ']">Specify file type</label> <span class="text-danger">*</span>';
html += '<input class="form-control" placeholder="Specify the file type" name="other[' + i + ']" type="text" id="other[' + i + ']" >';
html += '<span class="badge">';
html += '<small id="sh-text4" class="form-text mt-0">Specify the file type as you selected the file as "Other"</small>';
html += '</span>';
html += '</div>';
html += '<div id="upload' + i + '" class="form-group col-md-4">';
html += '<label for="upload[' + i + ']">Upload file</label>';
html += '<span class="text-danger">*</span>';
html += '<input class="form-control" name="upload[' + i + ']" type="file" id="upload[' + i + ']" required>';
html += '<span class="badge">';
html += '<small id="sh-text4" class="form-text mt-0">Upload the file | Formats allowed: <strong>PDF, DOC, ZIP, JPG, PNG GIF and Excel</strong></small></span>';
html += '</div>';
html += '<div class="form-group col-md-4" style="padding-top: 30px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
html += '</div>';
html += '</div>';
jQuery('#newRow').append(html);
scr += '<script';
scr += '>$(document).ready(function(){ $("#filename' + i + '").change(function () { if ($(this).val() === "others") {$("#Other' + i + '").show(); document.getElementById("other[' + i + ']").required=true}else{ $("#Other' + i + '").hide(); document.getElementById("other[' + i + ']").required=false;}}); $("#Other' + i + '").hide(); }); </';
scr += 'script>';
jQuery('#newScript').append(scr);
i++;
});
// remove row
jQuery(document).on('click', '#removeRow', function () {
i--;
$(this).closest('#addedRow').remove();
});
This is how I have implemented this in my project you can see there is a variable that you need to pass here
<input type="file" name="files['+i+']" class="form-control" />;
You have to increase the value of i once the row is added
This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Why does this PDO statement silently fail?
(2 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
function e_type($connect) {
$output1 = '';
$query = "SELECT * FROM elimo_type ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output1 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output1;
}
function hw_type($connect) {
$output2 = '';
$query = "SELECT * FROM hw_version ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output2 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output2;
}
function sw_type($connect) {
$output3 = '';
$query = "SELECT * FROM sw_version ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output3 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output3;
}
?>
<?php
include 'header.php';
?>
<div class="container">
<h3 align="center">Purchase</h3>
<br />
<h4 align="center">Enter Purchase Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Serial No</th>
<th>Type</th>
<th>Hardware Version</th>
<th>Software Version</th>
<th>Key</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$(document).on('click', '.add', function () {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="serial_no[]" class="form-control serial_no" /></td>';
html += '<td><select name="e_type[]" class="form-control e_type"><option value="">Select Type</option><?php echo e_type($connect); ?></select></td>';
html += '<td><select name="hw_type[]" class="form-control hw_type"><option value="">Select Hardware Version</option><?php echo hw_type($connect); ?></select></td>';
html += '<td><select name="sw_type[]" class="form-control sw_type"><option value="">Select Software Version</option><?php echo sw_type($connect); ?></select></td>';
html += '<td><input type="text" name="key[]" class="form-control key" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function () {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function (event) {
event.preventDefault();
var error = '';
$('.serial_no').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Enter Serial no at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.e_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Type at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.hw_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Hardware Version at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.sw_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Software Version at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.key').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Enter Key at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '')
{
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function (data)
{
if (data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Purchase Details Saved</div>');
}
}
});
} else
{
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
</script>
<?php
//insert.php;
if (isset($_POST["serial_no"])) {
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
$id = uniqid();
for ($count = 0; $count < count($_POST["serial_no"]); $count++) {
$query = "INSERT INTO elimo_purchase
(id,serial_no, e_type, hw_type, sw_type,key)
VALUES (:id,:serial_no, :e_type, :hw_type, :sw_type,:key)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':serial_no' => $_POST["serial_no"][$count],
':e_type' => $_POST["e_type"][$count],
':hw_type' => $_POST["hw_type"][$count],
':sw_type' => $_POST["sw_type"][$count],
':key' => $_POST["key"][$count]
)
);
}
$result = $statement->fetchAll();
if (isset($result)) {
echo 'ok';
}
}
?>
I'm getting output as purchase details saved but result is not stored into database.
You need to debug as per below,
Check all the values which you pass in insert query print all and check values.
Then print the query and fire the same query manually and check it was inserted or not
When you're doing an INSERT query, you can't use a fetch function, because it doesn't return any data. That can only be used with SELECT. You need to check the result of $statement->execute().
if(isset($_POST["serial_no"]))
{
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
$id = uniqid();
$query = "INSERT INTO elimo_purchase (id,serial_no, e_type, hw_type, sw_type,key)
VALUES (:id,:serial_no, :e_type, :hw_type, :sw_type,:key)";
$statement = $connect->prepare($query);
for($count = 0; $count < count($_POST["serial_no"]); $count++)
{
if (!$statement->execute(
array(
':id' => $id,
':serial_no' => $_POST["serial_no"][$count],
':e_type' => $_POST["e_type"][$count],
':hw_type' => $_POST["hw_type"][$count],
':sw_type' => $_POST["sw_type"][$count],
':key' => $_POST["key"][$count]
)
)) {
die('not ok');
}
}
echo 'ok';
}
So I have this form:
<form data-ajax="false" name="frm" action="cmd_go.php" method="post" >
<input type="hidden" name="cmd" value="insertarlineapedidomultiple">
<input type="hidden" name="mod" value="yes">
<!--<input id="insertList" type="hidden" name="insertList" value="">-->
<input type="hidden" name="o" value="<?php echo $o ?>">
<div id="div_lista_familias" data-role="collapsibleset" data-content-theme="a" data-iconpos="right">
</div>
<input class="insertar btn-azul ui-btn ui-corner-all" data-role="none" type="submit" value="Insertar"/>
</form>
Then we have some Javascript code to populate the form content after calling a web service:
function listaProductos(alb, fam){
var ok = false;
$.ajax({
type: 'GET',
url: url_servicio + alb + '/' + fam + '/productos',
dataType: "json", // data type of response
//async: false,
error: function(){
ok = false;
},
success: function(data){
var content;
var acum = 0;
for(i=0; i<data.length; i++){
ok = true;
var qty = get_item_qty_inline(data[i].itemid);
var qty2 = get_item_qty2_inline(data[i].itemid);
var qty3 = get_item_qty3_inline(data[i].itemid);
var dto = get_item_dto1_inline(data[i].itemid);
content = '<fieldset class="ui-grid-d">';
content += '<div class="ui-block-a"><label for="name">';
content += data[i].itemid + ' ' + data[i].nombre + '</div>';
content += '<div class="ui-block-c ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty + '" placeholder="Uds1" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<div class="ui-block-b ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number" name="dtoporc1[]" pattern="[0-9]*" id="number-pattern"'
content += ' value="' + dto + '" placeholder="%Dto1"></div>';
content += '<div class="ui-block-d ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad2[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty2 + '" placeholder="Uds2" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<div class="ui-block-e ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad3[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty3 + '" placeholder="Uds3" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<input type="hidden" name="idalbaran[]" value="' + alb +'">';
content += '<input type="hidden" name="itemid[]" value="' + data[i].itemid +'">';
content += '<input type="hidden" name="famalbaran[]" value="' + fam +'">';
content += '<input type="hidden" name="itemdesc[]" value="' + data[i].nombre +'">';
content += '<input type="hidden" name="precioventa[]" value="' + data[i].precio + '">';
content += '<input type="hidden" name="dtoporc2[]" value>';
content += '<input type="hidden" name="dtoporc3[]" value>';
$('#'+fam.replace(/ /g, '_')+'_content').append(content);
acum += parseFloat(qty || 0) + parseFloat(qty2 || 0) + parseFloat(qty3 || 0);
$('#'+fam.replace(/ /g, '_')+' .ui-li-count').html(acum);
}
},
complete: function(data, status){
if (!ok){
$('#'+fam.replace(/ /g, '_')).remove();
}
}
});
}
Finally, this is the PHP code we have in cmd_go.php
//GET variables
if(isset($_GET)){
$params = array_keys($_GET);
for ($i=0;$i<count($params);$i++)
if(isset($_GET[$params[$i]])){
$nv=$params[$i];
$$nv=$_GET[$params[$i]];
}
}
//POST variables
if(isset($_POST)){
$params = array_keys($_POST);
for($i=0;$i<count($params);$i++)
if(isset($_POST[$params[$i]])){
$nv=$params[$i];
$$nv=$_POST[$params[$i]];
//print "$nv : ".$$nv.'<br />';
}
}
var_dump($itemid);
The problem is that not all values are posted, because our $itemid array only has 91 elements, when our web service returns about 400. Out HTML form is correctly displayed with all 400 items, but out PHP var_dump returns:
array(91){[0]=>string(6) "173771" [1]=>string(6) "173772" [2]=>string(6) "564814"...[90]=>string(6) "548115"}
Any ideas on why POST could be taking only 91 records??
You need to check max_input_vars value in php.ini. It can lead to such behavior.
http://php.net/manual/en/info.configuration.php#ini.max-input-vars
i want to use append a table on click of add button. this table will display all values from the $category array . i tried to use php code inside of jquery and the sample code is as below. how can i improve my code to display array from php variable?
$(".add_field_button").on("click", function(e) {
var wrapper = $(".input_fields_wrap");
$(wrapper).append('<hr>\n\
<table class="append-group table">\n\
<tr>\n\
<td colspan='4'>\n\
<div class="form-group">\n\
<label class="">\n\
Select Category<span id="load"></span>\n\
</label>\n\
<?php foreach($categories as $category){?>\n\
<div class="radio-inline">\n\
<label style="font-weight:normal;">
<input class="category" id = "<?php echo $category['id'];?>" type="radio" onclick="get_sub_category('<?php echo $category['id'];?>',0)" name="category_id" <?php if ($action == 'edit' && $detail[0]['category_id'] == $category['id']) { echo "checked='checked'";} ?> value="<?php echo $category['id'];?>"><?php echo ucwords(strtolower($category['name']));?>
</label>\n\
</div>\n\
<?php }?>\n\
</div>\n\
<input type="hidden" id="selected_item" value="<?php if(isset($detail[0]['category_item_id'])) echo $detail[0]['category_item_id'];?>">\n\
</td>\n\
</tr>\n\
</table>\n\
');
});
Saperate every part and make the things moduler, so that it will be easy to extend. In PHP Do like this:
$categories_data = "";
foreach($categories as $category) {
$categories_data .= '<div class="radio-inline">';
$categories_data .= '<label style="font-weight:normal;">';
$categories_data .= '<input class="category" id = "'.$category['id'].'" type="radio" onclick="get_sub_category("'.$category['id'].'",0)" name="category_id" ';
if ($action == 'edit' && $detail[0]['category_id'] == $category['id']) {
$categories_data .= ' checked="checked" ';
}
$categories_data .= 'value="'.$category['id'].'">';
$categories_data .= ucwords(strtolower($category['name']));
$categories_data .= '</label></div>';
}
$cat_item_id = "";
if( isset($detail[0]['category_item_id']) ) {
$cat_item_id = $detail[0]['category_item_id'];
}
In your JAVASCRIPT saperate the template, variables etc. and then append after replace the things properly:
var _categories = '<?php echo $categories_data; ?>';
var _cat_item_id = '<?php echo $cat_item_id ?>';
// Your template
var _template = '<hr>\n\
<table class="append-group table">\n\
<tr>\n\
<td colspan='4'>\n\
<div class="form-group">\n\
<label class="">\n\
Select Category<span id="load"></span>\n\
</label>\n\
{{categories}}\n\
</div>\n\
<input type="hidden" id="selected_item" value="{{cat_item_id}}">\n\
</td>\n\
</tr>\n\
</table>';
// Marge with original values and append
var _table = _template.replace(/{{categories}}/, _categories)
.replace(/{{cat_item_id}}/, _cat_item_id);
$(wrapper).append( _table );
To access categories and item_id globally you can use window._categories = '<?php echo $categories_data; ?>'; and window._cat_item_id = '<?php echo $cat_item_id ?>'; so that if you have external js file (custom.js) then its easy to access these values with window._categories and window._cat_item_id
You can preload your js objects in the header of your php file like this:
<script type="text/javascript">
var GLOBALS = {
categories: <?php echo json_encode($categories); ?>,
detail: '<?php echo isset($detail[0]['category_item_id']) ? $detail[0]['category_item_id'] : ""; ?>',
action: '<?php echo $action; ?>'
}
</script>
<script src="myscript.js">
Next create a script that triggers on the button press. You can grab your category data from the global variables set in the php file.
$(".add_field_button").on("click", function(e) {
var $span = $('<span>', {id: "load"});
var $label = $('<label>', {text: "Select Category"}).append($span);
var $divs = [];
for (var i in GLOBALS.categories) {
var action = GLOBALS.action || "";
var detail = GLOBALS.detail || "";
var id = GLOBALS.categories[i].id || "";
var name = GLOBALS.categories[i].name || "";
var $i = $('<input>', {
class: category,
id: id,
type: "radio",
onclick: "get_sub_category(" + id + ", 0)",
name: "category_id",
value: id,
text: name.toLowerCase()
});
if (action == "edit" && detail == id) {
$i.prop("checked", true);
}
var $l = $('<label>', {style: "font-weight: normal"}).append($i);
var $d = $('<div>', { class: "radio-inline"}).append($l);
$divs.append($d);
}
var $div = $('<div>', {class: "form-group"}).append($label, $divs);
var $input = $('<input>', {type: "hidden", id: "selected_value", value: GLOBALS.detail});
var $td = $('<td>', {colspan: 4}).append($div, $input);
var $tr = $('<tr>').append($td);
var $table = $("<table>", {class: "append-group table"}).append($tr);
var $wrapper = $(".input_fields_wrap").append($('<hr>'), $table);
});
I am using jcart http://conceptlogic.com/jcart/ to create some cart functionality in wordpress.
I am trying to access a jcart function within another function in my functions.php file.
foreach($jcart->get_contents() as $item) {
$psitems[] = $item['id'];
}
This code works fine on functions.php itself or on any template page-- it creates the $psitems array so I can check if that array contains certain values.
Now, within the following function:
function gallery_shortcode_fancybox($attr) { ...
I have the following:
foreach($jcart->get_contents() as $item) {
$psitems[] = $item['id'];
}
foreach ( $attachments as $id => $attachment ) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_image($id, 'full', false, false) : wp_get_attachment_image($id, 'full', true, false);
$output .= "<div class='property'>";
$output .= "$link";
$output .= '
<div class="property-details">
<div class="property-details-inner">
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="' . $_SESSION['jcartToken'] . '" />
<input type="hidden" name="my-item-id" value="' . $id . '" />
<input type="hidden" name="my-item-name" value="Photo #' . $id . '" />
<input type="hidden" name="my-item-url" value="' . wp_get_attachment_url( $id ) . '" />
<input type="hidden" name="my-item-qty" value="1" size="3" />';
if(in_array($id,$psitems)) {
$output .= '<span class="action terminal pull-sheet">Image in Pullsheet</span>'
} else {
$output .= '<input type="submit" name="my-add-button" value="Add to Pull Sheet" class="action terminal pull-sheet" />';
}
$output .= '</fieldset>
</form>
</div> <!-- property-details-inner -->
</div>';
$output .= "</div>";
}
return $output;
I get the following error:
Call to a member function get_contents() on a non-object
If I try placing the original foreach($jcart->get_contents() as $item) { ... code outside of the function, I get the following error:
Warning: in_array() expects parameter 2 to be array, null given in...
How can I access this array inside the function and avoid these errors?
Thanks!
Regarding the first error, it means that you have to initialize $jcart.
As for the warning, try this:
$array = $jcart->get_contents();
foreach ($array as $item) ...