I'm trying to return a form to update some attributes in my user entity
I'm tying to have a single page app, so I'm creating forms, trying to setup their Update functions in a single controller, and to load the forms in separate twig templates that are all loaded in the main "profile" page.
My entire user controller:
<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ModifyUserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\UserRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserController extends AbstractController
{
/**
* #Route("/profile", name="profile", methods={"GET"})
*/
public function index(): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
return $this->render('profile.html.twig', [
'controller_name' => 'UserController',
]);
}
/**
* #Route("/profile", name="update", methods={"PUT"})
* #param UserInterface $user
* #param Request $request
* #param EntityManagerInterface $em
* #return Response
*/
public function updateUser(UserInterface $user, Request $request, EntityManagerInterface $em) : Response
{
$userId = $this->getUser()->getId();
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->find($userId);
$form = $this->createForm(ModifyUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$em->persist($user);
$em->flush();
$this->addFlash('success', 'Saved');
return $this->redirectToRoute('profile');
}
return $this->render('modifyUser.html.twig', [
'updateUser' => $form->createView()
]);
}
}
My form type:
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\LanguageType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ModifyUserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', TextareaType::class)
->add('MotherLanguage', LanguageType::class)
->add('addLanguage', LanguageType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// Configure your form options here
]);
}
}
The modal where I'm trying to call the form:
<!-- Modify User Modal -->
<div class="modal fade" role="dialog" id="editUserModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Modify profile</h3>
<button class="close" type="button" data-dismiss="modal">×</button>
</div>
{{ form_start(updateUser) }}
<input type="hidden" name="_method" value="PUT">
<div class="modal-body">
<div class="form-group">
<label for="description">Description</label>
{{ form_row(updateUser.description, { 'id': 'description','attr': { 'class' : 'form-control'}}) }}
<label for="addNativeLanguage">Add your native language</label>
{{ form_row(updateUser.MotherLanguage, { 'id': 'addNativeLanguage','attr': { 'class' : 'form-control'}}) }}
</select>
<label for="addLanguage">Add other languages you speak</label>
{{ form_row(updateUser.addLanguage, { 'id': 'addLanguage','attr': { 'class' : 'form-control'}}) }}
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-light">Update</button>
</div>
{{ form_end(updateUser) }}
</div>
</div>
</div>
<!-- /Modify User Modal -->
Update:
After Modifying the Controller to the following:
<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ModifyUserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\UserRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserController extends AbstractController
{
/**
* #Route("/profile", name="profile", methods={"GET","PUT"})
*/
public function index(UserInterface $user, Request $request, EntityManagerInterface $em) : Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
/*return $this->render('profile.html.twig', [
'controller_name' => 'UserController',
]);*/
$userId = $this->getUser()->getId();
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->find($userId);
$form = $this->createForm(ModifyUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$em->persist($user);
$em->flush();
$this->addFlash('success', 'Article Created! Knowledge is power!');
return $this->redirectToRoute('profile');
}
return $this->render('profile.html.twig', [
'user' => $user,
'updateUser' => $form->createView()
]);
}
}
I'm getting a new error :
Too few arguments to function App\Entity\User::addLanguage(), 0 passed in /home/majd/Projects/Symfony/Back/vendor/symfony/property-access/PropertyAccessor.php on line 422 and exactly 1 expected.
As per #dutycorpse 's comment instead of going for the property, I was going directly for the function responsible for adding languages.
Related
I am trying to build a list filter in Symfony. I'm still new to PHP, MySQL, and twig. The official documentation doesn't help a lot. It is required that I have a page with a list of all classes and next to that a search bar where the user inputs the class they want and it will show on the page without the others. I'll post my code but I think it is missing a lot of code. I only need little help and maybe sources for documentation on how to do it the official documents aren't very clear for someone with zero experience.
My ClassesRepository.php
<?php
namespace App\Repository;
use App\Entity\Classes;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #method Classes|null find($id, $lockMode = null, $lockVersion = null)
* #method Classes|null findOneBy(array $criteria, array $orderBy = null)
* #method Classes[] findAll()
* #method Classes[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ClassesRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Classes::class);
}
public function findbyName()
{
return $this->createQueryBuilder('c')
->getQuery()->getResult();
}
public function getSearchClasses($class){
$qb = $this->createQueryBuilder('c')
->where('c.Title LIKE :Title')
->setParameter('Title', '%' . $class->getTitle() . '%')
->orderBy('c.Title', 'DESC')
->getQuery();
}
}
classesController:
<?php
namespace App\Controller;
use App\Entity\Classes;
use App\Entity\Students;
use App\Entity\Courses;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class ClassesController extends AbstractController
{
/**
* #Route("custom/classes", name="classes_list")
*/
public function index()
{
$classes = $this->getDoctrine()->getRepository(classes::class)->findAll();
return $this->render('classes/index.html.twig', [
'classes' => $classes
]);
}
/**
* #Route("/classes/new", name="new_class")
* #Method({"GET","POST"})
*/
public function new(Request $request)
{
$class = new Classes();
$form = $this->createFormBuilder($class)
->add('Title', TextType::class, array('attr' =>
array('class' => 'form-control')))
->add('save', SubmitType::class,array('label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$class = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($class);
$entityManager->flush();
return $this->redirectToRoute('classes_list');
}
return $this->render('classes/new.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/classes/edit/{id}", name="edit_class")
* #Method({"GET","POST"})
*/
public function edit(Request $request, $id)
{
$class = new Classes();
$class = $this->getDoctrine()->getRepository(classes::class)->find($id);
$form = $this->createFormBuilder($class)
->add('Title', TextType::class, array('attr' =>
array('class' => 'form-control')))
->add('save', SubmitType::class,array('label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
return $this->redirectToRoute('classes_list');
}
return $this->render('classes/edit.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/classes/delete/{id}")
* #Method({"DELETE"})
*/
public function delete(Request $request, $id){
$class = $this->getDoctrine()->getRepository(Classes::class)->find($id);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($class);
$entityManager->flush();
$response = new Response();
$response->send();
}
/**
* #Route("/classes/{id}", name="classes_show")
* #Method({"GET"})
*/
public function show($id){
$_class = $this->getDoctrine()->getRepository(Classes::class)->find($id);
return $this->render('classes/show.html.twig', array('classes' => $_class));
}
// /**
// * #Route("custom/classes/save")
// */
// public function save() {
// $entityManager = $this->getDoctrine()->getManager();
// $classes = new Classes();
// $classes->setTitle('Grade 2');
// $entityManager->persist($classes);
// $entityManager->flush();
// return new Response('Saved an classes with the id of '.$classes->getId());
// }
}
Index.html.twig is Location where I will need to locate the list filter
{% extends 'base.html.twig' %}
{% block title %}Classes{% endblock %}
{% block body %}
<br>
<h1>Classes:</h1>
Create
<br>
{% if classes %}
<div class="alignleft">
<table id="classes" class="table table-striped" style="width:70%">
<thead>
<tr>
<th>Class</th>
<th>Details </th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for classes in classes %}
<tr>
<td> {{ classes.title }}</td>
<td>
Show Class Details
</td>
<td>
Edit
</td>
<td>
X
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div>
<form method="GET" action="search" style = "position:absolute; left:1100px; top:150px; height:100px; width:100px">
<input type="text" name="q" placeholder="Search Query...">
<select name="column" style = "position:absolute; left:40px; top:30px; width:100px ">
<option value="classes.Title" >Class</option>
</select>
<input type="submit" class="btn btn-warning" value="Find" style = "position:absolute; left:40px; top:56px; width:100px ">
</form>
</div>
{% else %}
<p>No Classes Available</p>
{% endif %}
{% endblock %}
{% block javascripts %}
<script src="/js/classmain.js"></script>
{% endblock %}
I don't understand the behavior you expect from the filter but I hope it will help you..
In your ClassesRepository.php
// if has not $classTitle and $query it will find all
public function getSearchClasses($classTitle = null , $query=null){
$qb = $this->createQueryBuilder('c')
->orderBy('c.Title', 'DESC');
if($classTitle && $classTitle !== '') {
$qb->andWhere('c.Title LIKE :classTitle')
->setParameter('classTitle', '%' . classTitle . '%');
}
if($query && $query !== '') {
// doSomethings with query input
}
return $qb->getQuery()->getResult();
}
In your classesController:
/**
* #Route("custom/classes", name="classes_list")
*/
public function index(Request $request)
{
$classTitle = $request->query->get('classTitle',null);
$query = $request->query->get('query',null);
// if has not $classTitle and $query it will find all
$classes = $this->getDoctrine()->getRepository(classes::class)->getSearchClasses($classTitle,$query);
return $this->render('classes/index.html.twig', [
'classes' => $classes
]);
}
In your index.html.twig
// redirect to the same route that render this template ..
<form method="GET" action="{{ path('classes_list') }}">
<input type="text" name="query" placeholder="Search Query...">
<select name="classTitle">
{% for class in classes%}
<option value="{{class.title}" >{{class.title}}</option>
{% endfor %}
</select>
<input type="submit" class="btn btn-warning" value="Find">
</form>
I'm learning how yo use symfony, and my problem is, when I want to use the handleRequest function, it did not validate my email en message field, but it's good for name field.
Look the code:
Contact.php entity
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Contact
{
/**
* #Assert\NotBlank
*/
private $name;
/**
* #Assert\NotBlank
*/
private $email;
/**
* #Assert\NotBlank
*/
private $message;
public function getName()
{
return $this->name;
}
public function getEmail()
{
return $this->email;
}
public function getMessage()
{
return $this->message;
}
public function setName($name)
{
$this->name = $name;
}
public function setEmail($email)
{
$this->name = $email;
}
public function setMessage($message)
{
$this->name = $message;
}
}
?>
BlogController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Article;
use App\Entity\Contact;
use App\Repository\ArticleRepository;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\HttpFoundation\Request;
class BlogController extends Controller
{
/**
* #Route("/blog", name="blog")
*/
public function blog(ArticleRepository $repo)
{
$articles = $repo->findAll();
return $this->render('blog/index.html.twig', [
'controller_name' => 'BlogController',
'articles' => $articles
]);
}
/**
* #Route("/", name="blog_home")
*/
public function home()
{
return $this->render('blog/home.html.twig');
}
/**
* #Route("/blog/articles/{id}", name="blog_show")
*/
public function show(Article $article)
{
return $this->render('blog/show.html.twig',[
'article' => $article
]);
}
/**
* #Route("/contact", name="blog_contact")
*/
public function contact(Request $request)
{
$contact = new Contact; /* Create the new contact object */
$form = $this->createFormBuilder($contact) /* Creating the form */
->add('name', TextType::class)
->add('email', TextType::class)
->add('message', TextareaType::class)
->getForm();
dump($contact);
$form->handleRequest($request);
dump($contact);
if($form->isSubmitted() && $form->isValid())
{
return $this->redirectToRoute('blog_home');
}
dump($request);
return $this->render('blog/contact.html.twig',[
'form' => $form->createView()
]);
}
}
contact.html.twig
{% extends 'base.html.twig' %}
{% block title %}BLOG - Contact{% endblock %}
{% block body %}
<h2>Me contacter !</h1>
<div class="row">
<div class="col-md-5">
{{ form_start(form) }}
<label>Nom:</label>
{{ form_widget(form.name) }}
<label>Email:</label>
{{ form_widget(form.email) }}
<label>Message:</label>
{{ form_widget(form.message) }}
<br>
<button type="submit" class="btn btn-info">Envoie</button>
{{ form_end(form) }}
</div>
<div class="col-md-1">
</div>
<div class="col-md-6">
<div class="card border-info mb-1" style="max-width: 20rem;">
<div class="card-header">Twitter: #Fergvae</div>
</div>
<div class="card border-dark mb-1" style="max-width: 20rem;">
<div class="card-header">Discord: Fergvae#0730</div>
</div>
<div class="card border-danger mb-1" style="max-width: 20rem;">
<div class="card-header">Youtube: Fergvae</div>
</div>
</div>
</div>
{% endblock %}
The only things that didn't work is the handleRequest it's why I made multiple dump.
you also can look the dumped content, the first is before handle and second after.
Dumped symfony content
Thanks to all people who answer this question !
Ok my bad, I just forget when I copy past to change the ^this->name in de setters ! Excuse me for the disturb
It's great that you have found your solution, but just in case:
If usage for classes, a better practice is to use a FormType, in there you can declare your class on which fields the form should be automatically created. Which Symfony will automatically catch all of the needed fields and will create the form for you, less code written and etc. Or you can create a custom form, and define all of your needed fields, including restrictions as not empty and etc..
To sum it up, if possible keep as less logic in the controllers as possible and move them deeper.
I was trying to create a custom form type with it's own template view via Symfony 4 Documentation but I got a lot of errors by searching and trying to create one.
Here is my custom form type file ImageChoiceType.php:
<?php
namespace App\Form\Type;
use App\Entity\Media;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ImageChoiceType extends AbstractType
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
// 'data_class' => Media::class,
'class' => Media::class,
'choices' => $this->entityManager->getRepository(Media::class)
->findAll(),
));
}
public function getParent()
{
return EntityType::class;
}
/**
* {#inheritdoc}
*/
public function getName()
{
return 'image_choice';
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'image_choice';
}
}
Here is my field template:
{% block image_choice_widget %}
<div class="image_widget">
<div class="radio">
<label for="post_image_placeholder" class="">
<input type="radio" id="post_image_placeholder" name="post[image]" value=""
{{ form.vars.value == "" ? "checked='checked'" : ""}}> None
</label>
</div>
<div class="image-container">
{% for key,choice in form.vars.choices %}
<div class="radio col-xs-2">
<label for="post_image_{{ key }}" class="">
<input class="image-radio-buttons" type="radio" id="post_image_{{ key }}" name="post[image]"
value="{{ key }}" {{ form.vars.value == key ? "checked='checked'" : ""}}>
<img src="{{ asset(constant('App\\Constants::UPLOAD_MEDIA')~choice.label) }}" class="image-thumbs img-responsive"/>
</label>
</div>
{% endfor %}
<div class="clearfix"></div>
</div>
</div>
{% endblock %}
The interesting part is if I override one of the built-in types of Symfony via this template by changing the first line to {% block entity_widget %} and use EntityType in my form builder, it works well. But as I started to populate this with my own custom type, It got angry and showed a lot of unrelated errors!
Any help or instruction?
OK, I found out how to create it!
That was so easy. The documentation showed that it's so complex, but actually it's not.
This is the custom form type file ImageChoiceType.php:
<?php
namespace App\Form\Type;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ImageChoiceType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
}
public function getParent()
{
return EntityType::class;
}
/**
* {#inheritdoc}
*/
public function getName()
{
return 'image_choice';
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'image_choice';
}
}
This is how I use this field in my form builder:
...
->add('image',ImageChoiceType::class , [
'label' => 'Choose an Image',
'class' => Media::class
])
...
and the template that I've provided in the question is exactly what generates the pictures!
I'm setting up a blog and want the homepage to show the latest blog entries including links to the single entries.
I got a link to all entries showing in a list but I can't exactly figure out how to show a single entry. Plus now I always get an "object not found" exception as soon as I try to click on the link.
Here's the controller which contents the Function to show a single entry:
<?php
// src/BlogBundle/Controller/BlogController.php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use BlogBundle\Entity\Blog;
use BlogBundle\Entity\User;
use BlogBundle\Form\BlogType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class BlogController extends Controller
{
/**
* #Route("/blog", name="bloglist", requirements={"page": "\d+"})
*/
public function listAction()
{
$entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'));
dump($entry);
return $this->render('BlogBundle:blog:blog.html.twig', [
'bloglist' => $entry
]);
}
/**
* #Route("/blog/new", name="create")
*/
public function createAction(Request $request) {
$entry = new Blog();
$entry->setDate(new \DateTime('now'));
$entry->setAuthor($this->getUser());
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entry = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:blog:createsubmit.html.twig', array(
'entry' => $entry,
'form' => $form->createView(),
'success' => true
));
}
return $this->render('BlogBundle:blog:new.html.twig', array(
'quote' => 'New blog entry created!',
'form' => $form->createView(),
));
}
/**
* #Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
*/
public function listSingleEntryAction(Request $request, Blog $blog)
{
$em = $this->getDoctrine()->getRepository('BlogBundle:Blog')->find($blog);
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:singleentry:edit.html.twig', array(
'entry' =>$entry,
'form' => $form->createView()
));
}
/**
* #Route("/blog/edit/{id}", name="entryedit", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function editAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:blog:editsubmit.html.twig', array(
'entry' => $entry,
'form' => $form->createView(),
'success' => true
));
}
return $this->render('BlogBundle:blog:edit.html.twig', array(
'form' => $form->createView(),
));
}
else {
echo '<div class="alert alert-danger alert-dismissable">
<span aria-hidden="true" data-dismiss="alert" class="close">×</span>
<h4>
<i class="fa fa-exclamation-circle "></i>
Only the author of an entry is allowed to edit it!</h4></div>';
return $this->listAction();
}
}
/**
* #Route("/blog/delete/{id}", name="entrydelete", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function deleteAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
$em->remove($entry);
$em->flush();
return $this->render('BlogBundle:blog:deletesubmit.html.twig');
}
else {
return $this->render('BlogBundle:blog:error.html.twig');
}
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => 'BlogBundle\Entity\Blog'
]);
}
}
?>
for my homepage:
<?php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DefaultController extends Controller {
/**
* #Route("/", name="welcome")
*/
public function indexAction() {
$entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'),5);
dump($entry);
return $this->render('BlogBundle:Default:index.html.twig', [
'Welcome' => 'Welcome!',
'avatar_url' => 'http://www.lufthansa.com/mediapool/jpg/45/media_789050645.jpg',
'blog' => $this->redirectToRoute('singleentry'),
'bloglist' => $entry
]);
}
}
?>
And those are the twig templates I try to render
singleentry.html.twig:
{% extends '::base.html.twig' %}
{% block body %}
<div class="container">
<div class="col-md-11">
<h1 class="page-header">{{ blog. title }}</h1>
<div class="table">
<p><span class="fa fa-clock-o"></span> Posted on {{ blog.date|date('d.M Y H:i A') }} </p>
<p><span class="fa fa-user-circle"></span> Posted by {{ blog.author }} </p>
<p>{{ blog.text }}</p>
<!-- <a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> -->
<button type="button" class="btn btn btn-info">
Edit entry
</button>
<button type="button" class="btn btn btn-warning">
Delete entry
</button>
<hr>
</div>
</div>
</div>
{% endblock %}
for the list of blog entries on my homepage:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title text-center">My latest blog entries</h3>
</div>
<table class="table">
{% for blog in bloglist %}
<tr>
<td>{{ blog.title }}</td>
<td width="85%" style="max-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;">
{{ blog.text }}
</td>
</tr>
{% endfor %}
</table>
</div>
edited version of listSingleEntryAction --> object shown as NULL
public function listSingleEntryAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($id);
if($entry == null)
{
$message='Entry does not exist';
return $this->render('BlogBundle:blog:error.html.twig');
}
return $this->render('BlogBundle:blog:singleentry.html.twig', Array(
'entry' => $entry,
'success' => true,
));
}
The problem is your arguments.
public function listSingleEntryAction(Request $request, Blog $blog)
{
First of all, it shouldn't be with a Blog type. It's int.
Second, rename it to $id.
And I think you have the same problem with edit and delete actions.
check out your action. First 2 lines are the reason of your problem.
/**
* #Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
*/
public function listSingleEntryAction(Request $request, Blog $blog)
{
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
I would like to provide the functionality to change his/her password on his/her own on my web application but I found the error addressed on the title so can anyone help me to solve this?
url:
http://nuatthai.loc/auth/password
routing:
Route::post('auth/password', ['as' => 'auth.postPassword', 'uses' => 'PasswordController#postPassword']);
Route::get('auth/password', ['as' => 'auth.prePassword', 'uses' => 'PasswordController#prePassword']);
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use App\Role;
use App\User;
use App\Http\Controllers\Controller;
class PasswordController extends Controller
{
use ResourceController;
public function __construct()
{
$this->middleware('role:' . Role::ADMIN + Role::OWNER + Role::MANAGER + Role::ACCOUNTANT);
}
protected function validator(array $data)
{
return Validator::make($data, [
'password' => 'required|confirmed|min:8',
]);
}
private function updateData(Request $request)
{
$user = User::find($this::getMyId());
$user->password = $request->input('password');
$user->remember_token = str_random(60);
$user->save();
return $user;
}
public function prePassword()
{
return view('auth.change');
}
public function postPassword($request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
\Session::flash('flash_error', $validator->messages());
$this->throwValidationException(
$request, $validator
);
}
$this::updateData($request);
}
}
view:
{{-- resources/views/auth/change.blade.php --}}
#extends('common.layout')
#section('header') #parent #endsection
#section('navbar') #include('common.navbar') #endsection
#section('sidebar') #include('common.sidebar') #endsection
#section('content')
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('action' => ['PasswordController#postPassword'], 'class' => 'form-horizontal')) !!}
<div class="form-group">
<label class="col-md-4 control-label input-lg">Password</label>
<div class="col-md-6">
<input type="password" class="form-control input-lg" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label input-lg">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control input-lg" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary btn-lg" style="margin-right: 15px;">
Reset Password
</button>
</div>
</div>
</form>
</div><!-- .panel-body -->
</div><!-- .panel --> #endsection
{{-- resources/views/auth/change.blade.php --}}
middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Role;
use App\UserRole;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $mode)
{
if(!\Auth::check()) {
// session expired.
return redirect()->guest('auth/login');
}
else {
$admin = $mode & Role::ADMIN;
$owner = $mode & Role::OWNER;
$manager = $mode & Role::MANAGER;
$accountant = $mode & Role::ACCOUNTANT;
$type = \Auth::user()->role->type;
if(($admin) && ($type == Role::ADMIN)) {
return $next($request);
}
if(($owner) && ($type == Role::OWNER)) {
return $next($request);
}
if(($manager) && ($type == Role::MANAGER)) {
return $next($request);
}
if(($accountant) && ($type == Role::ACCOUNTANT)) {
return $next($request);
}
return response('Access Denied.', 403);
}
}
}
Role:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\ResourceController;
class Role extends Model
{
use ResourceController;
const TABLE = 'common_roles';
const ROLE_ID = 'role_id';
const ROLE_TYPE = 'type';
const TABLE_ROLE_ID = self::TABLE . '.' . self::ROLE_ID;
const TABLE_ROLE_TYPE = self::TABLE . '.' . self::ROLE_TYPE;
protected $table = self::TABLE;
protected $primaryKey = self::ROLE_ID;
const ADMIN = 0b1000; // 8
const OWNER = 0b100; // 4
const MANAGER = 0b10; // 2
const ACCOUNTANT = 0b1; // 1
public function users()
{
return $this->hasMany('App\User');
}
}
I really appreciate of any suggestions and advices in advance.