File upload with multiple browse button (populated from array) on Laravel - laravel

I need to upload file from dynamic upload button that generated form array as below code (Edited and workd already).
#foreach( $transfer as $key => $item )
<tr>
<td>
<input type="file" name="document[]" class="doc filestyle"/>
</td>
</tr>
#endforeach
This is boostrap filestyle
<script type="text/javascript">
$('.doc').filestyle({
buttonName : 'btn-success',
input: false,
icon: false,
});
It only work for single file. But I have no idea for multiple. (Edited and workd already)
if(count(Request::file('document', [])) > 0){
foreach( Request::file('document', []) as $key => $item ){
echo 'Reg ID: ' . $key . '<br />';
echo 'Value: ' . $item->getClientOriginalName() . '<br />';
}
}
Thanks for all advise.

Thats because you are not defining your control name as array
Change This to
<input type="file" name="document" id="doc{{$key}}" class="filestyle"/>
This
<input type="file" name="document[]" id="doc{{$key}}" class="filestyle"/>
Not name="document" change to name="document[]"
and sorry i have missed multiple Attributes in tag thanks to #Md.Sukel Ali
This Might Work

You need to add multiple attribute in your in input field.
<input type="file" name="document[]" id="doc{{$key}}" class="filestyle" multiple="" />

Related

Passing checkbox value from view to controller

How to pass checkbox value from views to controller so that I can compare the checked/unchecked values (for database update)?
Views:
#foreach ($second as $sec)
<br>
<div class = "form-group">
{{$sec->Roll }}
&nbsp&nbsp&nbsp&nbsp
{{ $sec->Name}}
</div>
<div class = "form-group">
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="1" />
</div>
#endforeach
Controller:
foreach ($columns as $col) {
//dd("Y");
if($col == $txt[1]) {
$got=DB::table($req)->select($col)->get();
//dd($got);
//COMPARE CHECKBOX VALUE "CHECKED/UNCHECKED" WITH ITS DEFAULT VALUE
DB::statement("UPDATE " . $req . " set " . $got . " to " . $got . " + 1 WHERE" .$req->Roll . " IN ".( implode(',', $req)));
}
}
Ps: This might be applicable only if my description matches what you are trying to do, because your question seems so.
One of the ways I have done it is not to put any value in the checkbox element. Then inspect if the value returned is string with is_string($the_variable) or not. That is, instead of:
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="checkbox_1" />
I'll have:
<input tabindex="1" type="checkbox" name="checkbox_1" />
This might not be an ideal solution, but a bit curious if you have tried it.
So in the controller, any checked checkbox would have 'on' as the value, while unchecked one would have null:
so if I do in my controller:
return request()->all();
I should get the values of the checked as 'on' and the values of the unchecked as null
So i'll do for example in controller:
if(is_string(request()->get('checkbox_1))) {
//checked
else {
// unchecked
}
Hope this is clear now.
Just for an update:
One other way to do this is to pass the key of the column you are trying to update when making the foreach, so you will have something like this:
#foreach ($second as $key=> $sec)
then on the checkbox it will serve as different names:
<input tabindex="1" type="checkbox" name="{{ $key }}" />
This way if you do return request()->all(); at the first in your controller, you can then tell if something else is wrong or not.
Please make sure you note the $key in that foreach() so to be sure you are doing the right thing.

Request tracker REST API: Web Interface to Create New Tickets

I previously had a custom form that users could fill out to place work orders, and once they hit submit, it would create a new ticket with all the information and add it to one of the RT queues.
We previously used Mason to do this, but now we've moved to WordPress and would like to redo this in a cleaner way using PHP.
I read through the API documentation and reviewed this thread along with many others posted on Stack Overflow. I know how to connect to RT and create new tickets via command line and cURL, but I can't seem to figure out how to do so using the web interface on submit. I would really appreciate if someone could give me some pointers on where to start.
Thanks
Edit:
Thank you for the response. Below is the form I've made which interacts with a our SQL database to pull some information and I need it to create a new ticket with all the information on submit. Should I create a new php file similar to [this][2] and include it as a form action?
<form action="<?php echo $_SELF; ?>";
method="post"
id="woForm"
name="woForm"
enctype="multipart/form-data"
>
<input type="hidden" name="session_id" value="<?php echo session_id(); ?>">
<input type="hidden" name="Queue" value="<?php echo $queue; ?>">
<input type="hidden" name="id" value="new">
<input type="hidden" name="Status" value="new">
<input type="hidden" name="Owner" value="10">
<table width="450" align="center" border="0" cellpadding="0" cellspacing="5">
<tr><td align="left" colspan="2">
<h2><?php echo $name; ?></h2>
<p>Please note that all fields except for <b>Ext:</b>, <b>CC:</b> and <b>Attachments:</b> are <span class="required">required</span>.
You cannot submit a request for assistance using this form unless all the required
fields have been completed.</p>
<h2 style="color:red;">Please enter information for the INDIVIDUAL needing assistance</h2>
</td>
</tr>
<?php
// Get all of the customFields
$query1 = "select * from CustomFields where disabled='0' and sortOrder != 0 order by sortOrder ASC;";
$result1 = mysql_query($query1) or die ("dead3: ".mysql_error());
// Go through each custom field
while($row1 = mysql_fetch_array($result1)) {
// Get the information about that field
$count = 0;
$fieldId = $row1['id'];
$name = $row1['Name'];
// $postname is in a very specific format, and will become the name of the field in the form
// where the data for this custom field is entered. In order to submit a ticket into rt, the
// name of the field MUST be in this format.
$postName = "Object-RT::Ticket--CustomField-".$fieldId."-Values";
?>
<!-- Create a row in the table for this custom field -->
<tr>
<!-- Create a column with the name of the custom field -->
<td align="right" class="requestformlabel"><label class="required"><?php echo $name; ?>:</label></td>
<!-- Create a column for the input field -->
<td class = "requestformtd">
<?php
// If the custom field is department or building, we need a pull-down menu
if($name=="Department" || $name=="Building") { ?>
<!-- start of the pull-down menu -->
<select name="<?php echo $postName; ?>">
<?php
// Get all of the possible values for the customField from the database
// Added option to exclude sort order 9999. See ticket #40665 for more info.
$query3 = "SELECT * FROM CustomFieldValues WHERE CustomField='$fieldId' AND SortOrder != '9999' ORDER BY SortOrder ASC";
$result3 = mysql_query($query3) or die ("dead4: ".mysql_error());
// Go through each possible value for the custom field
while($row3 = mysql_fetch_array($result3)) {
// Get the information on the custom field value from the database
$tmp = $row3['Name'];
$description = $row3['Description'];
// If the custom field value was already selected
if($tmp == $_POST["$postName"]) {
// Insert the option into the pull-down menu and mark it as selected in the form
echo "<option value='$tmp' selected='selected'>$description</option>";
// otherwise
} else {
// Only insert it as an option in the pull-down menu
echo "<option value='$tmp'>$description</option>";
}
}
?>
</td></tr>
<?php
// If the name of the custom field is operating system, we want radio buttons
} else if ($name == "Operating System") {
// Get all the possible values for this field form the database
$query4 = "select * from CustomFieldValues where CustomField='$fieldId' order by sortorder asc";
$result4 = mysql_query($query4) or die ("dead5: ".mysql_error());
// For each customfield value
while($row4 = mysql_fetch_array($result4)) {
// Get the description of the customfieldvalue from the database
$osName = $row4['Description'];
// If the customfieldvalue has already been selected
if ($osName == $_POST["$postName"]) {
// Put the radio button into the form and mark it as checked
echo "<input type='radio' name='$postName' value='$osName' checked='checked'>$osName";
// Otherwise
} else {
// Put the radio button into the form
echo "<input type='radio' name='$postName' value='$osName'>$osName";
}
} ?>
</td></tr>
<?php
// If the name of the custom field is ip adress, we want a disbaled text box. This is because while we want the user to see their ip adress, we do not want them to be able to change it.
} else if ($name == "IP_Address"){
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php
echo $_SERVER['REMOTE_ADDR']; ?>' readonly></td></tr>
<?php
// If it's the hostname variable
} else if ($name == "Host_Name"){
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php echo gethostbyaddr($_SERVER['REMOTE_ADDR']); ?>' readonly></td></tr>
<?php
// Otherwise, create a text box for the custom field.
} else {
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php echo $_POST["$postName"]; ?>'></td></tr>
<?php } // end else statement
} // end while loop
?>
<tr>
<td class="requestformlabel" align="right"><label class="required">Your E-mail Address:</label></td>
<td align="left" class="requestformtd"><input name="Requestors" size=40 value="<?php echo $_POST['Requestors']; ?>"></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Confirm Your E-mail Address:</label></td>
<td align="left" class="requestformtd"><input name="Requestors_2" size=40 value="<?php echo $_POST['Requestors_2']; ?>"></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="fields">Cc:</label></td>
<td align="left" class="requestformtd"><input name="Cc" size=40 value="<?php echo $_POST['Cc']; ?>"></td>
</tr>
<tr>
<td align="right"><p> <br/> </p></td>
<td align="right"><span class="ccnote">(Separate multiple email addresses with commas.)<br/> </span></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Short Problem Summary:</label></td>
<td align="left" class="requestformtd"><input name="Subject" size=40 maxsize=100 value="<?php echo $_POST['Subject']; ?>"></td></tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Decribe the issue below:</label></td>
<td align="left" class="requestformtd"><textarea
class="messagebox" cols=35 rows=15 wrap="hard" name="Content"><?php echo $_POST['Content']; ?></textarea>
</td>
</tr>
<?php
//if session has attachments
if($_SESSION['attach'] != '') {
?>
<!-- row for existing attahcments -->
<tr>
<!-- column that states these are the current attachments, and tells the user what to do if
they wish to remove an attachment. -->
<td class="requestformlabel" align="right">Current Attachments:<br/>
<span class="ccnote">(Check box to delete)</span>
</td>
<!-- coulmn that lists the attachments -->
<td class="requestformtd" align="right">
<?php
// Go through each file in $_SESSION['attach']
while (list($key, $val) = each($_SESSION['attach'])) {
// Get the name of the file
$attName = $val['name'];
// Create a checkbox to mark the file as needing to be removed from the list
echo "<input type='checkbox' name='DeleteAttach-$attName' value='1'>$attName<br/>";
} // end while loop
?>
</td>
</tr>
<?php // end if for attachments
}
?>
<tr>
<td class="requestformlabel" align="right"><label class="fields">Attachments:</label></br>
<span class="ccnote">Max. attachment size: 50MB.</span></td>
<td align="right" colspan="2" class="requestformtd">
<input type="file" name="Attach">
<br/>
<input type="submit" name="AddMoreAttach" value="Add More Files">
</td>
</tr>
<tr>
<td align="left"><input type="submit" name="submit" value="Submit Request"></td>
<td> </td>
</tr>
</table>
</form>
Edit 2:
Thanks. Using the documentation and code from this repo I created a new file called new_ticket.php with the following content:
<?php
if($_POST['action'] == 'call_this') {
require_once 'RequestTracker.php';
$url = "www.test.com/rt/REST/1.0/";
$user = "user";
$pass = "password";
$rt = new RequestTracker($url, $user, $pass);
$content = array(
'Queue'=>'9',
'Requestor'=>'test#example.com',
'Subject'=>'Lorem Ipsum',
'Text'=>'dolor sit amet'
);
$response = $rt->createTicket($content);
print_r($response);
}
?>
I also made of copy of RequestTracker.php from the same Github repo.
In the file where the form is located, I added the following script and added create_ticket() as an action to the onclick property of submit button. But this doesn't seem to be working. I tried logging something to the console to see how far the code gets, the create_ticket() function is being called properly but anything that comes after $.ajax({ ... above will not appear to the console. I also tried putting some console logs in my new_ticket.php file but that doesn't log anything either, so what am I doing wrong?
<script>
function create_ticket() {
$.ajax({
url:"new_ticket.php", //the page containing php script
type: "POST", //request type
data:{action:'call_this'},
success:function(result){
alert(result);
}
});
}
</script>
PS: I'm using ajax because I need to run the PHP code onclick and this can't be done directly as it would in Javascript.
Probably the easiest approach is to look at the PHP examples in the REST documentation on the Request Tracker wiki. You don't mention the version of RT you are using, but the REST interface has been stable so this should work with most versions.

Cannot upload images in magento

I have a custom module by which i am trying to upload images. However i cant upload images
This is my form file
<?php
<form id="imageform" method="post" action="<?php echo $this->getFormAction(); ?>">
<input type="file" id="chain_Image" value="" name="Image[]" class="input-text">
</form>
note that this is only a small part of my code. actually this form can contain any number images. that is we can upload more than one image at a time.
This is my saveAction() :
<?php
$arr = $this->getRequest()->getPost('Image');
foreach($arr as $image)
{
if(isset($_FILES[$image]['name']) and (file_exists($_FILES[$image]['tmp_name'])))
{
try
{
$path = Mage::getBaseDir('media') . DS . 'banner' . DS;
$uploader = new Varien_File_Uploader($image);
$uploader->setAllowedExtensions(array('jpg','png','gif','jpeg'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES[$image]['name'];
filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$postData['Image'] = $_FILES[$image]['name'];
}
catch(Exception $e)
{}
}
else
{
if(isset($postData[$image]['delete']) && $postData[$image]['delete'] == 1)
$postData[$image] = '';
else
unset($postData[$image]);
}
}
$bannerModel->addData($postData)->setId($this
->getRequest()->getParam('id'))->save();
However it does not upload my imaged. $_FILES is seem to be empty,when i have printed this. What is the problem in my code. Help me. Thanks in advance !!!
I hope there is a mistake at save function. Here is my example code for saving an image with other details. Let see this may help you.
$newsModel->setId($this->getRequest()->getParam('id'))
->setTitle($postData['title'])
->setImage($_FILES['image']['name'])
->setContent($postData['content'])
->setStatus($postData['status'])
->save();
You have to save the image by calling as setImage($_FILES['image']['name']) Try this..
Remember to put the enctype="multipart/form-data" in form parameters :
<form id="imageform" method="post" action="<?php echo $this->getFormAction(); ?>" enctype="multipart/form-data">
<input type="file" id="chain_Image" value="" name="Image[]" class="input-text">
</form>

printing in joomla

I need help to solve a printing problem completely blocking my project. To be precise and clear, I have two articles Joomla containing PHP code (I use the pluging Free sourcerer).
The first article contains the following code:
{source}
<form method="post" action="http://localhost/essai/index.php?option=com_content&view=article&id=2">
<p>
<input type="text" name="num" />
</p>
<input type="submit" value="Display the value of num" />
</form>
{/source}
The second article whose id is 2 contains the following code:
{sourcer}
if (isset ($_POST [ 'num'])) {
$Address=J Request :: getVar( 'num', '', 'post');
echo $Address;
} else {
echo "num does not exist";
}
{/source}
My objective is recover the value of the input field of the form num in the second article with id 2 and print. When I click on the button "Display the value of num" value zone num is retrieved and displayed, but when I click on the link to print
the article, "Does not exist num" is displayed in the open windows.
When I print the article, $ _POST ['num'] does not exist!
Is that this is a problem printing in Joomla or other? Help me please.
NB: I use Joomla_2.5.9, Template Beez2 integrated in joomla,
Sourcerer-Free v4.1.3
There are 2 changes you need to make in order to get this to work.
1 - I have included the form inside the PHP
{source}
<?php
echo'<form method="post" action="http://localhost/essai/index.php?option=com_content&view=article&id=2">' .
'<p>' .
'<input type="text" name="num" />' .
'</p>' .
'<input type="submit" value="Display the value of num" />' .
'</form>';
?>
{/source}
2 - Remove some of the extra SPACES from the code
{source}
<?php
if (isset($_POST['num'])) {
$Address=JRequest :: getVar('num','','post');
echo $Address;
} else {
echo "num does not exist";
}
?>
{/source}

Adding a 'add another' option in Wordpress custom meta box using jquery $.post

I'm creating a wordpress plugin, with a custom post type and in that post type a custom meta box.
Inside the meta box, I have a form that let's the user input: Date, Media, Title.
The form looks like this:
$mc_date = get_post_meta($_GET['post'],'mc_date',true);
$mc_media = get_post_meta($_GET['post'],'mc_media',true);
$mc_title = get_post_meta($_GET['post'],'mc_title',true);
echo '<form id="add_media_form">';
echo '<table>';
echo '<tr>';
echo '<td>Date</td><td>Media</td><td>Title</td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="text" name="mc_date" value="'.$mc_date.'" class="datepicker"/></td>';
echo '<td><input type="text" name="mc_media" value="'.$mc_media.'" /></td>';
echo '<td><input type="text" name="mc_title" value="'.$mc_title.'" /></td>';
echo '<td><img src="'.WP_PLUGIN_URL.'/mc/plus.png" /></td>';
echo '</tr>';
echo '</table>';
echo '</form>';
echo '<div class="addmedianotify"></div>';
jquery:
jQuery('.add_new_media').click(function(e){
var plug = jQuery(this).attr('rel');
e.preventDefault();
jQuery.post(plug + '/ajax_add_media.php',jQuery('#add_media_form').serialize(),function(data){
jQuery('.addmedianotify').html('<span>'+data+'</span>');
});
});
What I want to do, is that when the user click the 'add_new_media' link/image a new set of textboxes for date, media and title will appear.
My main concern is that, what's the trick to name those inputs which is dynamic. and to save and retrieves the custom data in it.
Because the page will still update when the user clicks 'Update' you would need to be able to save your fields on save_post and in your ajax. Using ajax for this might not be the best method as you're making more work for yourself by needing to save that data twice. I would ditch the ajax and simply use an html array so you can add on fields and make one submission when the user clicks 'Update'. To add new rows as the user needs, I would simply clone your tr and append it to the table in your click event. Something like...
The PHP & HTML
<img src="'.WP_PLUGIN_URL.'/mc/plus.png" />
<table>
<tr>
<td>Date</td>
<td>Media</td>
<td>Title</td>
<td></td>
</tr>
<?php
//$mcs will be a multi-dimensional array with this method
$mcs = get_post_meta($post->ID,'mcs',true);
//Loop through each set of saved mc data (date, media, and title per item) and output inputs so the saved values can be edited and resaved.
foreach ($mcs as $mc) : ?>
<tr>
<td><input type="text" name="mc[][date]" value="<?php echo $mc['date'] ?>" class="datepicker"/></td>
<td><input type="text" name="mc[][media]" value="<?php echo $mc['media'] ?>" /></td>
<td><input type="text" name="mc[][title]" value="<?php echo $mc['title'] ?>" /></td>
<td>Remove</td>
</tr>
<?php endforeach ?>
</table>
The Javascript
<script>
(function($){
//Grab the first
$('.add_new_media').click(function(e) {
//Use the first tr as a cookiecutter and add another cookie to the bowl :)
$('table tr:first-child')
.clone()
.appendTo($('table'))
.find('input')
.val('')
}
$('.remove').click(function(){
$(this).parent().parent().remove()
})
})(jQuery)
</script>
The PHP upon form submission
<?php
if ($_POST) :
//$_POST['mc'] is a multi-dimensional array of all the date/media/title input rows
print_r($_POST['mc']);
/*
..would look something like
Array (
[0] => Array (
'date' => 'some value',
'media' => 'some value',
'title' => 'some value'
),
[1] => Array ( ... ),
[2] => Array ( ... ) ... and so on
)
*/
//RUN INPUT VALIDATION!!
//Update the list
update_post_meta($post->ID, 'mcs', $_POST['mc']);
endif;
?>

Resources