MethodNotAllowedHttpException in RouteCollection.php - laravel-5.3

I am trying to Pass some values from two text boxes in login.blade.php to the testController and echo the values.Iam getting "Method Not Allowed Exception error" I can't understand why , Please tell me what wrong have i done..
the Flow is Login.blade.php -> testController#getIndex
web.php
Route::get('welcome','testController#getIndex');
Route::get('login','testController#getLogin');
Route::get('/','testController#getData');
testController.php
class testController extends Controller
{
public function getIndex(Request $request)
{
$email = $request->get('email');
$password = $request->get('password');
echo $email;
}
public function getData(){
$datas = Test::all();
return view('welcome',compact('datas'));
}
public function getLogin()
{
return view('login');
}
}
login.blade.php
{!! Form::open(['Url' => 'welcome']) !!}
{!! Form::label('email','Email') !!}
{!! Form::text('email',null,array('class' => 'form-control', 'placeholder' => 'Email' ) ) !!}
{!! Form::label('password','Pasword')!!}
{!! Form::text('password',null, array('class' => 'form-control', 'placeholder' => 'Password')) !!}
{!! Form::submit('Login',array('class' => 'btn btn-success btn-block','style'=>'margin-top: 20px;'))!!}
{!! Form::close() !!}

When using Form::open() - if you don't specify a method (GET or POST), it will default to submitting the form as a POST request. You have your welcome route set up to handle a GET request.
For a login form, I'd recommend you stick with a POST request, which will require you to update your route definition to;
Route::post('welcome','testController#getIndex');
For future reference, you can specify a method when opening your form as follows:
{!! Form::open(['url' => 'welcome', 'method' => 'GET']) !!}

Related

Rendering a template with form inside from a service

my DataTable service code is given below
public function dataTableTest(string $class, Request $request, $FormBuilder): Response
{
$FormFactory = Forms::createFormFactory();
$form = $FormFactory
//->createBuilder()
->create('App\Form\NewsType', null, array(
'method' => 'POST',
))
->add('task', TextType::class, [
'label' => 'Some task',
'required' => true,
])
->add('dueDate', DateType::class)
->add('save', SubmitType::class, [
'label' => 'Create',
])
//->getForm()
;
$response = $this->twig->render('forms/FormFactory.html.twig', [
'controller_name' => 'FormsController',
'form' => $form->createView(),
]);
return new Response($response);
}
FormFactory.html.twig code is
{{ form(form) }}
and i have an error
SyntaxError HTTP 500 Internal Server Error
Unknown "form" function.
1 so how can render a template with twig function 'form' ? or its not possible?
2 When i render some template from service than
a)twig knows entity functions or properties like 'array.id'
b)twig does not know all twig functions like form(), form_start
and so on.
c) I think i need some extra twig dependency injections

Symfony2 - Override Sonata AdminBundle filter

I need to override the filter in Sonata AdminBundle to use a totally different kind of filter using images.
For now it's a html form:
/**
* #param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('orderIdentifier', null, ['label' => 'N°'])
->add('orderDeliveryAddress', null, ['label' => 'Client'])
->add('partner.name', null, ['label' => 'Partenaire'])
->add('postal', null, ['label' => 'Code postal'])
->add('product.code', null, ['label' => 'Produit'])
->add('volume', null, ['label' => 'Volume', 'template'])
->add('deliveryType', null, ['label' => 'Type de livraison'])
->add('createdAt', null, ['label' => 'Date'])
->add('state', null, array('show_filter' => true), 'choice', array(
'choices' => $this->getConfigurationPool()->getContainer()->get('fm.command.order_status_manager')->countAllOrderByStatus(),
))
;
}
How can I totally override this method?
I found a way to override the template:
We override the controller to add my new logic:
namespace Site\AdminBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
class CommandManagementController extends Controller
{
public function listAction()
{
$request = $this->getRequest();
$this->admin->checkAccess('list');
$preResponse = $this->preList($request);
if ($preResponse !== null) {
return $preResponse;
}
if ($listMode = $request->get('_list_mode')) {
$this->admin->setListMode($listMode);
}
$datagrid = $this->admin->getDatagrid();
$formView = $datagrid->getForm()->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
return $this->render('Admin/Command/list.html.twig', array(
'action' => 'list',
'form' => $formView,
'datagrid' => $datagrid,
'csrf_token' => $this->getCsrfToken('sonata.batch'),
), null, $request);
}
}
The twig template:
{% extends 'SonataAdminBundle:CRUD:base_list.html.twig' %}
{% block list_filters %}
{# Your HTML here #}
{% endblock %}

How to get rid of the Invalide CSRF token error

I have a symfony form. Submitting it, I have an error message :
The CSRF token is invalid. Please try to resubmit the form.
I dont know why I have this. I bind request to form after checking the request method is post :
if ($request->getMethod() === 'POST') {
$form->handleRequest($request);
}
Here is the type of the form.
class PasswordActionType extends AbstractType {
protected $forgotten_password;
public function __construct($forgotten_password) {
$this->forgotten_password = $forgotten_password;
}
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options) {
$builder->add('identifiant', 'text', array('attr' => array('style' => 'width:250px')));
if(!$this->forgotten_password) {
$builder->add('ancienMDP', 'password', array(
'label' => 'Ancien MDP',
'attr' => array(
'class' => 'ligne',
'style' => 'width:252px'
)));
$builder->add('nouveauMDP', 'repeated', array(
'type' => 'password',
'invalid_message' => 'Confirmation différente du nouveau mot de passe',
'first_options' => array('label' => 'Nouveau MDP'),
'second_options' => array('label' => 'Confirmer'),
'options' => array(
'attr' => array(
'class' => 'ligne',
'style' => 'width:252px'
))
));
} else {
$builder->add('ancienMDP', 'hidden', array('error_bubbling' => false, 'data' => 'NULL'));
$builder->add('nouveauMDP', 'hidden', array('error_bubbling' => false, 'data' => 'NULL'));
}
}
public function configureOptions(\Symfony\Component\OptionsResolver\OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'My\Bundle\Security\PasswordAction',
'csrf_protection' => true,
'csrf_field_name' => 'token'
));
}
public function getName() {
return 'cramif_password_action';
}
}
So 2 forms use the same builder. The difference is the value of "forgotten_password".
form1 : forgotten_password = true
the 2 fields 'ancienMDP' and 'NouveauMDP' are hidden html fields
form2: forgotten_password = false
the 2 fields are what u can see.
There is not problem with form1, no CSRF error.
The problem occurs with form2.
Note : the 2 forms are displayed with Twig with the same commands.
Note2 : in the twig template I have a form_rest
Just to help people :
If u think u did it right :
bind the request after checking that the form is posted
used form_rest.
Check that you did not invalidate your session. Of course, for the CSRF to work, you need a valid session.

Symfony2 form filter for ManyToMany entity relation

I have 2 entities:
class Exercise
{
//entity
}
and
class Question
{
//entity
}
Their relationship is ManyToMany.
The question is: How I can filter (on the exercise form) the Question entities?
I have this form for Exercise:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('questions', null, array(
'property' => 'name',
'multiple' => true,
'expanded' => false,
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('u')
->where('u.level = :level')
->setParameter('level',$options['level'])
->orderBy('u.dateR', 'ASC');},
))
//other fields
->add('Save','submit')
;
}
I know that I can filter with the query_builder but, how I can pass the var $search?
Should I create another form?
Any help would be appreciated.
Best regards
EDIT: I have found the solution that I want. I put 2 forms on the Controller Action, one form for the entity and one form for filter.
//ExerciseController.php
public function FormAction($level=null)
{
$request = $this->getRequest();
$exercise = new Exercise();
//Exercise form
$form = $this->createForm(new ExerciseType(), $exercise,array('level' => $level));
//create filter form
$filterForm = $this->createFormBuilder(null)
->add('level', 'choice', array('choices' => array('1' => '1','2' => '2','3' => '3')))
->add('filter','submit')
->getForm();
//Manage forms
if($request->getMethod() == 'POST'){
$form->bind($request);
$filterForm->bind($request);
//If exercise form is received, save it.
if ($form->isValid() && $form->get('Save')->isClicked()) {
$em = $this->getDoctrine()->getManager();
$em->persist($exercise);
$em->flush();
return $this->redirect($this->generateUrl('mybundle_exercise_id', array('id' => $exercise->getId())));
}
//If filter form is received, filter and call again the main form.
if ($filterForm->isValid()) {
$filterData = $formFiltro->getData();
$form = $this->createForm(new ExerciseType(), $exercise,array('level' => $filterData['level']));
return $this->render('MyBundle:Exercise:crear.html.twig', array(
'ejercicio' => $ejercicio,
'form' => $form->createView(),
'formFiltro' => $formFiltro->createView(),
));
}
}
return $this->render('juanluisromanCslmBundle:Ejercicio:form.html.twig', array(
'exercise' => $exercise,
'form' => $form->createView(),
'formFiltro' => $filterForm->createView(),
));
}
Templating the forms
On the form.html.twig
{{ form_start(filterForm) }}
{{ form_errors(filterForm) }}
{{ form_end(filterForm) }}
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_end(form) }}
It works for me and it is that i was looking for.
What you probably want to do here, is to make use of the form builder:
$search = [...]
$form = $this->createForm(new AbstractType(), $bindedEntityOrNull, array(
'search' => $search,
));
here you can provide any list of arguments to the builder method of your AbstractType.
public function buildForm(FormBuilderInterface $builder, array $options)
as you may have guessed at this point you may access the options array throu the $option variable.
As a side note remember to provide a fallback inside the default option array. In your AbstractType you can do something like this:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'search' => 'some_valid_default_value_if_search_is_not_provided'
));
}
hope it helps, regards.

stuck on symfony2 for contact form

I have problem with a contact form in symfony2 here is the code what i've done and what error do i get
<?php
// src/Aleksandar/IntelMarketingBundle/Resources/views/ContactType.php
namespace Aleksandar\IntelMarketingBundle\Resources\views;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Collection;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'attr' => array(
'placeholder' => 'What\'s your name?',
'pattern' => '.{2,}' //minlength
)
))
->add('email', 'email', array(
'attr' => array(
'placeholder' => 'So I can get back to you.'
)
))
->add('subject', 'text', array(
'attr' => array(
'placeholder' => 'The subject of your message.',
'pattern' => '.{3,}' //minlength
)
))
->add('message', 'textarea', array(
'attr' => array(
'cols' => 20,
'rows' => 2,
'placeholder' => 'And your message to me...'
)
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$collectionConstraint = new Collection(array(
'name' => array(
new NotBlank(array('message' => 'Name should not be blank.')),
new Length(array('min' => 2))
),
'email' => array(
new NotBlank(array('message' => 'Email should not be blank.')),
new Email(array('message' => 'Invalid email address.'))
),
'subject' => array(
new NotBlank(array('message' => 'Subject should not be blank.')),
new Length(array('min' => 3))
),
'message' => array(
new NotBlank(array('message' => 'Message should not be blank.')),
new Length(array('min' => 5))
)
));
$resolver->setDefaults(array(
'constraints' => $collectionConstraint
));
}
public function getName()
{
return 'contact';
}
}
?>
This is the code for the contact form which will be rendered in the view
no here is the code from my controller
<?php
namespace Aleksandar\IntelMarketingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
/**
* #Route("/contact", _name="contact")
* #Template()
*/
public function contactAction()
{
$form = $this->createForm(new ContactType());
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject($form->get('subject')->getData())
->setFrom($form->get('email')->getData())
->setTo('info#intelmarketing.es')
->setBody(
$this->renderView(
'AleksandarIntelMarketingBundle::contact.html.php',
array(
'ip' => $request->getClientIp(),
'name' => $form->get('name')->getData(),
'message' => $form->get('message')->getData()
)
)
);
$this->get('mailer')->send($message);
$request->getSession()->getFlashBag()->add('success', 'Your email has been sent! Thanks!');
return $this->redirect($this->generateUrl('contact'));
}
}
return array(
'form' => $form->createView()
);
}
}
and here is the rooting
aleksandar_intel_marketing_contactpage:
pattern: /contact
defaults: { _controller: AleksandarIntelMarketingBundle:Default:contact }
now when i try to open the page its says the fallowing:
"[Semantical Error] The annotation "#Route" in method
Aleksandar\IntelMarketingBundle\Controller\DefaultController::contactAction()
was never imported. Did you maybe forget to add a "use" statement for
this annotation? 500 Internal Server Error - AnnotationException "
If any one knows what might be the problem please let me know
As the error message states, you are missing a use statement on top of your controller file.
Simply add:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
on top of your class DefaultController.
You can then replace your routing with:
aleksandar_intel_marketing:
resource: "#AleksandarIntelMarketingBundle/Controller/DefaultController.php"
type: annotation
This way, you are using the #Route annotation instead of the default yml way to declare your routes.
http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html

Resources