Symfony: A Button to query the database and popup - javascript

I need to create a button that will automatically search in my database all user with a "secouriste" Attribute set and print their firstname, lastname and phone number in a popup.
Here is what I found from my research:
In my HTML, I have to set a button which will enable a popup modal with id of the user I want to get and under this button, there is the code of my popup modal with a listener.
In my JS, I get the data (which is an object).
In Ajax, I need to pass the ID to my controller.
In PHP, I get the ID with a symfony request and FindOneBy.
But there are different problems with this technique: I dont need to get only one person but a list of person with the good attribute so maybe I should use "FindBy" instead of "FindOneBy", but someone said to me that I should use a custom FindAll(). I'm completely lost right now. Here is what I could gather from posts, I know that's far from right, but this is what I have.
//=============================================
// Recherche PopUp Secouriste
//=============================================
$(document).on('show.bs.modal', '#secouristeModal', function (e) {
var id = $('#secouristeModal').data('id');
$.ajax({
url: 'UserBundle/utilisateur',
method: 'POST',
data: {
id: id
}
}).done(function (data) {
// Si status est égal à true
if(data.status) {
console.log(data);
$('#userTitle').replaceWith(data.user.firstName);
}
}).fail(function (data) {
// Code if error
});
})
PHP
$user = $this->findBy($request->request->get('secouristeAttribute' -> $secouristeAttribute));
if($user) {
return new JSONResponse(array(
'user' => $user
));
} else {
// Faire code de retour avec une erreur (status = false)
}
}
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#secouristeModal">
Liste des secouristes
</button>
<!-- Modal des secouristes-->
<div class="modal fade" id="secouristeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Liste des Secouristes</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- prints a list but doesnt load it from db on request only -->
{% for user in workFlow.listeSecouriste|default('')%}
{% if user.tel is not null %}
<br />{{ user.username }} - {{ user.nom }} {{ user.prenom }} - {{ user.tel }}
{% else %}
<br />{{ user.username }} - {{ user.nom }} {{ user.prenom }}
{% endif %}
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Thank you very much for your help.
Exx

I don't think you can filter your query with a findAll so findBy is good.
But you need to pass an array, something like that:
$users = $this->findBy(['attribute' => $request->request->get('secouristeAttribute')]);
Also, I'm not really sure about that, but before you return your list of Users you could have to implement JsonSerializable Interface with the method jsonSerialize() (or at least the toArray() magic method).

I finally solved my problem, here is how I did it if it can help someone later:
//For my popup
function myAlert(message,titre='Information',btn='',class_msg='',fonction,args) {
//=======================================================
if (btn==''){
btn='<a name="btnOk" class="btn btn-success">Ok</a>';
}
if (class_msg!='') {
message='<div class="'+class_msg+'">'+message+'</div>';
}
myConfirm(message,titre,btn,fonction,args); // Message d'alerte
}
//listeSecouriste.html.twig
<ul>{% for secouriste in listeSecouriste |sort secouriste.nom %}
<li>{{ secouriste.fullName }} {{ secouriste.tel }}</li>
{% endfor %}
</ul>
//php: my controller
public function getSecours($agence=null){
$listeSecouriste = $this->getDoctrine()->getManager()->getRepository('SIGUserBundle:Utilisateur')->ListeSecouriste($agence);
$retour=array('ok'=>false);
if ($listeSecouriste!== null){
$retour['ok']=true;
$retour['html']=$this->renderView('SIGUserBundle:Utilisateur:listeSecouriste.html.twig',
array(
'listeSecouriste'=>$listeSecouriste
)
);
}
return new JsonResponse($retour);
}

Related

EasyAdmin - Add confirm modal on basic actions

I'm trying to update edit/new actions to get a confirmation modal but when I confirm into the modal window, the page page reload and nothing persist in the database.
Any solutions ?
ModuleCrudController (src/Controller/Admin/ModuleCrudController.php) :
public function configureActions(Actions $actions): Actions
{
return $actions
->update(Crud::PAGE_INDEX, Action::NEW,
fn(Action $action) => $action
->setLabel('Ajouter un module'))
->update(Crud::PAGE_INDEX, Action::BATCH_DELETE,
fn(Action$action) => $action
->setLabel('Supprimer'))
->update(Crud::PAGE_NEW, Action::SAVE_AND_ADD_ANOTHER,
fn(Action $action) => $action
->setLabel('Créer et ajouter un nouveau module')
->displayAsLink()
->addCssClass('confirm-action')
->setHtmlAttributes([
'data-bs-toggle' => 'modal',
'data-bs-target' => '#modal-confirm',
]));
ModuleCrudController (src/Controller/Admin/ModuleCrudController.php) :
public function configureAssets(Assets $assets): Assets
{
$assets->addJsFile('assets/js/confirm-modal.js');
return parent::configureAssets($assets);
}
layout.html.twig (templates/bundles/EasyAdminBundle/layout.html.twig) :
{% extends '#!EasyAdmin/layout.html.twig' %}
{% block content_footer_wrapper %}
<div id="modal-confirm" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h4>Êtes-vous sûr ?</h4>
<p>Parce que ça va faire des trucs de fifou</p>
</div>
<div class="modal-footer">
<button type="button" data-bs-dismiss="modal" class="btn btn-secondary">
<span class="btn-label">{{ 'action.cancel'|trans([], 'EasyAdminBundle') }}</span>
</button>
<button type="button" data-bs-dismiss="modal" class="btn btn-success" id="modal-confirm-button">
<span class="btn-label">{{ 'action.confirm'|trans([], 'EasyAdminBundle') }}</span>
</button>
</div>
</div>
</div>
</div>
{% endblock %}
confirm-modal.js (public/assets/js/confirm-modal.js) :
document.addEventListener("DOMContentLoaded",(
function() {
document.querySelectorAll(".confirm-action").forEach((function(e){
e.addEventListener("click",(function(t){
t.preventDefault();
document.querySelector("#modal-confirm-button").addEventListener("click",(function(){
location.replace(e.getAttribute("href"));
}));
}));
}));
}
));

Uploading files in Django using jQuery

I am trying to upload multiple files for a blog post object, however, it seems that my Ajax form is not working properly and I cannot see the files uploading.
Since there is no post object at the time of creating the images, I am trying to upload the files then get them in my view and after saving the post I am trying to save those files by assigning the id of that post to them. Currently, my issue is it seems my files are not uploading and I cannot get them at all.
I am not getting any error and therefore, I cannot find an issue.
Below is my file upload and post create view:
#login_required
def post_create(request):
data = dict()
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(False)
post.author = request.user
#post.likes = None
post.save()
for image in request.FILES.getlist('file'):
instance = Images(post=Post.objects.get(post.id),image=image)
instance.save()
data['form_is_valid'] = True
posts = Post.objects.all()
posts = Post.objects.order_by('-last_edited')
data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request)
else:
data['form_is_valid'] = False
else:
form = PostForm
context = {
'form':form
}
data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request)
return JsonResponse(data)
class PostImageUpload(LoginRequiredMixin, View):
def get(self, request):
images = Images.objects.all()
return render(self.request, 'home/posts/post_create.html', {'images':images} )
def post(self, request):
data = dict()
form = ImageForm(self.request.POST, self.request.FILES)
if form.is_valid():
image = form.save(False)
image.save()
data = {'is_valid': True, 'name': image.file.name, 'url': image.file.url}
else:
data['is_valid'] = False
return JsonResponse(data)
This my javascript code:
$(document).ready(function(){
$(".js-upload-images").click(function () {
$("#fileupload").click();
});
$("#fileupload").fileupload({
change : function (e, data) {
if(data.files.length >= 4){
alert("Sorry, you can only upload up to 4 images")
return false;
}
},
dataType: 'json',
sequentialUploads: true,
start: function (e) {
$("#modal-progress").show();
},
stop: function (e) {
$("#modal-progress").hide();
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
var strProgress = progress + "%";
$(".progress-bar").css({"width": strProgress});
$(".progress-bar").text(strProgress);
},
done: function (e, data) {
if (data.result.is_valid) {
$("#image_list tbody").prepend(
"<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
)
}
}
});
});
HTML Code
{% load crispy_forms_tags %}
{% load static %}
<script src="{% static 'js/image_upload.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/js/vendor/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/js/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/jquery-file-upload/js/jquery.fileupload.js' %}"></script>
<form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" >Create a Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{ form|crispy }}
<div class="my-3 mx-3">
<button type="button" class="btn btn-sm mr-auto btn-primary js-upload-images">
<span><i class="fas fa-camera"></i></span>
</button>
<input id="fileupload" type="file" name="file" multiple
style="display: none;"
data-url="{% url 'home:post-image-upload' %}"
data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
<table id="image_list" class="table table-bordered my-2">
<tbody>
{% for image in images %}
<tr>
<td>{{ image.file.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="modal fade" id="modal-progress" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</form>
The fileupload framework that I am using is working as well as I can see in the terminal Django is successfully completing the get request.
I appreciate all the help in advance!

Ajax request into Bootstrap modal with a load spinner from Symfony controller

I have created a modal to display information about a specific record when I click on the button.
{% for seat in seats %}
<span class="fa-stack fa-lg seat" id="{{ seat.id }}" data-toggle="modal" data-target="#seatModal">
<i style="color: lightgrey;" class="fa fa-stop fa-stack-2x"></i>
<strong style="color: white;" class="fa-stack-1x">
{{ seat.seatNo }}
</strong>
</span>
{% endfor %}
<div class="modal fade seat-details" id="seatModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content"></div>
</div>
</div>
I have an Ajax request that get the information for the specific seat when clicking on that seat icon.
$(document).ready(function () {
$('.seat').click(function() {
var url = Routing.generate('show_seat', {'seat': $(this).attr('id')});
$.get(url, function (data) {
$(".modal-content").html(data);
});
});
});
This ajax call perform a request to the 'show_seat' route which lead to this controller action:
public function showSeatAction(Seat $seat)
{
return $this->render('AppBundle:Seat:seat_details.html.twig', [
'seat' => $seat,
]);
}
This action renders the details in the seat_details.html.twig;
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Seat Details</h4>
</div>
<div class="modal-body table-responsive no-padding">
<table class="table table-modal">
<tbody>
<tr>
<th>Description</th>
<td>{{ seat.desc }}</td>
</tr>
<tr>
<th>Seat Number</th>
<td>{{ seat.seatNo }}</td>
</tr>
<tr>
<th>Status</th>
<td>
{% if seat.status == 'special' %}
<span class="label label-info">{{ seat.status|upper }}</span>
{% elseif seat.status == 'bad' %}
<span class="label label-warning">{{ seat.status|upper }}</span>
{% else %}
<span class="label label-default">{{ seat.status|upper }}</span>
{% endif %}
</td>
</tr>
</tbody>
</table>
</div>
And finally when the Ajax request is done it loads it into the modal as you can see in that Ajax function: $(".modal-content").html(data);.
This works good, but now I'm trying to add a spinner, because what happens now is when I click one the modal opens and the right data displays, but when I close it and open a new one the model opens with the previous data and then when the Ajax is done the text data get replaced in the modal.
But I want to let a spinner show until the Ajax is done and then the complete modal should display.
I've tried to add this:
$(document).on({
ajaxStart: function() { $('.loading').show() },
ajaxStop: function() { $('.loading').hide() }
});
This makes the spinner appear when clicking and hides it when Ajax is done, but the modal still appear too early. So I've tried to modify it to this:
$(document).on({
ajaxStart: function() {
$('.loading').show();
$('.seat-details').hide();
},
ajaxStop: function() {
$('.loading').hide();
$('.seat-details').show();
}
});
But this doesn't change anything.
Can somebody help me out to fix this?
var seatModal = $("#seatModal");//your modal
$(document).on({
ajaxStart: function() {
seatModal.find(".modal-content").html("");//empty modal every ajaxstart
$('.loading').show();
seatModal.modal("hide");//hide
},
ajaxStop: function() {
$('.loading').hide();
seatModal.modal("show");//modal show
}
});
You can process with an other way. Initialize your modal with nothing in it.
Then, when the user close the modal, remove the content and replace it with your spinner.
$(".modal").on("hidden.bs.modal", function(){
$(".modal-content").html([your spinner here]);
});

How to load specific div or id ajax and laravel

i have a comment system on my app in laravel and i can edit my comments with ajax but once edited it doesn't load automatically the edited comment. To see the edited comment i need to reload the page manually. I will put some of the code here.
This is the JS:
var commentId = 0;
var divcomment = null;
$('.edit-comment').click(function(event){
event.preventDefault();
/* Accedemos al Div Que contiene el Panel*/
var divcomment = this.parentNode.parentNode;
/* Buscamos el Contenido con Id display-text */
commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
var commentBody = $(divcomment).find('#display-comment').text();
$('#comment').val(commentBody);
$('#edit-comment').modal();
/* Asignas a tu modal */
});
$('#modal-save').on('click', function(){
$.ajax({
method: 'PUT',
url: urlEdit,
data: {
comment: $('#comment').val(),
commentId: commentId,
_token: token,
_method: 'PUT',
dataType: 'json',
}
})
.done(function (msg){
$(divcomment).text(msg['new_comment']);
$('#edit-comment').modal('hide');
});
});
This is the Html:
<article class="row">
<div class="col-md-3 col-sm-3 hidden-xs">
<figure class="thumbnail">
<img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic }}" />
<figcaption class="text-center">{{ $comment->user->name }}</figcaption>
</figure>
</div>
<div class="col-md-8 col-sm-8">
<div class="panel panel-default arrow left">
<div class="panel-body">
<header class="text-left">
<div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
<time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
</header>
<div id="comment-post" data-commentid="{{ $comment->id }}">
<p id="display-comment">{{ $comment->comment }}</p>
</div>
</div>
<div class="panel-footer list-inline comment-footer">
#if(Auth::guest())
No puedes responder ningún comentario si no has ingresado.
#else
#if(Auth::user() == $comment->user)
Editar Eliminar
#endif
#if(Auth::user() != $comment->user)
Responder
#endif
#endif
</div>
</div>
</div>
</article>
2 variables created on the view
var token = '{{ Session::token() }}';
var urlEdit = '{{ url('comments/update') }}';
and finally the modal where i edit the comment:
<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="comment">Editar comentario</label>
<textarea class="form-control" name="comment" id="comment"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
<button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
</div>
</div>
</div>
</div>
Everything's working but the only thing i need is to load the edited comment back without refresh the whole page, btw i used $('#display-comment').load(document.URL + ' #display-comment'); and with this line i succesfully load the edited comment but, it load all the comments on the edited one, so i have to refresh the whole page to show just the edited.
Assuming that the data sent to the php side of things is the same data that you then want to update to, the following should work:
$('#modal-save').on('click', function(){
var comment = $('#comment').val();
// shove the edited comment into a variable local to the modal handler
$.ajax({
method: 'PUT',
url: urlEdit,
data: {
comment: comment, // reference said variable for ajax data
commentId: commentId,
_token: token,
_method: 'PUT'
},
dataType: 'json'
})
.done(function (msg){
//$(divcomment).text(msg['new_comment']);
// I commented out the above line as it clears the
// divcomment div's text entirely.
// Comment out the below 'if check' if it is not needed.
if (msg.success === true) {
$(divcomment).find('#display-comment').text(comment);
// And overwrite the #display-comment div with the new
// data if the user was successful in editing the comment
}
$('#edit-comment').modal('hide');
});
});
In a previous question of yours, you had a controller method on the php side of things that handled the ajax. Instead of redirecting(since it is ajax, there is no redirect), you should instead return json to indicate whether the action was successful or not. Here is an example of that:
public function update(Request $request)
{
//...
$comment = Comment::find($request['commentId']);
if (Auth::user() != $comment->user) {
return response()->json(['success' => false], 200);
}
//...
return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}
I referenced the above json in my answer on the javascript side of things; if you are not going to use the json response, then simply comment out the line(as I also noted in the code).
Update:
I missed something in your earlier block of code; you declare divcomment outside of the edit link's handler, but then you re-declare it inside of that handler again. I missed this in my earlier answer, so simply deleting the var from it, so it uses the outside declaration, fixes your code:
var commentId = 0;
var divcomment = null; //this is already declared, no reason to declare it
// again
$('.edit-comment').click(function(event){
event.preventDefault();
/* Accedemos al Div Que contiene el Panel*/
divcomment = this.parentNode.parentNode;
// ^ remove the var, making this use the global variable you already
// made above
/* Buscamos el Contenido con Id display-text */
commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
var commentBody = $(divcomment).find('#display-comment').text();
$('#comment').val(commentBody);
$('#edit-comment').modal();
/* Asignas a tu modal */
});

Laravel 4 validation in bootstrap modal

I'm a newbie to Laravel 4, and I'm trying to get a form validation in bootstrap modal.
My modal have a form with a text input and a submit button, and I want that when the validation fails, the modal show me the error.
But the modal, after the validation and the page refresh, is closed.
Here is the code from the controller and the view:
Controller code:
public function postAvatar()
{
$avatar_rules = array(
'avatar_src' => 'url',
);
$validator = Validator::make(Input::all(), $avatar_rules);
$validator->setAttributeNames(User::$names_attr);
if ($validator->passes())
{
$avatar_src = (Input::get('avatar_src'))? Input::get('avatar_src') : URL::asset('assets/images/user/default-user-avatar.png');
$user = User::find(Auth::id());
$user->avatar_src = $avatar_src;
if ($user){
return Redirect::to('dashboard')->withSuccess("Success: avatar updated.");
}
return Redirect::to('dashboard')->withError("Error: an error has occurred.");
}
return Redirect::back()->withErrors($validator);
}
View code:
<!-- Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="avatarModalLabel">Update avatar</h4>
</div>
<div class="modal-body">
<h4><span class="label label-info">Current avatar</span></h4>
<img class="img-circle img-responsive dashboard-avatar" src="{{ $user->avatar_src }}" alt="{{ $user->username }} avatar">
<div class="divider"></div>
<h4><span class="label label-info">New avatar</span></h4>
{{ Form::open(array('url' => 'dashboard/avatar', 'method'=>'post', 'role'=>'form')) }}
<ul>
#foreach($errors->all() as $error)
<div class="alert alert-danger" role="alert">{{ $error }}</div>
#endforeach
</ul>
<div class="form-group">
<label for="avatar_src" class="control-label">Link avatar</label>
<input type="text" name="avatar_src" class="form-control" id="avatar_src" placeholder="Link of avatar image url">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
How can I resolve ?
Thanks.
SOLVED:
Controller code:
public function postAvatar()
{
$avatar_rules = array(
'avatar_src' => 'url',
);
$validator = Validator::make(Input::all(), $avatar_rules);
$validator->setAttributeNames(User::$names_attr);
if ($validator->passes())
{
$avatar_src = (Input::has('avatar_src'))? Input::get('avatar_src') : URL::asset('assets/images/user/default-user-avatar.png');
$user = User::find(Auth::id());
$user->avatar_src = $avatar_src;
if ($user->save()){
if(Request::ajax()){
return Response::json(array('success' => true));
}
}
return Redirect::to('dashboard')->withError("Error: an error has occurred.");
}
return Response::json(array('errors' => $validator->errors()->toArray()));
}
View code:
<!-- Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="avatarModalLabel">Update avatar</h4>
</div>
<div class="modal-body">
<h4><span class="label label-info">Current avatar</span></h4>
<img class="img-circle img-responsive dashboard-avatar" src="{{ $user->avatar_src }}" alt="{{ $user->username }} avatar">
<div class="divider"></div>
<h4><span class="label label-info">New avatar</span></h4>
{{ Form::open(array('url' => 'dashboard/avatar', 'id'=>'avatar_form', 'method'=>'post', 'role'=>'form')) }}
<div class="alert alert-danger avatar_alert" role="alert" style="display: none">
<ul></ul>
</div>
<ul>
</ul>
<div class="form-group">
<label for="avatar_src" class="control-label">Link avatar</label>
<input type="text" name="avatar_src" class="form-control s_tooltip" id="avatar_src" placeholder="Avatar image links">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
Ajax:
<script>
$(document).on('submit', '#avatar_form', function(event){
var info = $('.avatar_alert');
event.preventDefault();
var data = { avatar_src: $("#avatar_src").val() }
$.ajax({
url: "/dashboard/avatar",
type: "POST",
data: data,
}).done(function(response) {
info.hide().find('ul').empty();
if(response.errors)
{
$.each(response.errors, function(index, error){
info.find('ul').append(error);
});
info.slideDown();
}
else if(response.success){
window.location.href = "/dashboard";
}
});
});
</script>
Your best bet would be to validate the form via AJAX to avoid the page reloading entirely. You would then check the response of your AJAX request for the presence of errors and show them inside the modal if they exist.
You could also add in client side validation to prevent the request being made until the rules are satisfied. I wouldn't recommend using this INSTEAD of server side validation but using it ASWELL as is normally quite desirable.
To accomplish this, you'd need to do something along these lines:
Javascript:
Catch submit event of your form and make an AJAX request.
$(document).on('submit', 'form', function(event){
event.preventDefault();
var data = { avatar_src: $("#avatar_src").val(); };
$.ajax({
url: "/dashboard/avatar",
data: data
type: "POST",
}).done(function(response) {
if(response.errors)
{
// Add error to Modal Body
}
else
{
// Show success message, close modal?
}
});
});
Backend:
Modify your controller method to detect if the current request is an AJAX request and if so, return the response in JSON instead of Redirecting. For example:
if(Request::ajax())
{
return Response::json(array('errors' => $validator->messages()));
}
else
{
return Redirect::back()->withErrors($validator);
}
I've not tested any of that code so might contain some typos/errors but hopefully this helps you!
I was facing same issue. After research on internet,I found that Laravel don't support withSuccess('success_msg') method.
return Redirect::to('dashboard')->withSuccess("Success: avatar updated.");
Here is complete discussion on this topic:
https://github.com/laravel/framework/issues/906.
But you can handle this issue with this approach:-
- For Error message:-
[code has to be added in controller]
return Redirect::to('view')->withErrors('your error message.');
[code has to be added in view]
#if(isset($errors) && count($errors->all())>0)
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
- for succcess message:-
[code has to be added in controller]
$success_msg='your success message.';
Session::flash('successMsg', $success_msg);
return Redirect::to('view');
[code has to be added in view]
#if (Session::has('successMsg'))
{{ Session::get('successMsg') }}
#endif
This approach is working fine for me.
For better display of your errors you can use bootstrap css.

Categories