Symfony 4.2 Form is not submitted or not valid - symfony

I followed the symfony 4.2 documentation, but it seems the form is not submitted...
I spent my whole sunday, but it seems a secret how does it works, in the logs I do not see any errors.
So start it. the config contains these settings:
framework:
validation:
email_validation_mode: 'html5'
enable_annotations: true
Here the entity:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\FeedbackRepository")
*/
class Feedback extends BaseEntity
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\Type("string")
* #Assert\NotBlank
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
* #Assert\Type("string")
* #Assert\Email()
* #Assert\NotBlank
*/
private $email;
AS you can see I use the Assert annotations for the validations.
So here the formtype:
class FeedbackType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('email', EmailType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Feedback::class,
// enable/disable CSRF protection for this form
'csrf_protection' => true,
// the name of the hidden HTML field that stores the token
'csrf_field_name' => '_token',
]);
}
}
Maybe the problem with the token, but I do not know exactly.
Now let see the view:
<form action="{{ path('feedback') }}" type="POST">
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
{{ form_label(feedback.name) }}
{{ form_widget(feedback.name) }}
</div>
<div class="input-field">
<i class="material-icons prefix">email</i>
{{ form_label(feedback.email) }}
{{ form_widget(feedback.email) }}
</div>
{{ form_widget(feedback._token) }}
Next, here the controller which get the request.
/**
* #Route("/feedback", name="feedback", methods="GET|POST")
*/
public function feedbackFormAction(Request $request, EntityManagerInterface $entityManager): JsonResponse
{
$feedbackForm = new Feedback();
$form = $this->createForm(FeedbackType::class, $feedbackForm);
$form->handleRequest($request);
dump($request);
dump($feedbackForm);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($feedbackForm);
$entityManager->flush();
} else {
$errors = $this->getErrorsFromForm($form);
dump($form);die;
return new JsonResponse(['data' => ['result' => 'failed', 'errors' => $errors]]);
}
return new JsonResponse(['data' => ['result' => 'success']]);
}
The errors give me an empty array in Json format.
If I check the dump($feedbackForm) I see that the submitted property is false. and the modeldata, viewdata and normdata values are null... But how is this possible?
Dumping request:
query: ParameterBag {#16 ▼
#parameters: array:1 [▼
"feedback" => array:11 [▼
"name" => "a"
"email" => "a#a.a"
"_token" => "NJHBv7NpwYlugFcU-sE0qoBEQkS38yhxOjbklkHu8j0"
]
]
}
I think, this is correct.

You have not loaded the form data into the entity and trying to persist an empty new Feedback.
if ($form->isSubmitted() && $form->isValid()) {
// add line below
$feedbackForm = $form->getData();
$entityManager->persist($feedbackForm);
$entityManager->flush();
} else { ...
Read carefully https://symfony.com/doc/current/forms.html#handling-form-submissions

Did you create your FeedbackType, Controller action and the form view manually?
Remove all and use
php bin/console make:crud Feedback
This will generate operational files :-)
I think that using form_row is apropriate that using form_widget
Your Controller
/**
* #Route("/feedback", name="feedback", methods="GET|POST")
*/
public function feedbackFormAction(Request $request, EntityManagerInterface $entityManager): JsonResponse
{
$feedback = new Feedback();
$form = $this->createForm(FeedbackType::class, $feedback);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$entityManager->persist($feedbackForm);
$entityManager->flush();
return new JsonResponse(['data' => ['result' => 'success']]);
}
else {
$errors = $this->getErrorsFromForm($form);
return new JsonResponse(['data' => ['result' => 'failed', 'errors' => $errors]]);
}
}
return $this->render('path_to_your_feed_back.html.twig', [
'feedback' => $feedback,
'form' => $form->createView(),
]);
}
Your form.html.twig
{{ form_start(form, {'method': 'POST', 'attr' : {'class' : 'formFeedback'}}) }}
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
{{ form_row(form.name) }}
</div>
<div class="input-field">
<i class="material-icons prefix">email</i>
{{ form_row(form.email) }}
</div>
{{ form_end(form) }}

Related

Symfony form element ID

I've inherited some code which uses Symfony (v3.3) to generate forms. Some elements are being created with no space between the element type and the auto-generated ID. This means the element doesn't display:
<selectid="someID">
...
</selectid="someID">
This is happening on select elements and textarea elements.
I'm not familiar with Symfony so don't know how to troubleshoot this... any help is much appreciated!
Edit: added code as requested. The problem is I don't know where the issue lies and there are a lot of classes.
Twig template
<form action="" method="post" name="callback" id="request-callback" class="contact-form">
<input type="hidden" name="form-type" value="callback">
{#<input type="hidden" name="mc4wp-subscribe" value="1">#}
<div{% if form.name.vars.errors | length > 0 %} class="form-error"{% endif %}>
{{ form_label(form.name) }} {{ form_errors(form.name) }}
{{ form_widget(form.name) }}
</div>
<div{% if form.phone_number.vars.errors | length > 0 %} class="form-error"{% endif %}>
{{ form_label(form.phone_number) }} {{ form_errors(form.phone_number) }}
{{ form_widget(form.phone_number) }}
</div>
<div{% if form.email.vars.errors | length > 0 %} class="form-error"{% endif %}>
{{ form_label(form.email) }} {{ form_errors(form.email) }}
{{ form_widget(form.email) }}
</div>
<div{% if form.treatment.vars.errors | length > 0 %} class="form-error"{% endif %}>
{{ form_label(form.treatment) }} {{ form_errors(form.treatment) }}
{{ form_widget(form.treatment) }}
</div>
<div class="text-center">
<button class="button bg-darkblue" type="submit" id="contact_send" name="contact[send]">Send My Request</button>
</div>
</form>
Form class
<?php
namespace REDACTED;
use DrewM\MailChimp\MailChimp;
use GuzzleHttp\Exception\ConnectException;
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Translator;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Bridge\Twig\Form\TwigRenderer;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Validator\Validation;
use GuzzleHttp\Client;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormFactoryInterface;
abstract class Form
{
/**
* Recaptcha endpoint
*/
const RECAPTCHA_VERIFY = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Default from name
*/
const EMAIL_FROMNAME = '';
/**
* #var \Twig_Environment
*/
protected $twig;
/**
* #var \Symfony\Component\Form\FormInterface
*/
protected $form;
/**
* #var \Symfony\Component\HttpFoundation\Request
*/
private $request;
/**
* Capture failed
*
* #var bool
*/
protected $captchaFailed = false;
/**
* #var string
*/
protected $template;
/**
* #var string
*/
protected $messageTemplate;
/**
* #var string
*/
protected $subject;
/**
* #var string
*/
protected $emailTo;
/**
* #var string
*/
protected $emailFromName;
/**
* #var array
*/
protected $params = [];
protected $mailchimpList;
private $mailchimpApiKey = '6542760048f1c73d69df8f552d4a2b87-us18';
public $mailerError;
public $redirectTo;
/**
* SunstoneForm constructor
*
* #param Request $request
* #param $emailTo
* #param $emailFromName
* #param array $params
*/
private function __construct(
Request $request = null,
$emailTo = null,
$emailFromName = null,
array $params = []
) {
$this->request = $request;
$this->emailTo = $emailTo;
$this->emailFromName = $emailFromName;
$this->params = $params;
}
/**
* Make the contact form
*
* #param Request $request
* #param string $emailTo
* #param string $emailFromName
* #param array $params
* #return static
*/
public static function make(
Request $request = null,
$emailTo = null,
$emailFromName = self::EMAIL_FROMNAME,
array $params = []
) {
return (new static($request, $emailTo, $emailFromName, $params))
->twig()
->form();
}
/**
* Render the form
*
* #return string
*/
public function renderForm()
{
return $this->twig->render($this->template, [
'form' => $this->form->createView(),
'captchaFailed' => $this->captchaFailed,
]);
}
/**
* Handle a form submission and check form is valid
*
* #return bool
*/
public function handleRequest()
{
$this->form->handleRequest($this->request);
if ($this->form->isSubmitted() && $this->form->isValid()) {
// send the message
return $this->process();
}
return false;
}
/**
* Instantiate Twig
*
* #return $this
*/
protected function twig()
{
// instantiate twig
$translator = new Translator('en');
$loader = new \Twig_Loader_Filesystem([
TWIG_TEMPLATE_DIR,
ABSPATH.'vendor/symfony/twig-bridge/Resources/views/Form',
]);
$twig = new \Twig_Environment($loader, [
'debug' => WP_DEBUG,
]);
$twig->addExtension(new FormExtension());
$twig->addExtension(new TranslationExtension($translator));
if (WP_DEBUG) {
$twig->addExtension(new \Twig_Extension_Debug);
}
// get form engine
$formEngine = new TwigRendererEngine(['form_div_layout.html.twig'], $twig);
$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader([
TwigRenderer::class => function() use ($formEngine) {
return new TwigRenderer($formEngine);
},
]));
$this->twig = $twig;
return $this;
}
public function getForm()
{
return $this->form;
}
public function getSubmissionComplete()
{
return sprintf('<div class="form-sent">%s</div>',
get_field('form_submitted_content', 'options')
);
}
/**
* Generate the form
*
* #return $this
*/
protected function form()
{
$this->form = $this->formFields(
Forms::createFormFactoryBuilder()
->addExtension(new HttpFoundationExtension)
->addExtension(new ValidatorExtension(Validation::createValidator()))
->getFormFactory()
)
->getForm();
return $this;
}
/**
* #param array $additionalData
* #return bool
*/
protected function process(array $additionalData = [])
{
$data = $this->form->getData();
$mailer = new \PHPMailer(true);
$mailer->addAddress($this->emailTo);
if (WP_DEBUG && defined('DEBUG_BCC')) {
$mailer->addBCC(DEBUG_BCC);
}
$mailer->From = $this->emailTo;
$mailer->FromName = 'drpuneetgupta.co.uk';
$mailer->Subject = $this->subject;
$mailer->Body = $this->twig->render($this->messageTemplate, [
'data' => $data + $additionalData,
]);
$mailer->isHTML(true);
if ($this->mailchimpList) {
try {
$mailchimp = new MailChimp($this->mailchimpApiKey);
$mailchimp->post("lists/{$this->mailchimpList}/members", [
'email_address' => $data['email'],
'status' => 'subscribed',
]);
} catch (\Exception $e) {}
}
try {
return $mailer->send();
} catch (\phpmailerException $e) {
$this->mailerError = $e->getMessage();
}
return false;
}
/**
* Define form fields
*
* #param FormFactoryInterface $formFactory
* #return mixed
*/
abstract protected function formFields(FormFactoryInterface $formFactory);
}
RequestCallback extends Form class
<?php
namespace REDACTED;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use DrewM\MailChimp\MailChimp;
class RequestCallback extends Form
{
protected $template = 'request-callback.twig';
protected $messageTemplate = 'email-callback.twig';
protected $mailchimpList = 'REDACTED';
protected $subject = 'Callback request';
/**
* #param FormFactoryInterface $formFactory
* #return FormBuilderInterface
*/
protected function formFields(FormFactoryInterface $formFactory)
{
return $formFactory->createNamedBuilder('request_callback', FormType::class, null, [
'allow_extra_fields' => true,
])
->add('mc4wp-subscribe', HiddenType::class, [
'data' => 1,
])
->add('name', TextType::class, [
'required' => true,
'label' => 'Your Name',
'attr' => [
'placeholder' => 'Your Name',
],
'label_attr' => [
'class' => 'sr-only',
],
'constraints' => [
new NotBlank(['message' => 'Please enter your name']),
],
])
->add('phone_number', TextType::class, [
'required' => true,
'label' => 'Phone Number',
'attr' => [
'placeholder' => 'Phone Number',
],
'label_attr' => [
'class' => 'sr-only',
],
'constraints' => [
new NotBlank(['message' => 'Please enter your phone number']),
],
])
->add('email', EmailType::class, [
'required' => true,
'label' => 'Your email address',
'attr' => [
'placeholder' => 'Email address',
],
'label_attr' => [
'class' => 'sr-only',
],
'constraints' => [
new NotBlank(['message' => 'Please enter your email address']),
new Email(['message' => 'Please enter a valid email address']),
],
])
->add('treatment', ChoiceType::class, [
'required' => true,
'label' => 'Which treatment would you like to discuss?',
'label_attr' => [
'class' => 'sr-only',
],
'constraints' => [
new NotBlank(['message' => 'Please select a treatment']),
],
'choices' => [
'Which treatment would you like to discuss?' => '',
'Liposuction' => 'Liposuction',
'Lipoedema' => 'Lipoedema',
'Breast reduction' => 'Breast reduction',
'Male chest reduction' => 'Male chest reduction',
],
]);
}
}
I thought I'll create an answer for this as finding the right answer in a comment is not straightforward.
As #DarkBee mentions in one of the question comments the fix on the question PHP 7.4 trimming whitespace between string variables solves this issue.
There is a fix in Twig that prevents the whitespace from being trimmed so updating to a recent Twig version fixes the issue:
composer require "twig/twig:^2.0"

How to use constraints in controller

I've been trying to add a edit-user page where they can change username, email address and password.
One thing I am trying to implement is they have to type in the old password to be able to change it to a new one.
I've been reading these pages:
https://symfony.com/doc/current/validation.html
https://symfony.com/doc/current/reference/constraints/UserPassword.html
but I'm really struggling on the implementation side.
Here's my Controller for the form:
<?php
namespace App\Controller\User;
use App\Entity\User;
use App\Form\User\EditUserType;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class EditController extends Controller
{
public function edit(Request $request, UserPasswordEncoderInterface $encoder)
{
$userInfo = ['username' => null, 'plainPassword' => null, 'password' => null, 'email' => null];
$form = $this->createForm(EditUserType::class, $userInfo);
$form->handleRequest($request);
$user = new User();
$oldPassword = $user->getPassword();
if ($form->isSubmitted() && $form->isValid()) {
$userInfo = $form->getData();
$username = $userInfo['username'];
$email = $userInfo['email'];
$newPass = $userInfo['plainPassword'];
$oldPass = $userInfo['password'];
$encryptOldPass = $encoder->encodePassword($user, $oldPass);
if ($oldPassword === $encryptOldPass) {
$this->addFlash('danger', $oldPass. ' ' .$encryptOldPass. ' ' .$oldPassword);
return $this->redirectToRoute('user_edit');
} else {
$this->addFlash('success', $oldPassword. '-' .$encryptOldPass);
return $this->redirectToRoute('user_edit');
}
$pass = $encoder->encodePassword($user, $newPass);
$user->setPassword($pass);
$user->setEmail($email);
$user->setUsername($username);
echo 'trey was here';
$this->addFlash('success', 'User Details Edited');
return $this->redirectToRoute('user_edit');
}
return $this->render('user/edit.html.twig', array('form' => $form->createView()));
}
}
my EditUserType file:
<?php
namespace App\Form\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class EditUserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('email', EmailType::class)
->add('username', TextType::class)
->add('password', PasswordType::class, array())
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'New Password'),
'second_options' => array('label' => 'New Repeat Password')
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array());
}
}
my validation (file: config/validator/validation.yaml)
App\Form\User\EditUserType:
properties:
oldPassword:
- Symfony\Component\Security\Core\Validator\Constraints\UserPassword:
message: 'Invalid Password'
my template file:
{% include 'builder/header.html.twig' %}
<div class="user-container" id="user-content">
{% block body %}
{% include 'builder/notices.html.twig' %}
<div class="user-container">
<i class="fas fa-user-edit fa-5x"></i>
</div>
<hr />
{{ form_start(form) }}
{{ form_row(form.username, { 'attr': {'class': 'form-control', 'value': app.user.username} }) }}
{{ form_row(form.email, { 'attr': {'class': 'form-control', 'value': app.user.email} }) }}
{{ form_row(form.password, { 'attr': {'class': 'form-control'} }) }}
{{ form_row(form.plainPassword.first, { 'attr': {'class': 'form-control'} }) }}
{{ form_row(form.plainPassword.second, { 'attr': {'class': 'form-control'} }) }}
<div class="register-btn-container">
<button class="btn btn-danger" id="return-to-dash-btn" type="button">Cancel!</button>
<button class="btn btn-primary" type="submit">Update!</button>
</div>
{{ form_end(form) }}
{% endblock %}
</div>
{% include 'builder/footer.html.twig' %}
Typing in any old password for the old password fields seems to get by and not update the password to the newly typed value.. so how do I validate the old password against the database so the user can update it to a new password?
Thanks
Found the solution, using cerad comment on previous (now removed) answer:
updated controller:
<?php
namespace App\Controller\User;
use App\Form\User\EditUserType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class EditController extends Controller
{
public function edit(Request $request, UserPasswordEncoderInterface $encoder)
{
$userInfo = ['username' => null, 'plainPassword' => null, 'password' => null, 'email' => null];
$form = $this->createForm(EditUserType::class, $userInfo);
$form->handleRequest($request);
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
if ($form->isSubmitted() && $form->isValid()) {
$userInfo = $form->getData();
$username = $userInfo['username'];
$email = $userInfo['email'];
$newPass = $userInfo['plainPassword'];
$oldPass = $userInfo['password'];
if (!$encoder->isPasswordValid($user, $oldPass)) {
$this->addFlash('danger', 'Old password is invalid. Please try again');
return $this->redirectToRoute('user_edit');
}
$pass = $encoder->encodePassword($user, $newPass);
$user->setPassword($pass);
$user->setEmail($email);
$user->setUsername($username);
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', 'User Details Edited - Please Login Again');
return $this->redirectToRoute('login');
}
return $this->render('user/edit.html.twig', array('form' => $form->createView()));
}
}
the issue was, I wasn't checking the logged in user details, and I thought persist meant insert, not insert/update - so lack of knowledge on this one.

Symfony function search wih query builder

I would like to create a function to search for a movie through the query builder
I have a table Movie:
1. Id
2. Titre
3. Content
And i have class MovieRepository :
class MovieRepository extends EntityRepository
{
public function myFindAll()
{
return $this->createQueryBuilder('a')
->getQuery()
->getResult();
}
public function getSearchMovies($movie){
$qb = $this->createQueryBuilder('m')
->where('m.title LIKE :title')
->setParameter('title', '%' . $movie->getTitle() . '%')
->orderBy('m.title', 'DESC')
->getQuery();
}
}
Also i have MovieController :
public function indexAction()
{
$movie = new Movie;
$form = $this->createForm(new SearchMovieType(), $movie);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
$movies = $this->getDoctrine()
->getManager()
->getRepository('AreaDownloadBundle:Movie')
->getSearchUsers($movie);
return $this->render('AreaDownloadBundle:Download:index.html.twig', array('form' => $form->createView(),array('movies' => $movies)));
} else {
$movies = $this->getDoctrine()
->getManager()
->getRepository('AreaDownloadBundle:Movie')
->myFindAll();
return $this->render('AreaDownloadBundle:Download:index.html.twig',array('form' => $form->createView(), 'movies' => $movies));
}
}
SearchMovieType :
class SearchMovieType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title','text', array('required' => false, ))
;
}
And i have index.hml.twig, which can display movies with a search bar :
{% extends "::template.html.twig" %}
{% block body %}
<form action="{{ path('area_download_index') }}" method="post">
<div id="bar">
{{ form_widget(form.title) }}
<input type="submit" value="Chercher">
{{ form_rest(form) }}
</div>
</form>
{% for movie in movies %}
{{ movie.title }}
{{ movie.content }}
{% endfor %}
{% endblock %}
when I seized a title of a movie he sends me this error
Variable "movies" does not exist in AreaDownloadBundle:Download:index.html.twig at line 12
Instead of posting it as a comment, it should have been posted as an answer in the correct formatting; like so:
return $this->render(
'AreaDownloadBundle:Download:index.html.twig',
array(
'form' => $form->createView(),
'movies' => $movies
)
);
This definitely should fix the problem!

Symfony2 create new entity error: NotFoundException

I am getting NotFoundHttpException error when I try to create new entity with form.
This is a code for creating form and entity - CategoryController:
/**
* Displays a form to create a new Category entity.
*
* #Route("/new", name="category_new")
* #Method({"GET"})
*/
public function newAction(Request $request)
{
$entity = new Category();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a new Category entity.
*
* #Route("/", name="category_create")
* #Method("POST")
* #Template("AdminBundle:CategoryPanel:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Category();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('category_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Category entity.
*
* #param Category $entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Category $entity, ServiceCategory $parentCategory = null)
{
$form = $this->createForm(CategoryType::class, $entity, array(
'action' => $this->generateUrl('category_create'),
'method' => 'POST',
'parentCategory' => $parentCategory
));
$form->add('submit', SubmitType::class, array(
'label' => 'Create',
'attr' => array(
'class' => "btn btn-primary"
)
));
return $form;
}
CategoryType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', TextType::class, array('label' => 'Category name'));
$parentCategory = $options["parentCategory"];
if($parentCategory != null){
$builder->add('parent', 'entity', array(
'class' => "CoreBundle:ServiceCategory",
'choices' => array($parentCategory)
));
}else{
$builder->add('parent', 'entity', array(
'class' => "CoreBundle:ServiceCategory",
'query_builder' => function(ServiceCategoryRepository $cp){
$qb = $cp->createQueryBuilder('c');
return $qb;
},
));
}
}
Why this code is looking for entity when I am only attempting to create it?
UPDATE
new.html.twig
{% extends 'AdminBundle:AdminPanel:base.html.twig' %}
{% block body -%}
<h1>Category creation</h1>
{{ form_start(form) }}
{{ form_row(form.name) }}
{{ form_row(form.parent) }}
<ul class="record_actions">
<li style="display: inline-block">
{{ form_widget(form.submit) }}
</li>
<li style="display: inline-block">
<a href="{{ path('category_panel_index') }}">
<button type="button" class="btn btn-primary">
Back to the list
</button>
</a>
</li>
</ul>
{{ form_end(form) }}
{% endblock %}
This might be a conflict between multiple routes as it happened in my case.
You might have some other route may be in some other controller having similar path (with dynamic varaibles) making <>/new pointing somewhere else.
Please do a var_dump in your newAction Controller to check if the execution is coming right there.

Symfony doctrine had an sql injection failure?

I made a little project in symfony 3, and ran the detectify.com over that.
As detectify says, i have "Blind SQL Injection in MySQL" risk
I have Postgres, but nevermind. My keys in the table escalated to 700 after scan. But no data here.
Sooo, i have a security risk.
the controller:
public function bidAction($category = null, Request $request)
{
$bid = new Bids();
$bid->setCategory($category);
$bid->setDate(new \DateTime('now'));
$form = $this->createFormBuilder($bid)
->add('notes', 'textarea', array('label' => 'Message'))
->add('email', 'email')
->add('save', 'submit', array('label' => 'Write your bid'))
->getForm();
$form->handleRequest($request);
if ($form->isValid() && $form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$em->persist($bid);
$em->flush();
return $this->redirectToRoute('mikola_studio_main_bid_category', array('category'=>'success'));
}
return $this->render('MikolaStudioMainBundle:Default:bid.html.twig',
array(
'category' => $category,
'form' => $form->createView(),
'unique'=>false, // for template
'sidebar'=>true // for template
));
}
i was in faith, doctrine persist were protected against sql injection
im now disappointed
the entity:
/**
* #var string
*
* #ORM\Column(name="notes", type="text")
*/
private $notes;
/**
* #var string
*
* #Assert\Email(
* message = "The ({{ value }}) is not valid!",
* checkMX = true
* )
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
Twig:
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.notes) }}
{{ form_row(form.email) }}
<footer>{{ form_row(form.save, {'attr': {'class': 'button icon fa-shopping-cart'}}) }}</footer>
{{ form_end(form) }}
The detectify request body:
form%5Bnotes%5D=&form%5Bemail%5D=If(%40x%2c0%2c(SeleCT(%40x%3a%3dSleeP(0.1)--1))‌​)%2f*%27Or(If(%40x%2c0%2c(SeleCT(%40x%3a%3dSleeP(0.1)--1))))Or%27%22or(If(%40x%2c‌​0%2c(SeleCT(%40x%3a%3dSleeP(0.1)--1))))Or%22*%2f&form%5Bsave%5D=
readable:
form[notes]=&form[email]=If(#x,0,(SeleCT(#x:=SleeP(0.1)--1))‌​)/*'Or(If(#x,0,(SeleCT(#x:=SleeP(0.1)--1))))Or'"or(If(#x,‌​0,(SeleCT(#x:=SleeP(0.1)--1))))Or"*/&form[save]=

Resources