I need help to solve my problem. I have a page with my list of "equipos". Every "equipo" in the table has an Edit buttom, and the page show another buttom to add new "equipos".
So far I manage to call a modal for NEW using the {{ render() }} syntax, the equipoNewModal works fine because is an "static" route (/equipo/new) in Symfony; but the EDIT don't work because I can't pass the "equipo" variable to the equipoEditModal and get the id to complete the route (/equipo/{id}/edit) and call the controller.
Symfony can't render the page and return an error: Variable "equipo" does not exist.
The controller isn't the problem, if I create an tag with href={{ path('edit_equipo', {'id': equipo.id}) }} in the list.html.twig template and skip the modal I can edit every equipo. To dismiss the controller, if I hardcoded the line:
{{ form_start(equipoForm, {'action': path('edit_equipo', {'id': equipo.id})}) }}
in the edit.html.twig to:
{{ form_start(equipoForm, {'action': path('edit_equipo', {'id': 1})}) }}
the edit action works, of course for every equipo the edit action call the edition of the item with id=1 in the database, but it say that the controller works fine.
I'm missing something and hope the community find the solution... sorry my english.
==============
list.html.twig
<table id="datatable-buttoms" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>EQUIPOS</th>
</tr>
</thead>
<tbody>
{% for equipo in equipos %}
<tr>
<td>{{ equipo.id }}</td>
<td>{{ equipo.equipo }}</td>
<td>{{ equipo.nomenclador }}</td>
<td>{{ equipo.nomenclador.especialidad }}</td>
<td>
<button type="button" class="btn btn-primary" href="" data-toggle="modal" data-target="#equipoEditModal">
Editar
</button>
<button type="button" class="btn btn-danger" href="" data-toggle="modal" data-target="#equipoDeleteModal">
Eliminar
</button>
</td>
</tr>
{{ render(controller('AppBundle:Equipo:edit', {'id': equipo.id})) }}
{% endfor %}
</tbody>
</table>
<button type="button" class="btn btn-primary" href="" data-toggle="modal" data-target="#equipoNewModal">
Agregar
</button>
{{ render(controller('AppBundle:Equipo:new')) }}
=============
new.html.twig
<div class="modal fade" id="equipoNewModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">NUEVO</h4>
</div>
<div class="modal-body">
{{ form_start(equipoForm, {'action': path('new_equipo')}) }}
{{ form_widget(equipoForm) }}
<button type="submit" class="btn btn-primary">Guardar</button>
{{ form_end(equipoForm) }}
</div>
</div>
</div>
</div>
==============
edit.html.twig
<div class="modal fade" id="equipoEditModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">EDITAR</h4>
</div>
<div class="modal-body">
{{ form_start(equipoForm, {'action': path('edit_equipo', {'id': equipo.id})}) }}
{{ form_widget(equipoForm) }}
<button type="submit" class="btn btn-primary">Guardar</button>
{{ form_end(equipoForm) }}
</div>
</div>
</div>
</div>
===============
Edit Controller
/**
* #Route("/equipo/{id}/edit", name="edit_equipo")
*/
public function editAction(Request $request, Equipo $equipo)
{
$form = $this->createForm(EquipoFormType::class, $equipo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$equipo = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($equipo);
$em->flush();
return $this->redirectToRoute('list_equipos');
}
return $this->render('sysreport/equipos/edit.html.twig', [
'equipoForm' => $form->createView(),
]);
}
EDIT:
To solve the problem only add the line that #Nobady says in the editAction controller...
To call every modal depending of the equipo change data-target in the list.html.twig file:
<button type="button" class="btn btn-primary" href="" data-toggle="modal" data-target="#equipo{{ equipo.id }}">
and of course in the edit.html.twig file too:
<div class="modal fade" id="equipo{{ equipo.id }}">
to solve then you have to pass equipo as parameter, like this in Edit Controller:
/**
* #Route("/equipo/{id}/edit", name="edit_equipo")
*/
public function editAction(Request $request, Equipo $equipo)
{
$form = $this->createForm(EquipoFormType::class, $equipo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$equipo = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($equipo);
$em->flush();
return $this->redirectToRoute('list_equipos');
}
return $this->render('sysreport/equipos/edit.html.twig', [
'equipoForm' => $form->createView(),
'equipo' => $equipo
]);
}
Related
I'm trying to have an edit form in a modal but this edit form is not working in the context.
It is working when I try the form directy in a webpage using the URI address but it is not when I try it in my page context. I'm gonna explain more ...
In my webpage, I have a render controller :
<div class="card">
<div class="body">
{{ render(controller('AppBundle:Classeur3:vacation', {'request':app.request , 'id': zone.id})) }}
</div>
</div>
This controller retrieve somme Entities and display a table as following :
<table id="sites-list" class="table table-bordered datatable">
<thead>
<tr>
<th>Employé</th>
<th>Heure d'entrée</th>
<th>Heure de sortie</th>
<th>Durée</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for v in vacations %}
<tr id="tr-vacation-{{ v.id }}">
<td>{{ v.user }}</td>
<td>{{ v.entryTime|date }}</td>
<td>{{ v.exitTime|date }}</td>
<td>{{ v.totalTime }}</td>
<td style="width: 150px;">
<button onclick="$('#modal').modal({remote: '{{ path('edit_vacation', {'id': v.id}) }}' });" type="button" class="btn btn-circle waves-effect waves-circle waves-float" style="margin-right: 5px;">
<i class="material-icons">search</i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
My edit_vacation ressource is defined bby the following route :
edit_vacation:
path: /vacation/{id}/edit
defaults: { _controller: AppBundle:Classeur3:editVacation }
This is my controller function :
public function editVacationAction(Request $request, $id){
$vacation = $this->getDoctrine()->getRepository(Answ31Vacation::class)->find($id);
$form = $this->createForm(Answ31VacationType::class, $vacation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($vacation);
$entityManager->flush();
//Message
$this->addFlash('success', 'Vacation mise à jours');
//Redirect to Zone edit page
return $this->redirectToRoute('zone_edit', array('id' => $vacation->getZone()->getId()));
}
return $this->render('AppBundle:Classeur3:edit_vacation.html.twig', array(
"form" => $form->createView()
));
}
And here is my view :
<div class="modal-body">
<div class="row">
<div class="col-sm-12">
{{ form(form) }}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">Fermer</button>
</div>
The modal is perfectly displayed, but when I submit the form, the page is reloaded as planed but the data are not updated.
When I try to call directly in URL my ressource ( baseurl/vacation/1/edit ) I have the form and the modifications are working, when I press my submit button the data are updated.
Any thought ?
In your editVacationAction you should try setting the target action of your form, like this
$form = $this->createForm(Answ31VacationType::class, $vacation, ["action"=>$this->generateUrl('edit_vacation']);
But when you submit, the page will change and you will loose the modal without some extra JavaScript.
I'm currently working on a private social network for fun and to improve my skills.
Anyway, I want to display a form to leave a comment on a post using a loop but I have issues trying that.
I'm using Symfony, twig and bootstrap, and I'd like to keep js, jquery or ajax away.
Here is my code:
My form builder:
class CommentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', null, [
"label" => "Your title"
])
->add('content', null, [
"label" => "Your content"
])
->add('submit', SubmitType::class, [
"label" => "Publish your shitty comment!"
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
]);
}
}
and my view:
<ul class="nav col-4 offset-3">
{% for post in posts %}
<li class="postItem">
<article class="postItem">
<p> {{ post.title }} </p>
<img id="postPics" src="{{ asset('./pictures/posts/' ~ post.picture) }}">
{{ form(leaveCommentForm) }}
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<author>{{ post.user.username }}</author>
<div class="commentPost">
{% for comment in post.comments %}
<article>
<h6 style="font-weight: bold">{{ comment.title }} -
By
<author>{{ comment.user.username }}
on {{ comment.dateCreated | date('Y-M-d') }}</author>
</h6>
<p>{{ comment.content }}</p>
</article>
{% endfor %}
</div>
<input type="hidden" value="{{ post.id }}" name="postId"> {{ post.id }}
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Leave a comment
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Leave a comment</h4>
</div>
<div class="modal-body">
{{ form_start(leaveCommentForm) }}
<input type="hidden" value="{{ post.id }}" name="postId"> {{ post.id }}
{{ form_end(leaveCommentForm) }}
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</article>
</li>
{% endfor %}
</ul>
As you can see I want to display my form on each iteration of post (with or without modal I don't really care I was just trying some things).
My problems here are:
*If I use a modal, I can't get my post.id inside my modal and so I can't send it to my controller.
Actually I get the value of first post.id for every posts.
*If I don't use a modal I can't even see my form on my page.
If you have a solution that would be great!
Thanks in advance guys!
I'm currently running into a very confusing problem with Symfony 4 (or not even that, I don't know). I've set up a login/registration system manually, which has been working great, up until now. I've developed a form where one can create branches for their main company. I used a FormType for that exact manner:
<?php
// src/Form/UserType.php
namespace App\Form;
use App\Entity\Filiale;
use App\Entity\Kammer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class FilialType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('apothekenname', TextType::class)
->add('email', EmailType::class)
->add('anrede', TextType::class)
->add('titel', TextType::class, array(
'required' => false
))
->add('vorname', TextType::class)
->add('name', TextType::class)
->add('adresszusatz', TextType::class, array(
'required' => false
))
->add('strasse', TextType::class)
->add('hausnummer', TextType::class)
->add('plz', NumberType::class)
->add('ort', TextType::class)
//->add('kammer', TextType::class)
->add('kammer', EntityType::class, array(
'class' => Kammer::class,
'choice_label' => 'name',
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Filiale::class,
));
}
}
?>
The view rendering the FormType looks like this, where there's a separate button triggering the Bootstrap modal dialog:
<div class="modal fade" id="modal-add-filiale" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Neue Filialapotheke anlegen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Schließen">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{ form_start(form_add_filiale) }}
<div class="form-group row">
<label class="col-xl-3" for="filiale-apothekenname">Apothekenname</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.apothekenname) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-anrede">Anrede</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.anrede) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-titel">Titel</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.titel) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-vorname">Vorname</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.vorname) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-name">Name</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.name) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-strasse">Straße</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.strasse) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-hausnummer">Hausnummer</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.hausnummer) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-adresszusatz">Adresszusatz</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.adresszusatz) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-plz">PLZ</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.plz) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-stadt">Stadt</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.ort) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-email">Email</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.email) }}
</div>
</div>
<div class="form-group row">
<label class="col-xl-3" for="filiale-kammerbezirk">Kammerbezirk</label>
<div class="col-xl-9">
{{ form_widget(form_add_filiale.kammer) }}
</div>
</div>
<button type="submit">Hu</button>
{{ form_end(form_add_filiale) }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Abbrechen</button>
<button id="modal-add-filiale-save" type="submit" class="btn btn-primary">Speichern</button>
</div>
</div>
</div>
</div>
The Controller function processing the form, renderung and submission looks like this:
public function login(Request $request, AuthenticationUtils $authUtils, AuthorizationCheckerInterface $authChecker) {
$isLoggedIn = ($authChecker->isGranted('ROLE_USER') || $authChecker->isGranted('ROLE_USER_MO'));
if($isLoggedIn) {
$filiale = new Filiale();
$form = $this->createForm(FilialType::class, $filiale);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$filiale->setUser($this->getUser());
$em = $this->getDoctrine()->getManager();
$em->persist($filiale);
$em->flush();
return $this->render('default/startpage_loggedin.html.twig', array(
'breadcrumb' => 'BROTKRUMEN',
'form_add_filiale' => $form->createView(),
'toast_finished' => 1,
));
}
return $this->render('default/startpage_loggedin.html.twig', array(
'breadcrumb' => 'BROTKRUMEN',
'form_add_filiale' => $form->createView(),
));
}
else {
// get the login error if there is one
$error = $authUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authUtils->getLastUsername();
return $this->render('default/startpage_loggedout.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
}
While the code isn't perfectly arranged and I'm probably missing some best practices, I still find the problem I'm facing weird. The form is only accessible while logged in - when I click the button to open the modal, then fill the form out and then press the submit button, I'm automatically getting logged out and the error message "invalid credentials" is displayed.
However, when I'm outsourcing the form rendering and form handling to a new view and a new controller function, the code does exactly what it's supposed to do, without touching the logged in user.
I'm basically running out of ideas and would appreciate any hint you guys could offer. Thank you in advance!
Edit: Security.yml
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
App\Entity\User:
algorithm: bcrypt
legacy_encoder:
algorithm: md5
encode_as_base64: false
iterations: 1
providers:
in_memory: { memory: ~ }
db_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
#pattern: ^/
#http_basic: ~
anonymous: ~
provider: db_provider
user_checker: App\Security\UserChecker
logout:
path: /logout
target: /
form_login:
login_path: home
check_path: home
access_control:
- { path: ^/motivwelten, roles: ROLE_USER }
- { path: ^/services/.*, roles: ROLE_USER }
- { path: ^/shop, roles: ROLE_USER }
- { path: ^/shop/.*, roles: ROLE_USER }
erase_credentials: false
While not a direct solution to the initial question I asked, I fixed the problem by moving every logic but the login away from the login method in my controller.
This should probably be the better practice anyways. I believe submitting to the /login route tirggers a login event and, as there are no credentials, the service can't verify the user and terminates the session while displaying "invalid credentials" as well.
I have a problem. Someone could tell me can i use couple forms in one vie on one route? I mean i have three forms with post method in show.blade.php in show function in ProfileController which showing users profiles. I posting 3 forms in this view,and in route i have something like this:
Route::post('profile/{id}', MessageController#store');// this is private message to other user
Route::post('profile/{id}', CommentController#store'); //this is comment to profile
Route::post('profile/{id}', CommentController#storeCommit'); // this is answer to comment profile
I dont know what i doing wrog,but this isdont work,i mean if i delete CommitStore route i can send message and add comment,but if i add this storeCommit i cant add comment,because i getting error, field from storeCommit cannot be null. Tomorrow i add code from controllers and view. Someone have any idea, please, help me, thanks.
This is View which has three forms, Sending Messages, Adding Comment to Profile and Adding Answer to Comment in profile:
#extends('layout')
#section('content')
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Informacje</li>
<li role="presentation">Postacie</li>
<li role="presentation">Posty</li>
<li role="presentation">Komentarze</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="info">
<table class="table table-bordered">
<tr class="active">
<td> Avatar </td>
<td> Informacje </td>
</tr>
<tr class="info">
<td>
<img src="{{$user->avatar}}" width="150px" height="150px" alt="Avatar" class="img-circle"> <BR /><BR />
#if(!\Auth::guest() && $user->id == \Auth::user()->id)
<a style="text-align:right" href="/profile/{{$user->id}}/edit"<button type="button" class="btn btn-primary btn-xs">Edytuj profil</button></a>
#endif
#if(!\Auth::guest() && \Auth::id() != $user->id)
<button style="float:right" type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-pencil"></span>
</button>
#endif
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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" id="myModalLabel">Wyślij wiadomość do {{$user->name}}</h4>
</div>
<div class="modal-body">
{!! Form::model(['method' => 'POST', 'action' => ['MessageController#store', $user->id]]) !!}
<div class="form-group">
{!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź tytuł wiadomości' ]) !!}
</div>
<div class="form-group">
{!! Form::textarea('message', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź wiadomość' ]) !!}
</div>
{!! Form::hidden('mess_to_user', $user->id) !!}
{!! Form::hidden('from_user_name', $user->name) !!}
</div>
<div class="modal-footer">
{!! Form::submit('Wyślij wiadomość', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
#include('errors.list')
</div>
</div>
</div>
</td>
<td width="960">
{!!$user->showName($user->name)!!}
#if($user->is_online == 1)
<span class="label label-success">Online</span>
#else
<span class="label label-danger">Offline</span>
#endif
<BR />
#foreach($user->group as $group)
<strong>Grupa użytkownika:</strong> {{$group->name}}
#endforeach
<BR />
<strong>Dołączył dnia:</strong> {{$user->created_at->diffForHumans()}} <BR />
<strong>Wiek: </strong>{{$user->age}}
<strong>Płeć: </strong>{{$user->formatSex($user->sex)}} <BR />
<div class="panel panel-primary">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Sygnatura użytkownika {{$user->name}}
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">
#if(empty($user->signature))
Brak sygnatury
#else
{!! $user->signature !!}
#endif
</div>
</div>
</div>
</td>
</tr>
</table>
<table class="table table-condensed">
<!-- Tabela na KONTAKTY-->
<tr>
<!--SOCIAL-->
<td>
<table class="table table-condensed">
<tr>
<td class="active">
#if(empty($user->skype))
<img src="http://a3.mzstatic.com/eu/r30/Purple6/v4/1e/0c/96/1e0c9683-1019-f450-f07e-017b6f0012c6/icon175x175.png" width="16" height="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://a3.mzstatic.com/eu/r30/Purple6/v4/1e/0c/96/1e0c9683-1019-f450-f07e-017b6f0012c6/icon175x175.png" width="16" height="16" /> {{$user->skype}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->facebook))
<img src="http://blogs-images.forbes.com/peterhimler/files/2014/02/high-res-logo_facebook1.png" width="16" height="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://blogs-images.forbes.com/peterhimler/files/2014/02/high-res-logo_facebook1.png" width="16" height="16" /> {{$user->facebook}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->twitter))
<img src="http://health.uri.edu/files/twitter.png" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://health.uri.edu/files/twitter.png" height="16" width="16" /> {{$user->twitter}}
#endif
</td>
</tr>
</table>
</td>
<!--GAME-->
<td width="50%">
<table class="table table-condensed">
<tr>
<td class="active">
#if(empty($user->xfire))
<img src="http://img06.deviantart.net/ebd6/i/2008/045/6/3/xfire_enhanced_icon_by_sparticusx.jpg" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://img06.deviantart.net/ebd6/i/2008/045/6/3/xfire_enhanced_icon_by_sparticusx.jpg" height="16" width="16" /> {{$user->xfire}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->steam))
<img src="http://vignette3.wikia.nocookie.net/clickerheroes/images/5/54/Logo-Steam.png/revision/latest?cb=20150529052012" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://vignette3.wikia.nocookie.net/clickerheroes/images/5/54/Logo-Steam.png/revision/latest?cb=20150529052012" height="16" width="16" /> {{$user->steam}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->origin))
<img src="https://pbs.twimg.com/profile_images/525760420192083969/Tv_fRfVF_400x400.png" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="https://pbs.twimg.com/profile_images/525760420192083969/Tv_fRfVF_400x400.png" height="16" width="16" /> {{$user->origin}}
#endif
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div role="tabpanel" class="tab-pane" id="postacie">
<table class="table table-bordered">
<tr class="active">
<td>
#forelse($user->player as $player)
<button type="button" style="width:200px; height:200px" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal{{$player->id}}">{!!$player->checkActive($player->active)!!}<BR />{!! Html::image('skin/Skin_'.$player->skin.'.png') !!}<BR/>
{{$player->formatName($player->name)}} </button>
#empty
#if(!\Auth::guest() && $user->id == \Auth::user()->id)
<center><p><h1><span class="glyphicon glyphicon-plus-sign"></span></h1></p></center>
#else
<center><h1><span class="label label-default">Brak postaci!</span></h1></center>
#endif
#endforelse
</td>
</tr>
</table>
</div>
<div role="tabpanel" class="tab-pane" id="posty">...</div>
<div role="tabpanel" class="tab-pane" id="komentarze">
<BR />
#if(!\Auth::guest())
<div class="panel panel-warning">
<div class="panel-heading">
Dodaj komentarz do profilu użytkownika {!!$user->showName($user->name)!!}
</div>
<div class="panel-body">
{!! Form::model(['method' => 'POST', 'action' => ['CommentController#store', $user->id]]) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź komentarz do tego profilu ' ]) !!}
</div>
{!! Form::hidden('to_user', $user->id) !!}
<div class="form-group">
{!! Form::submit('Dodaj komentarz', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
#include('errors.list')
</div>
</div>
#endif
#forelse($user->queryComment($comments, $user->id) as $com)
<div class="panel panel-primary">
<div class="panel-heading">
Komentarz od <a style="color:white" href="/profile/{{$com->user_id}}">{{$com->name}}</a> <span class="label label-warning">{{$com->created_at}}</span>
#if(!\Auth::guest())
<button style="float:right" type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal{{$com->id}}">
<span class="glyphicon glyphicon-plus-sign"></span>
</button>
#endif
</div>
<div class="panel-body">
{{$com->comment}}
</div>
<div class="panel panel-success">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{$com->id}}" aria-expanded="false" aria-controls="collapseOne">
Pokaż wszystkie komentarze
</a>
</h4>
</div>
<div id="collapse{{$com->id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
#forelse($user->queryCommit($commits, $com->id) as $commit)
<div class="panel-body">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Podkomentarz od {{$commit->user_name}} <span class="label label-warning">{{$commit->created_at}}</span> </h3>
</div>
<div class="panel-body">
{{$commit->body}}
</div>
</div>
</div>
#empty
<div class="panel-body">
Brak podkomentarzy!
</div>
#endforelse
</div>
</div>
<div class="modal fade" id="myModal{{$com->id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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" id="myModalLabel">Dodaj komentarz</h4>
</div>
<div class="modal-body">
{!! Form::model(['method' => 'POST', 'action' => ['CommentController#storeCommit', $user->id]]) !!}
<div class="form-group">
{!! Form::text('body', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź adnotację do wybranego komentarza ' ]) !!}
</div>
{!! Form::hidden('to_comment', $com->id) !!}
{!! Form::hidden('to_user_com_id', $user->id) !!}
</div>
<div class="modal-footer">
{!! Form::submit('Dodaj komentarz', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
#include('errors.list')
</div>
</div>
</div>
</div>
#empty
<p>Brak komentarzy w profilu</p>
#endforelse
{!!$comments->render()!!}
</div>
#include('errors.list')
#foreach($user->player as $p)
#include('character.show')
#endforeach
</div>
#stop
This is MessageController and CommentController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\CommentRequest;
use App\Http\Requests\CommitRequest;
use App\Comment;
use App\Commit;
class CommentController extends Controller
{
public function store(CommentRequest $request)
{
\Auth::user()->comment()->create([
'comment' => $request->input('comment'),
'to_user' => $request->input('to_user'),
'from_name' => \Auth::user()->name
]);
flash()->success('Komentarz został dodany!');
return redirect('/profile/'.$request->input('to_user').'');
}
public function storeCommit(CommitRequest $request)
{
Commit::create(
[
'body' => $request->input('body'),
'to_comment' => $request->input('to_comment'),
'user_name' => \Auth::user()->name,
'from_user_id' => \Auth::id(),
'to_user_com_id' => $request->input('to_user_com_id')
]);
flash()->success('Dodałeś adnotację do komentarza!');
return redirect('/profile');
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\MessageRequest;
use App\Http\Requests\AnswerRequest;
use App\Message;
use App\User;
use App\Answer;
class MessageController extends Controller
{
public function __construct()
{
parent::__construct();
$this->middleware('auth');
}
public function index()
{
$sent = Message::where('from_user', \Auth::id())->count();
$got = Message::where('to_user', \Auth::id())->count();
$read = Message::where('to_user', \Auth::id())->where('read', 1)->count();
$notread = Message::where('to_user', \Auth::id())->where('read', 0)->count();
$sentto = Message::where('from_user', \Auth::id())->latest('created_at')->take(1)->get();
$gotfrom = Message::where('to_user', \Auth::id())->latest('created_at')->take(1)->get();
return view('message.index', compact('sent', 'got', 'sentto', 'gotfrom', 'read', 'notread'));
}
public function store(MessageRequest $request)
{
\Auth::user()->message()->create([
'title' => $request->input('title'),
'message' => $request->input('message'),
'to_user_id' => $request->input('mess_to_user'),
'from_user_name' => \Auth::user()->name,
'to_user_name' => $request->input('from_user_name')
]);
flash()->success('Udało Ci się wysłać prywatną wiadomość!');
return redirect('/profile/'.$request->input('mess_to_user').'');
}
public function show($id)
{
$message = Message::findOrFail($id);
$answers = Answer::paginate(10);
if($message->to_user == \Auth::id() || $message->from_user == \Auth::id())
{
if($message->to_user == \Auth::id())
{
Message::where('id', $id)->update(['read' => 1]);
}
return view('message.show', compact('message', 'answers', 'check'));
}
else
{
return back();
}
}
public function got()
{
$messages = Message::where('to_user', \Auth::id())->latest('created_at')->paginate(10);
return view('message.got', compact('messages'));
}
public function sent()
{
$messages = Message::where('from_user', \Auth::id())->latest('created_at')->paginate(10);
return view('message.sent', compact('messages'));
}
public function storeAnswer(AnswerRequest $request)
{
Answer::create([
'answer' => $request->input('answer'),
'user_id' => \Auth::id(),
'user_name' => \Auth::user()->name,
'to_message' => $request->input('to_message')
]);
flash()->success('Wiadomość prywatna została wysłana!');
return redirect('/private/'.$request->input('to_message').'');
}
}
Route.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/*==========This is main controller=============*/
Route::get('/', 'Controller#index');
Route::get('about', 'Controller#about');
Route::get('contact', 'Controller#contact');
Route::get('teammate', 'Controller#teammate');
/*=========Questions Controll===================*/
Route::get('quest', 'QuestController#index');
Route::get('quest/create', 'QuestController#create');
Route::get('quest/{id}', 'QuestController#show');
Route::post('quest', 'QuestController#store');
/*=============Changelog controller==============*/
Route::get('change/create', 'ChangeController#create');
Route::get('change', 'ChangeController#index');
Route::post('change', 'ChangeController#store');
/*=============Admin Controller==================*/
Route::get('admin', 'AdminController#index');
Route::get('admin/group/create', 'AdminController#createGroup');
Route::post('admin/group', 'AdminController#storeGroup');
Route::get('admin/note/create', 'AdminController#createNote');
Route::post('admin/note', 'AdminController#storeNote');
Route::get('admin/section/create', 'AdminController#createSection');
Route::post('admin/section', 'AdminController#storeSection');
Route::get('admin/article/create', 'AdminController#createArticle');
Route::post('admin/article', 'AdminController#storeArticle');
Route::get('admin/article/{id}', 'AdminController#showArticle');
Route::get('admin/article/{id}/edit', 'AdminController#editArticle');
Route::post('admin/article/{id}', 'AdminController#updateArticle');
Route::get('admin/profile', 'AdminController#profile');
Route::get('admin/profile/{id}/edit', 'AdminController#editProfile');
Route::post('admin/profile/{id}', 'AdminController#updateProfile');
/*=============Profile Controller================*/
Route::get('profile', 'ProfileController#index');
Route::get('profile/{id}', 'ProfileController#show');
Route::get('profile/{id}/edit', 'ProfileController#edit');
Route::post('profile/{id}', 'ProfileController#update');
Route::post('profile/{id}, 'MessageController#store');
Route::post('profile/{id}, 'CommentController#store');
/*============Character Controller===============*/
Route::get('character/create', 'CharacterController#create');
Route::post('character', 'CharacterController#store');
Route::get('character/online', 'CharacterController#online');
/*============Private Message Controller==========*/
Route::get('private', 'MessageController#index');
Route::get('private/got', 'MessageController#got');
Route::get('private/sent', 'MessageController#sent');
Route::get('private/{id}', 'MessageController#show');
Route::post('private/{id}', 'MessageController#storeAnswer');
Route::controllers(
[
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
You are using the same route to access two different functions. That is why when you delete one the code works.
//This is wrong.
Route::post('profile/{id}', CommentController#store');
Route::post('profile/{id}', CommentController#storeCommit');
You can either mention one as "get" and other as "post" and make the required changes within the respective function to fetch and process data.
Route::get('profile/{id}', CommentController#store');
Route::post('profile/{id}', CommentController#storeCommit');
Else, give two different routes for the functions
Route::post('profile/{id}', CommentController#store');
Route::post('profile/storeCommit/{id}', CommentController#storeCommit');
Updated
Try changing the third form like this:
{!! Form::open(array('method'=>'post', 'route' => array('store.commit', $object->id))) !!}
And change your route like this:
Route::post('profile/storeCommit/{id}', ['uses' => 'CommentController#storeCommit', 'as' => 'store.commit']);
Hope this is helpful.
i have a bootstrap modal dialog which use laravel form to register a user.
Here's the code:
<div id="addPenggunaModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="ModalLabel">Tambah Pengguna Baru</h3>
</div>
<div class="modal-body">
{{ Form::open(array('url'=>'users/addpengguna','class'=>'form-horizontal', 'method'=> 'POST')) }}
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="control-group">
<label for="firstname" class="control-label">First Name:</label>
<div class="controls">
{{ Form::text('firstname', null, array('class'=>'span3', 'placeholder'=>'First Name')) }}
</div>
</div> <!-- /field -->
<div class="control-group">
<label for="lastname" class="control-label">Last Name: </label>
<div class="controls">
{{ Form::text('lastname', null, array('class'=>'span3', 'placeholder'=>'Last Name')) }}
</div>
</div> <!-- /field -->
<div class="control-group">
<label for="email" class="control-label">Email Address: </label>
<div class="controls">
{{ Form::text('email', null, array('class'=>'span3', 'placeholder'=>'Email Address')) }}
</div>
</div> <!-- /field -->
<div class="control-group">
<label for="password" class="control-label">Password:</label>
<div class="controls">
{{ Form::password('password', array('class'=>'span3', 'placeholder'=>'Password')) }}
</div>
</div> <!-- /field -->
<div class="control-group">
<label for="confirm_password" class="control-label">Confirm Password:</label>
<div class="controls">
{{ Form::password('password_confirmation', array('class'=>'span3', 'placeholder'=>'Confirm Password')) }}
</div>
</div> <!-- /field -->
<div class="control-group">
<label for="type_user" class="control-label">Tipe Pengguna:</label>
<div class="controls">
{{ Form::radio('level', '1'); }} Supervisor
{{ Form::radio('level', '0'); }} Sales
</div>
</div> <!-- /field -->
</form>
</div>
<div class="modal-footer">
{{ Form::submit('Simpan', array('class'=>'button btn btn-primary','id'=>'mdl_save_change'))}}
<button class="btn" data-dismiss="modal" aria-hidden="true">Batal</button>
</div>
{{ Form::close() }}
</div>
then i use the controller to save the details:
public function postAddpengguna(){
/* function to add user in data pengguna */
$validator = Validator::make(Input::all(), User::$rules);
if($validator -> passes()){
$user = new User;
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->level = Input::get('level');
/* save the following details */
$user->save();
return Redirect::to('pengguna');
} else {
return Redirect::to('index');
}
}
but the form doesn't save any data to database. I have another page called registration and it works.
my questions:
how to trace POST from laravel form submit, is there any browser extension?
how to trace error log in laravel
any ideas what's going on in my problem?
thank you in advance.
UPDATE
Here's the screenshot that describe how this works.
bootstrap modal:
when i press the submit button (blue button in modal) i want it to save the data to db. The function php is shown above.
PS. i don't use any AJAX to call the value from the FORM. But when i use the AJAX, it always error because TOKEN is missing.
First of all check the action and _token field of form . To add token field in your form you should include the following line in your form:
<input type="hidden" name="_token" value="{{csrf_token()}}">
To re-use bootstrap modal in your project you can check this Github link
In the latest versions of laravel 5 you can use a shortcut to get the token field.
<form ... >
{!! csrf_field() !!}
</form>
In this case you'll get something like
<input type="hidden" name="_token" value="hpyL7cUbCMFBGRfCi2dpzE5XHGj8WuyY2jqloKRx">
You can in any case get the token string calling csrf_token(), anyway I honestly prefer the csrf_field() alternative.
You may use this code with your ajax code:
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!}
}
});
});