Form validation in Symfony2 wont go away - php

I made this Controller to play around with Symfony 2.3
namespace AskThem\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use AskThem\MainBundle\Entity\Task;
class DefaultController extends Controller {
private $context = array();
public function indexAction(Request $request) {
$task = new Task();
$form =
$this->createFormBuilder($task)
->add("task", "text")
->add("dueDate", "date")
->add("save", "submit")
->add("saveAndAdd", "submit")
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'homepage'
: 'task_success';
return $this->redirect($this->generateUrl($nextAction));
}
$this->context["form"] = $form->createView();
return $this->render('AskThemMainBundle:Default:index.html.twig', $this->context);
}
public function successAction(Request $request) {
return new Response("Victory");
}
}
The form was working fine, so then I added a validation-yml file with some NotBlank rules to test if it would work, and indeed it did.
But when I deleted those rules (I even deleted the whole file) the form still kept presenting itself with the required attribute. How do I turn off the validation?

Related

Why are my Symfony Router are not Working?

I am currently creating a Symfony Project for School and i was just trying some things out with this Security Bundle... I was creating the Registration Controller with this php bin/console make:registration-form Command and it worked out fine. The Files got created and i got no Errors but when i am trying to go to /register they just show me my index.php all the time... if i delete index.php its always # Page not Found from my Symfony Local Server... Im just testing out so im just using this localhost Webserver from Symfony. I tested out the Route with php bin/console router:match /register and it showed green, it works and exists. But when i try going to the Site nothing happens.
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Repository\UserRepository;
use App\Security\EmailVerifier;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
class RegistrationController extends AbstractController
{
private EmailVerifier $emailVerifier;
public function __construct(EmailVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address('info#julian-schaefers.dev', 'Julian Schaefers'))
->to($user->getUserIdentifier())
->subject('Please Confirm your Email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
// do anything else you need here, like send an email
return $this->redirectToRoute('_profiler_home');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
#[Route('/verify/email', name: 'app_verify_email')]
public function verifyUserEmail(Request $request, UserRepository $userRepository): Response
{
$id = $request->get('id');
if (null === $id) {
return $this->redirectToRoute('app_register');
}
$user = $userRepository->find($id);
if (null === $user) {
return $this->redirectToRoute('app_register');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register');
}
// #TODO Change the redirect on success and handle or remove the flash message in your templates
$this->addFlash('success', 'Your email address has been verified.');
return $this->redirectToRoute('app_register');
}
}

Controller not found: service "AppBundle/Controller/TestController.php" does not exist

I get the error Controller not found: service "AppBundle / Controller / TestController.php" does not exist
but i don't know how to debug it. Can someone please help me !?
Is it possible that the error comes from the routing or it is something else !?
I just want to clarify that I use Symfony 3.4.
Here is the extract from the TestController.php code
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Task;
use AppBundle\Form\TaskType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("test/form-test")
*/
class TestController extends Controller
{
/**
* #Route("/", name="test")
*/
public function newAction(Request $request)
{
// creates a task and gives it some dummy data for this example
$task = new Task();
$task->setTask('Write a blog post');
$task->setDueDate(new \DateTime('tomorrow'));
$form = $this->get('form.factory')->createNamed('addTask', TaskType::class, $task);
$form->handleRequest($request);
$validator = $this->get('validator');
$errors = $validator->validate($form);
if (count($editErrors) > 0) {
$errorsString = (string)$editErrors;
return new Response($errorsString);
}
echo('------------------------------------------------------------------------' . $form->isSubmitted() . ' && ' . $form->isValid());
if ($form->isSubmitted() && $form->isValid()) {
// $form->getData() holds the submitted values
// but, the original `$task` variable has also been updated
$task = $form->getData();
// ... perform some action, such as saving the task to the database
// for example, if Task is a Doctrine entity, save it!
// $entityManager = $this->getDoctrine()->getManager();
// $entityManager->persist($task);
// $entityManager->flush();
return new Response('<h1>-----------------------------------------------------------------------------------OK</h1>');
}
return $this->render('default/index.html.twig', [
'form' => $form->createView(),
'errors' => $errors,
]);
}
}
thank you in advance

symfony wrong value into db after file upload

I've created a form to upload images and the upload itself is working, but the wrong value gets written into the database.
This is the code in my controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Users;
use AppBundle\Service\FileUploader;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class DefaultController extends Controller
{
/**
* #Route("/bearbeiten/{id}", name="edit")
*/
public function editAction($id, Request $request, FileUploader $fileUploader){
$user = new Users();
//Formular wird erstellt
$form = $this->createFormBuilder($listen)
->add('bild', FileType::class, array('required'=>false, 'label'=>'Bild (JPEG-Datei)', 'data_class'=>null))
->add('save', SubmitType::class, array('label'=>'Speichern', 'attr'=>array('class'=>'btn btn-primary')))
->getForm();
$form->handleRequest($request);
//Falls die Form valid ist....
if($form->isSubmitted() && $form->get('save')->isClicked()){
//Daten aus der Form in Variabeln sichern
$file = $form['bild']->getData();
$filename = $fileUploader->upload($file);
dump($filename);
$user->setBild($filename);
return $this->redirectToRoute('homepage');
}
}
}
The service FileUploader is stored in FileUploader.php and has the following code:
<?php
namespace AppBundle\Service;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileUploader
{
private $targetDir;
public function __construct($targetDir) {
$this->targetDir = $targetDir;
}
public function upload(UploadedFile $file) {
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getTargetDir(), $fileName);
return $fileName;
}
public function getTargetDir() {
return $this->targetDir;
}
}
I've also defined the service in services.yml:
AppBundle\Service\FileUploader:
arguments:
$targetDir: '%file_directory%'
...and declared the variable file_directory in config.yml:
parameters:
locale: en
file_directory: '/tmp'
Now when I dump the variabel $filename, I get the value back I expect, 2d504a8e0a9daba27e7baab69dc08896.jpeg as an example, but even though I use the same variabel to save the string into my database $user->setBild($filename);, another value gets written into my table.
Example of the value in my db: /tmp/phpn7rb2i
I'm really confused and appreciate any help.
Hopefully some of you can help me overcome this.
In your DefaultController you get the $filename via the FileUploader. You set that $filename to the $user via $user->setBild($filename); but you never persist that user to your database. Since you redirect just after that, the value in $filename as well as $user are lost.
You need to persist the data via the Entity Manager like this:
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
Since you seem to have a value inside your database, that value was either there from the beginning and never changes, or you persist at some other point, but whatever it is you persist, it is not the value you had in $filename in your editAction inside your DefaultController.
You need to call persist and flush on the entity manager to save your new User to database, like so (in controller):
$em = $this->getDoctrine()->getManager();
$user = new User();
$user->setBild($filename);
$em->persist($user);
$em->flush();

symfony repository logic functions

Hello i saw a lot of tutorials and still dont know how can i make custom functions in my already done repository.
this is content of my CommentController:
public function newAction(Request $request, $productId)
{
$comment = new Comment();
$form = $this->formFactory->create(CommentForm::class, $comment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->get('doctrine')->getManager();
/** #var Product $product */
$product = $em->getRepository(Product::class)->find($productId);
$comment->setAuthor($this->tokenStorsge->getToken()->getUser());
$comment->setProduct($product);
$comment->setContent($form->get('content')->getData());
$this->em->persist($comment);
$this->em->flush();
}
return $this->render(':form:comment.html.twig', array(
'form' => $form->createView(),
));
}
and i just want to make some function to make controller more beautiful any ideas? if you give me and example how can i insert my data into database via custom repository function. I know how to make custom query thats all. Every help/idea is very helpfull!
From here
Doctrine 2 ORM does not support INSERT via DQL or the DQL query builder. For a complete syntax, check the EBNF of DQL.
You can add more abstractions if you want your controller to look slightly more beautiful, off the top of my head (effective in Symfony 2.8):
BaseController.php:
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
abstract class BaseController extends Controller
{
/**
* #return ProductRepository
*/
protected function getProductRepo()
{
return $this->get('doctrine.orm.entity_manager')->getRepository(Product::class);
}
}
CommentController.php:
Use native controller functions to create a form and get the currently logged in user. And if you are not intend to add more complex logic between $form->isSubmitted() and $form->isValid() use just $form->isValid()
class CommentController extends BaseController
{
public function newAction(Request $request, $productId)
{
$comment = new Comment();
$form = $this->createForm(CommentForm::class, $comment);
$form->handleRequest($request);
if ($form->isValid()) {
/** #var Product $product */
$product = $this->getProductRepo()->find($productId);
$comment->setAuthor($this->getUser());
$comment->setProduct($product);
$comment->setContent($form->get('content')->getData());
$this->em->persist($comment);
$this->em->flush();
}
return $this->render(':form:comment.html.twig', array(
'form' => $form->createView(),
));
}
}

Redirect after validation fails in symfony2

I would separate logic in my controllers.
In newWebsiteAction() I display my form. Next, I send data from form to postWebsiteAction() method.
If validation fails, I would like to redirect to senWebsiteAction() and display errors. What I should add to my code to do it? Because now I dont see errors
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Website;
use AppBundle\Form\Type\WebsiteType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
class WebsitesController extends Controller
{
/**
* #Route("/websites", name="websites")
*/
public function getWebsiteAction()
{
return $this->render('websites/index.html.twig');
}
/**
* #Route("/websites/new", name="websites.new")
*/
public function newWebsiteAction()
{
$website = new Website();
$form = $this->createForm(new WebsiteType(), $website);
return $this->render('websites/create.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/websites/post", name="websites.post", methods={"POST"})
*/
public function postWebsiteAction(Request $request)
{
$form = $this->createFormBuilder()->getForm();
$form->handleRequest($request);
if($form->isValid())
{
$website = $form->getData();
$website->setUser($this->getUser());
$em =$this->getDoctrine()->getManager();
$em->persist($website);
$em->flush();
return $this->redirectToRoute('websites');
}
return $this->redirectToRoute('websites.new');
}
}
Hmm. IMHO you doing it wrong.
First: Why you wan't to do it in single action? If you want some separation better move some logic to services. Because store logic in services is Symfony2 way. E.g. Persist and flush logic to some EntityManager service (abstract example).
Second (hint): How you will get $form errors in newWebsiteAction()?
Edit:
Here is how I usually doing that:
public function createAction(Request $request)
{
$post = new Post();
$form = $this->createForm('post', $post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('show_post', ['slug_title' => $post->getSlugTitle()]));
}
return $this->render('GeekhubMainBundle:Post:create.html.twig', ['form' => $form->createView()]);
}
yes it looks like some logic will duplicated in different methods, but:
1) If method less than 20 lines all fine;
2) In your way you methods for handle form or create entity are not reusable;
Hope that will help :)
public function postWebsiteAction(Request $request)
{
$form = $this->createFormBuilder()->getForm();
$form->handleRequest($request);
if($form->isValid())
{
$website = $form->getData();
$website->setUser($this->getUser());
$em =$this->getDoctrine()->getManager();
$em->persist($website);
$em->flush();
return $this->redirectToRoute('websites');
} else {
$this->generateUrl('\your_defined_route');
return $this->redirect($url);
}
return $this->redirectToRoute('websites.new');
}
check out the else after $form is valid.

Categories