Input::old Laravel by dynamic field - php

I have a dynamic field and I can't get the old value because I added this dynamic field with jQuery, but after validation I don't have the fields.
My jQuery code:
var fielddd = 1;
$(document).on('click', '.btn.add-field', function() {
fielddd++;
$('#newfield').append('<textarea class="from-control" name="somename[]" id="field_' + field + '"></textarea>' + '<button class="btn add-field">add</button>' + '<textarea class="from-control" name="somename2[]" id="field_' + field + '"></textarea>');
});
HTML code:
<div class="row">
<div class="{{($errors->has('somename[]')}}"
<textarea class="from-control" name="somename[]" id="field">
</textarea>
{!! $errors->first('somename[]',:message) !!}
</div>
<button class="btn add-field">add</button>
<div class="{{($errors->has('name[]')}}"
<textarea class="from-control" name="name[]" id="field">
</textarea>
{!! $errors->first('somename[]',:message) !!}
</div>
</div>
<div class="row" id="newfield">
<!-- new textarea -->
</div>
How can I get the same fields with the same input after validation?
I for example some field is empty. If I press add field, and after that pressing the button submit the laravel check if the field is empty and if yes then it redirect to the same page and say to put some value inside the text area.

You could print out the old response in JavaScript in the form, that you could then fetch from. If you printed out old('somefield[]') as JSON, you could then read each value and re-populate the form with textareas.
var oldValues = json_encode(old('somefield[]'))
Then you could use oldValues
oldValues.forEach(function(oldValue) {
// create new textarea using oldValue as value
})

Related

bootstrap-datepicker date vanishes from vue input field when using v-model

I am using bootstrap-datepicker with vue js. The problem is, when I select date it comes to the input field but whenever I shift to another input field, the date vanishes. how do I make the date stay even if I switch to another field. below is my code
$('.datepicker').datepicker();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js" integrity="sha256-bqVeqGdJ7h/lYPq6xrPv/YGzMEb6dNxlfiTUHSgRCp8=" crossorigin="anonymous"></script>
<div class="input-group">
<div class="input-group-prepend">
<span v-bind:style="{ width: prependWidth + 'px' }" class="input-group-text">Acceptance Date</span>
</div>
<input data-provide="datepicker" v-model="formData.acceptance_date" id="acceptance_date" name="acceptance_date" type="text" placeholder="" class="form-control">
</div>
here is my vue data
formData: {
event_name: '',
ba_alt: '',
bn_alt: '',
acceptance_date: ''
},

send data from vuejs to laravel

i have a laravel page which contains a reserve form i redirect my user after selecting date now for number of people and counting the price i use vuejs but i want to pass the data to the laravel form and submit that from laravel with all the other data so here is a part of my code :
your final price
<input type="number" style=" background-color:#fff; border:none" v-model="finalPrice" disabled/>
and here is js part i cuted out code for better reading :
<script>
this.epic_price = this.sum_price + (this.total_price * this.sum_day)
this.$emit('input', this.epic_price)
</script>
although this form is not complete yet but i want to use it here in this page so i just paste it consider the form is not complete at all :
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed"
action="/properties/savereserve/" method="post">
<div class="row">
#foreach($price as $key => $prices)
<div class="col-lg-2 text-center">
{{$date[$key]}}
<hr>
{{$prices}}
</div>
#endforeach
</div>
</form>
//exacly on the same page i use my vue component so they are on the same page
<reserve
:sum_price="{{$sumprice}}"
:sum_day="{{$sumday}}"
:base_price="{{$property->base_price}}"
:property_id="{{$property->id}}"
:user_id="{{Auth::user()->id}}"
></reserve>

How to properly convert this working example to use ajax? (show details based on radio button selection)

I have a page to edit the administrators of a post.
In this page there are some radio buttons. Each radio button corresponds to a administrator of a post (ex: John, Jake, etc). When a radio button is selected the details of that administrator (name, email, etc) should be populated in the form fields. There is also a radio button "create new admin" that should reset the form fields when is selected.
I did this without ajax but now Im trying to replicate what I have but using ajax, that is, load each admin details and populate the form fields with that details, based on radio button selection, through an ajax request.
I have this ajax code in the view file but Im in doubt if its correct and how to, after get the administrators details, populate the form fields with the selected administrator/ selected radio button. Do you know how to do that?
Ajax code in the view file:
<script type="text/javascript">
$(document).ready(function () {
$("input[name='radiobutton']").click(function() {
let id = $(this).attr("id");
$.get('post/edit/'+ id+ '/admins', function(administrators) {
});
});
});
</script>
Below I have the Full working code example without Ajax:
Form in the view file:
<form method="post" class="clearfix" action="{{route('admins.update', ['id' => $post->id])}}" enctype="multipart/form-data">
{{csrf_field()}}
#foreach($administrators as $admin)
<div class="form-check">
<input class="form-check-input" type="radio" name="radiobutton" id="{{$admin->id}}" value="{{$admin->id}}">
<label class="form-check-label" for="">
{{$admin->name}}
</label>
</div>
#endforeach
<div class="form-check">
<input class="form-check-input" type="radio" name="radiobutton" id="create_administrator"
value="option2">
<label class="form-check-label" for="exampleRadios2">
Create new administrator
</label>
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" required class="form-control" value="{{ $admin->name }}" name="name">
</div>
<!-- below I have more form fields like administrator name, email, etc -->
<input type="submit" id="adminStoreButton" class="btn btn-primary" value="Create"/>
<input type="submit" id="adminUpdateButton" class="btn btn-primary" value="Update"/>
</form>
JS to populate the form fields based on radio button (administrator) selection:
$(document).ready(function () {
$("#adminStoreButton").hide();
var admins = {!! $admin !!}
$("input[name='radiobutton']").click(function() {
if($(this).attr("id") == "create_administrator"){
$("#adminUpdateButton").hide();
$("#adminStoreButton").show();
$("#edit_administrator").attr('action', '{{route('admins.store', ['post_id' => $post->id])}}');
}
else{
$("#adminUpdateButton").show();
$("#adminStoreButton").hide();
$("#edit_administrator").attr('action', '{{route('admins.update', ['post_id' => $post->id])}}');
}
let id = $(this).attr("id");
let data = admins.find(e => e.id == id) || {
name: "",
email: "",
...
};
$("input[name='name']").val(data.name);
$("input[name='email']").val(data.email);
...
});
});
Administrator controller edit method that returns the view with the edit administrators form above:
public function edit($id)
{
$post = Post::find($id);
$administrators = Administrator::where('post_id', $id)->get();
return view('administrators.edit')
->with('post', $post)
->with('administrators', $administrators));
}
edit and update routes
Route::get('post/edit/{id}/admins', [ 'uses' => 'AdminController#edit', 'as'=>'admins.edit']);
Route::post('post/update/{id}/admins', [ 'uses' => 'AdminController#update', 'as'=>'admins.update']);
Administrator controller update method:
public function update(Request $request, $id){
$this->validate($request, [
'name' => 'required|string',
...
]);
$adminToUpdate = Administrator::find($request->radiobutton);
$adminToUpdate->name = $request->name;
...
$adminToUpdate->save();
return redirect()->back();
}
}
Your markup and scripts don't look clean also makes everything complicated so, I will tell you how to accomplish this in the best way step by step
1) create a form markup to be populated once queried via ajax
something like below
<form class="myForm" action="">
<input type="text" name="firstname" value="">
<input type="text" name="lastname" value="">
... and so on...
<button class="actionButton" type"button" data-action="create">update</button>
</form>
2) you need a function to query the admin like below
function queryAdmin(id){
$('.myForm')[0].reset();
return $.post(queryEndPoint, {id: id}, function(response){
$('.actionButton').attr('data-action', 'update');
$('.myForm').find('input[name="firstname"]').val(response.firstname);
$('.myForm').find('input[name="lastname"]').val(response.firstname);
.... and so on ....
});
}
3) now the for loop to get admin list
#foreach($administrators as $admin)
<button class="adminButton btn" data-id="{{ $admin->id }}"></button>
#endforeach
4) now code to query admin when clicked button
$('.adminButton').click(function(){
queryAdmin($(this).attr('data-id'));
});
this will fill the form with admin details
5) now update/create form function
function updateOrCreate(endPoint){
$('.updateMe').click(function(){
$.post(endPoint, $('.myForm').serialize(), function(){
alert('done');
}).fail(function(){
alert('something error occured !!!');
});
});
}
6) update or create action
$('.actionButton').click(function(){
if($(this).attr('data-action') == 'update')
updateOrCreate(updateEndpoint);
else
updateOrCreate(createEndpoint);
});
now it will submit the form with update request once queried admin
now I hope rest you can do in this way best of luck

How to disable buttons on ng-blur when data doesn't match from database while changing the value of drodown

I have two columns and 3 buttons in a form and i am using data-ng-blur to disable these buttons until user id and password don't match in database. and it's working fine for the first time but when i change the user id with the same password without refreshing the page, my form buttons are still enabled while the password is incorrect. solutions please.
<div class="row">
<div class="col-md-6">
<label class='control-label'>Executive Name*</label>
<select class='form-control' data-ng-model="visit.executive_id" type="text" >
<option value="" disabled>---Select Executive---</option>
<option data-ng-repeat="exe in executive track by $index" value="<%exe.value%>"><%exe.text%></option>
</select>
</div>
<div class="col-md-6">
<label class='control-label'>Password* (Use your Mob. No)</label>
<input type="password" class='form-control' name="password" data-ng-blur="login()" data-ng-model="visit.password" type="text">
</div>
</div>
<div class='col-md-offset-4 col-md-4'>
<button class='btn-lg btn-block btn-primary' data-ng-click="visitsite()" ng-disabled="valid">
<center>Site Visit Receipt</center>
</button>
<button class='btn-lg btn-block btn-primary' data-ng-click="printblank()" ng-disabled="valid">
<center>Blank Site Visit</center>
</button>
<button class='btn-lg btn-block btn-primary' data-ng-click="propvisit()" ng-disabled="valid">
<center>Blank Property Visit</center>
</button>
</div>
Controller
angular.extend($scope, {
valid: true,
login: function () {
var credentials = $scope.visit;
$serviceModel.login(credentials).then(function (result) {
if (result.data.success) {
$scope.valid = false;
}
else {
$scope.valid = true;
alert('Incorrect Password');
}
});
}
}])
My guess is that your problem lies in a fact that login() function is not invoked when you change user id. Password field has data-ng-blur directive to trigger login() function once focus is lost on password field for your functionality to work while a similar directive for select element (which is responsible for user id selection) is missing for desired functionality to work.
Instead of
<select class='form-control' data-ng-model="visit.executive_id" type="text" > ...
try using
<select class='form-control' data-ng-model="visit.executive_id" data-ng-blur="login()" type="text" > ...
While we are at it by using directives for select element, instead of using data-ng-model directive, you can use ng-change directive that is specialised for select element use, see https://docs.angularjs.org/api/ng/directive/select#usage
<select class='form-control' data-ng-model="visit.executive_id" ng-change="login()" type="text" > ...
Good luck.

How to add functions in Bootstrap modal - Laravel

I'm currently developing a system with Laravel framework. Though, I'm not very familiar with MVC architecture yet.
When I'm developing the system, I come across a problem which relates with this bootstrap modal that has a form in it. I'd like to put functions in it so that it could be submitted to the database.
I have followed several tutorials, but didn't come up with a solution because they're all using pages instead of modals.
So, here is the HTML of the modal:
<div class="modal hide fade" id="linkSettings">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add New Link</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="focusedInput">Add A Link:</label>
<div class="controls">
<textarea class="autogrow"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>
Here is the Javascript of the above modal:
$('.btn-settingLink').click(function(e){
e.preventDefault();
$('#linkSettings').modal('show');
});
Now, how do I put the function in the Controller so that whenever a user presses Save Changes button, it will store the value in <textarea> into the database? Is there anything to do with the Javascript code? and Do I need to use {{Form::open('main/addLink','POST')}} at the form to pass its values to the controller and model?
Basically, all I ever wanted was to have the CRUD functions by using modal.
First you need to create a form with a route....
<form method="post" action="{{URL::to('Link/addlink')}}>
Or like you showed above, with your Blade {{Form}} ...either way
Then your textarea needs an id and name
<textarea id="mytext" name="mytext"></textarea>
So your HTML becomes...
<form method="post" action="{{URL::to('Link/addlink')}}>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="focusedInput">Add A Link:</label>
<div class="controls">
<textarea id="mytext" name="mytext" class="autogrow"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
Close
<input type="submit" id="submit" name="submit" class="btn btn-primary">Save changes</input>
</div>
</form>
Then in your Link controller...or wherever you're actually sending this form..no idea what your controllers are named :)
public function addlink(){
$input = Input::all();
//whatever validation you wanna do, with error handling etc...not gonna provide that, thats up to you
$yourmodel = New Model;
$yourmodel->text = $input['mytext'];
$yourmodel->save();
Return Redirect::back();
}
EDIT (for Ajax)
Add this script at the bottom of your page...
<script>
$(document).ready(function(){
$('input#submit').click(function(e){
e.preventDefault();
var text = $('#mytext').val();
var url = 'your url' //we were using Link/addlink in the other example
$.ajax({
type: "POST",
url: url,
data: { mytext: text },
success: function(){
//Probably add the code to close your modal box here if successful
$('#linkSettings').hide();
},
});
});
});
</script>
PS Completely untested....you will need some tweaking, plus the fact that your controller has the Redirect will probably make it not work since this will just be expecting an echoed Json string
But these are the nuts and bolts, and the foundation is there for you to continue on your own I would think...

Categories