I am still new to a bit of this.
I am making and edit form. I have several select2 boxes. one is populated via ajax and the others are done through the jquery inital setup.
I am trying to set the default value based on the model.
{!! Form::model($printJob, ['method' => 'PATCH', 'action' => ['PrintJobsController#update', $printJob->print_job_id ], 'class' => 'form-horizontal form-label-left']) !!}
<div class="form-group">
{!! Form::label('mo_id', 'MO Number', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}
<div class="col-md-9 col-sm-9 col-xs-12">
{!! Form::select('mo_id', [], null, ['id' => 'selMoNumber', 'required']) !!}
</div>
</div>
In my scripts i have the initializers
$("#selMoNumber").select2({
language: { errorLoading:function(){ return "Searching..." } },
dropdownAutoWidth: 'true',
placeholder: "Enter a MO Number",
width: '100%',
ajax: {
url: "/manufactureorders/query",
dataType: 'json',
delay: 500,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data) {
return {
results: data,
};
},
cache: true
},
minimumInputLength: 3,
});
How do i set the Select2 to be the models value?
Related
So I want to upload a picture but it only store its description correctly. The file is stored as "noimage.jpg" which means the filename isn't read. I'm using modal btw. My database is named galleries and the migration contains these:
$table->id();
$table->timestamps();
$table->string('upload');
$table->longtext('description')->nullable();
CONTROLLER:
public function store(Request $request)
{
$galleries=new Gallery;
// Handle File Upload
if($request->hasFile('upload')){
// Get filename with the extension
$filenameWithExt = $request->file('upload')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('upload')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.$extension;
// Upload Image
$path = $request->upload('upload')->storeAs('public/upload', $fileNameToStore);
// make thumbnails
$thumbStore = 'thumb.'.$filename.'_'.time().'.'.$extension;
$thumb = Image::make($request->file('upload')->getRealPath());
$thumb->save('storage/upload/'.$thumbStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$galleries->description = $request->input('description');
$galleries->upload = $fileNameToStore;
$galleries->save();
}
FORM:
<form id="uploadForm">
<div class="modal-body">
<input type="hidden" name="id" id="id">
<!-- Upload image input-->
<div class="input-group mb-3 px-2 py-2 rounded-pill bg-secondary shadow-sm">
<input type="file" name="upload" id="upload" onchange="readURL(this);" class="form-control border-0">
<label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
</div>
</div>
<!-- Uploaded image area-->
<p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
<div class="image-area mt-4 bg-white"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
<label>Caption</label>
<input type="textarea" class="form-control text-white" name="description" id="description">
</div>
</form>
AJAX
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//ADD PICTURE
$('#btnUpload').click(function(){
$('#uploadModal').modal('show');
});
$('#btnSave').click(function(){
$.ajax({
data: $('#uploadForm').serialize(),
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
});
//Image reader to show pic when selected
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function () {
$('#upload').on('change', function () {
readURL(input);
});
});
var input = document.getElementById( 'upload' );
var infoArea = document.getElementById( 'upload-label' );
input.addEventListener( 'change', showFileName );
function showFileName( event ) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
});
</script>
Assuming you're using ajax to upload the file, you'll need to use a FormData object instead of .serialize()
$.ajax({
data: new FormData($('#uploadForm').get(0)), // use formdata object
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
contentType: false, // required for
processData: false, // jquery ajax file upload
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
You don't add "enctype" in form tag.
Change your code:
<form id="uploadForm">
with:
<form id="uploadForm" enctype='multipart/form-data'>
If this above not working then:
1.install this package by following command:
composer require "laravelcollective/html":"^5.2.0"
2.In config/app add this line:
'providers' => [
// ...
**Collective\Html\HtmlServiceProvider::class,**
// ...
],
and
'aliases' => [
// ...
**'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,**
// ...
],
3.Change Form:
{!! Form::open([ 'action'=> 'NameofController#store', 'method' => 'POST','enctype' => 'multipart/form-data' ]) !!}
<div class="form-group">
{{Form::text('name','' , ['class' =>'form-control'])}}
</div>
<div class="form-group">
{{Form::text('phone','' , ['class' =>'form-control', 'placeholder' => 'phone' ])}}
</div>
<div class="form-group">
{{Form::file('image_name')}}
</div>
{{Form::submit('Submit' , ['class' =>'btn btn-primary' ])}}
{!! Form::close() !!}
you can this way to store your file with custom name:
$path = $request->file('upload')->store('public/upload/' .$fileNameToStore);
I have a user schedule record that I can update easily without one form field called disabled_dates. disabled_dates is setup to store an array of dates a user can add one at a time. What I did was add a form field with its own button using a javascript function disable() in the onclick attribute to update the record.
<div class='input-group text-center'>
{!! Form::text('disabled_dates', null , ['class' => 'form-control text-center datetimepicker15', 'id' => 'disable_date', 'placeholder' => '']) !!}
<span class="input-group-btn">
<button type="button" onclick="disable();" class="btn btn-fab btn-round btn-success">
<i class="material-icons">add</i>
</button>
</span>
Then created the disable(); like so
function disable() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'PUT',
url:'/schedule',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
}
The controller function used is
public function add_blocked_day(Request $request)
{
$schedule = User::find(auth()->user()->id)->schedule;
$current_blocked_dates = $schedule->disabled_dates;
$schedule->disabled_dates = $current_blocked_dates. ','.$request->blocked_date;
$schedule->save();
exit;
}
All Im getting now is too many redirects. The solution Im thinking is to seperate disabled_dates and enclose in its own form tags, because its calling the original form route somehow
I got it to work by changing the function to this
$(document).on("click", ".add-day" , function() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'POST',
url:'schedule/blocked-day',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
});
I am trying to retrieve data from REST API. I got below code from a tutorial which are not working in my machine but working in that video.
<template>
<div>
<h2>Articles</h2>
<div class="card mb-2" v-for="article in articles" v-bind:key="article.id">
<div class="card-header">
{{ article.title }}
</div>
<div class="card-body">
{{ article.body }}
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
articles : [],
article : {
id : '',
title : '',
body : ''
},
article_id : '',
pagination : {},
edit : false
}
},
created(){
this.fetchArticles();
},
methods:{
fetchArticles(){
fetch('api/articles')
.then(res => res.json())
.then(res => {
this.arcticles = res.data;
console.log(res.data);
})
}
}
}
</script>
After few research I changed my code to
<template>
<div>
<h2>Articles</h2>
<div class="card mb-2" v-for="article in articles" v-bind:key="article.id">
<div class="card-header">
{{ article.title }}
</div>
<div class="card-body">
{{ article.body }}
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
articles : [],
article : {
id : '',
title : '',
body : ''
},
article_id : '',
pagination : {},
edit : false
}
},
created(){
axios
.get('api/articles')
.then(res => {
this.articles = res.data.data;
console.log(res.data.data);
})
},
}
</script>
and it's working fine.
I want to fix the previous code (from the tutorial). Otherwise I'll not get further lessons.
From MDN documentation, the json() method is implemented on Response body, and it returns a promise wich resolves to result of parsing the body text as json.
response.json().then(data => {
// do something with your data
});
So, when using in fetch, the correct syntax is:
fetchArticles(){
fetch('api/articles')
.then(res => res.json())
.then(data=> {
this.arcticles = data; // the result here contains only the json data, it is not a response object, so it does not have a 'data' property.
console.log(data);
})
}
Please tell me, I ran into a problem. There is a site based on Laravel 5.5. The site has a multilanguage (two languages en/ru). For multilanguage I'm using:
dimsav/laravel-translatable
mcamara/laravel-localization
Added language files to the directory resources/lang/ru. The problem is the validation of the form. The site has a feedback form in the modal window, working with ajax (sending and validating), error messages are displayed only in the default language, the default language is en. I tried to send data from the form without the help of ajax, everything works well, messages are displayed in both Russian and English.
reoutes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'PagesController#getProfile')->name('profile');
Route::get('/skills', 'PagesController#getSkills')->name('skills');
Route::get('/portfolio', 'PagesController#getPortfolio')->name('portfolio');
Route::get('/resume', 'PagesController#getResume')->name('resume');
Route::post('/contact', 'PagesController#contact');
});
controller
public function contact(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
if ($validator->passes()) {
Mail::to('mycontactform#mail.ru')->send(new Contact($request));
return response()->json(['success'=>'Message sent successfully!']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
js
$(document).ready(function() {
$(".btn-send-message").click(function(e){
e.preventDefault();
$.ajax({
url: "/contact",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
});
var $success_msg = $(".print-success-msg");
var $error_msg = $(".print-error-msg");
function printSuccessMsg() {
$success_msg.html('Message sent successfully!');
$success_msg.css('display','block');
$success_msg.delay(5000).fadeOut(350);
$('#contact-form')[0].reset();
}
function printErrorMsg (msg) {
$error_msg.find("ul").html('');
$error_msg.css('display','block');
$.each( msg, function( key, value ) {
$error_msg.find("ul").append('<li>'+value+'</li>');
});
$error_msg.delay(5000).fadeOut(350);
}
});
form
<div class="modal-body col-md-8 offset-md-2">
<div class="alert alert-danger print-error-msg" style="display:none">
<strong>Errors:</strong>
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none"></div>
{!! Form::open(['id'=>'contact-form']) !!}
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Your Name">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Your Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
<button type="button" class="btn btn-success btn-send-message"><i class="fas fa-paper-plane"></i>
Send Message <span id="loading" style="display: none;"><img class="loader"
src="{{ asset('images/loading.gif') }}"></span>
</button>
{!! Form::close() !!}
</div>
Use LaravelLocalization::getLocalizedURL() which returns an URL adapted to $locale.
So your ajax code will be.
$.ajax({
url: "{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(),'/contact') }}",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
When you return your response try to use this helper __('translated_string')
To use this helper, you have to create some translate.php file in those folders resources/lang/en and resources/lang/en
For example:
File resources/lang/en/translate.php should contain this array
return [
'success_message' => 'Message sent successfully!',
];
File:
resources/lang/ru/translate.php should contain this array
return [
'success_message' => 'Сообщение успешно отправлено!',
];
For example:
return response()->json(['success'=> __('translate.success_message') ]);
To get some translated string, use dot notation for this helper;
Laravel localization helper
I'm using jqgrid with MVC 3.
I have this pages whose code is shown below:
#model VectorCheck.ViewModels.InsertUpdateInvoiceViewModel
#{
ViewBag.Title = "Edit Invoice " + #Model.Invoice.InvoiceNumber;
ViewBag.InvoiceId = (int)#Model.Invoice.InvoiceId;
}
<header class="controllerheader">
<h1>Edit Invoice #Model.Invoice.InvoiceNumber</h1>
</header>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.16.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/EditorHookup.js")" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/jquery.jqGrid-4.1.1/css/ui.jqgrid.css" />
<script src="../../Scripts/jquery.jqGrid-4.1.1/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.jqGrid-4.1.1/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="../../Scripts/Views/Invoice/create.js" type="text/javascript"></script>
<script src="../../Scripts/Views/Invoice/edit.js" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary()
<input type="hidden" id="invoiceid" value="#Model.Invoice.InvoiceId" />
<input type="hidden" id="organisationid" value="#Model.Invoice.OrganisationId" />
<fieldset>
<legend>Invoice</legend>
#Html.HiddenFor(model => model.Invoice.InvoiceId)
#Html.HiddenFor(model => model.Invoice.InvoiceAttachmentId)
#Html.HiddenFor(model => model.Invoice.CreatedByUserName)
#Html.HiddenFor(model => model.Invoice.CreatedDateTime)
#Html.HiddenFor(model => model.Invoice.ProgramManagerId, new { #id = "programmanagerid"})
<div class="columnRightCreate editor-label">
#Html.LabelFor(model => model.Invoice.AreaId)
</div>
<div class="dataRightCreate editor-field">
#Html.DropDownListFor(model => model.Invoice.AreaId, Model.AreaList, new { #id = "areaddl" }, Model.Invoice.ActiveInvoiceLines.Count() == 0)
#Html.ValidationMessageFor(model => model.Invoice.AreaId, "!")
</div>
<div class="invoiceHeaderCreate">
<div class="columnLeftCreate editor-label">
#Html.LabelFor(model => model.Invoice.OrganisationId)
</div>
<div class="dataLeftCreate editor-field">
#Html.DropDownListFor(model => model.Invoice.OrganisationId, Model.OrganisationList, new { #id = "organisationddl" })
#Html.ValidationMessageFor(model => model.Invoice.OrganisationId, "!")
</div>
<div class="columnLeftCreate editor-label">
#Html.LabelFor(model => model.Invoice.InvoiceNumber)
</div>
<div class="dateLeftCreate editor-field">
#Html.EditorFor(model => model.Invoice.InvoiceNumber)
#Html.ValidationMessageFor(model => model.Invoice.InvoiceNumber, "!")
</div>
<div class="columnLeftCreate editor-label">
#Html.LabelFor(model => model.Invoice.InvoiceDate)
</div>
<div class="dataLeftCreate editor-field" id="datepicker">
#Html.EditorFor(model => model.Invoice.InvoiceDate)
#Html.ValidationMessageFor(model => model.Invoice.InvoiceDate, "!")
</div>
<div class="columnRightCreate editor-label">
#Html.LabelFor(model => model.Invoice.TotalExcludingGst)
</div>
<div class="dataRightCreate editor-field">
#Html.EditorFor(model => model.Invoice.TotalExcludingGst)
#Html.ValidationMessageFor(model => model.Invoice.TotalExcludingGst, "!")
</div>
<div class="columnRightCreate editor-label">
#Html.LabelFor(model => model.Invoice.TotalIncludingGst)
</div>
<div class="dataRightCreate editor-field">
#Html.EditorFor(model => model.Invoice.TotalIncludingGst)
#Html.ValidationMessageFor(model => model.Invoice.TotalIncludingGst, "!")
</div>
<div class="columnRightCreate editor-label">
#Html.LabelFor(model => model.Invoice.AllowMoreThanAllowedPercentageToBePaidOverride)
#Html.CheckBoxFor(model => model.Invoice.AllowMoreThanAllowedPercentageToBePaidOverride)
</div>
<div class="columnRightCreate editor-label">
#Html.LabelFor(model => model.Invoice.AllowNumberOfProgressPaymentsOverride)
#Html.CheckBoxFor(model => model.Invoice.AllowNumberOfProgressPaymentsOverride)
</div>
#if (Model.Invoice.ApprovedForPayment == false) {
<div class="columnRightCreate editor-label">
#Html.LabelFor(model => model.Invoice.Rejected)
#Html.CheckBoxFor(model => model.Invoice.Rejected)
</div>
}
</div>
<input type="submit" value="Update" />
</fieldset>
<fieldset>
<legend>Invoice Lines</legend>
<table id="list">
</table>
<div id="pager">
</div>
</fieldset>
}
This deals with and invoice and its associated invoicelines. so the first part is basic MVC update on the invoice details. There are textboxes, selects etc and you press the update button to send the details back to be saved. This works fine if all you do it alter the invoice details.
However bellow that the table with id list is a jqgrid containing invoice lines. The code is:
$("#list").jqGrid({
url: '/InvoiceLine/GridData/' + invoiceId,
datatype: 'json',
mtype: 'POST',
colNames: ['InvoiceLineId', 'InvoiceId', 'Project', 'Amount', 'CreatedByUserName', 'CreatedDateTime', ''],
colModel: [
{ name: 'InvoiceLineId', index: 'InvoiceLineId', hidden: true, key: true, editable: true, editrules: { required: false} },
{ name: 'InvoiceId', index: 'InvoiceId', hidden: true, editable: true, editrules: { required: false }, editoptions: { defaultValue: invoiceId} },
{ name: 'Project', index: 'Project' },
{ name: 'Amount', index: 'Amount', width: 150, align: 'right', formatter: 'number', formatoptions: { thousandsSeparator: "," }, editable: true, editrules: { required: true, custom: true, custom_func: iscurrencycheck} },
{ name: 'CreatedByUserName', index: 'CreatedByUserName', hidden: true, editable: true, editrules: { required: false} },
{ name: 'CreatedDateTime', index: 'CreatedDateTime', hidden: true, editable: true, editrules: { required: false} },
{ name: 'act', index: 'act', width: 55, align: 'center', sortable: false, formatter: 'actions',
formatoptions: { keys: true,
delbutton: false,
//Reload grid so that the price group gets updated after a save
onSuccess: function (rowid) { reload(); }
}
}
],
pager: $('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
viewrecords: true,
imgpath: '',
caption: 'Invoice Lines',
editurl: '/InvoiceLine/Save/',
grouping: true,
groupingView: {
groupColumnShow: false,
groupField: ['Project']
}
});
$("#list").navGrid('#pager', { edit: false, add: true, del: true, search: false }, { }, { width: 500 }, { url: "/../InvoiceLine/Delete" });
});
This does the updates well etc. The problem is it causes problems with the MVC update. If you open the create invoice line dialog and then after closing it click the update button to save the invoice details a jquery validate error is thrown.
d is undefined
[Break On This Error]
....data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:c(a).metadat...
I had a look at the source and I'm pretty sure this is because one you open the dialog for create it contains a form tag and even after you close it this remains on the page though disabled.
Anyone know how to deal with this? Maybe how to get rid of the markup created by the dialog before the update button is pressed?
I suppose that the described problem exists because you placed <table id="list"></table><div id="pager"></div> inside of #using (Html.BeginForm()) {...}. In the grid you use the same column names as in the grid. So you get conflicts in the name of main form and the names in Add form of jqGrid.
I would recommend you to move <table id="list"></table><div id="pager"></div> outinside of #using (Html.BeginForm()) {...}.
As another workaround you can try to destroy edit form after closing. The default behavior of jqGrid is hiding the form only. Even the setting recreateForm: true helps here not because it deletes the previously hidden grid only at the beginning of opening of the form next time. So I suggest that you useonClose which destroy edit/add form directly on closing. The following code can be used somewhere before call of navGrid:
$.extend($.jgrid.edit, {
onClose: function () {
setTimeout(function() {
$("#editmodlist").remove(); // "list" part is the id of the grid
}, 100);
}
});