I have a strange problem on symfony 6.1
I searched, but I couldn't find the solution.
The error message: Neither the property "_token" nor one of the methods "_token()", "get_token()"/"is_token()"/"has_token()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
The error occurs when validation fails Error screen
#[Route('/new', name: 'app_commande_new', methods: ['GET', 'POST'])]
public function new(Request $request, ProductRepository $productRepository): Response
{
$commande = new Commande();
$form = $this->createForm(CommandeType::class, $commande);
//dd($request);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dd($form->getData());
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
//dd($form);
return $this->renderForm('commande/new.html.twig', [
'commande' => $commande,
'form' => $form,
]);
}
View
{{ form_start(form) }}
<div class="row">
<div class="col-md-6">
{{ form_row(form._token) }}
{{ form_row(form.client) }}
</div>
<div class="col-md-6">
{{ form_row(form.limitDate) }}
</div>
</div>
<button class="btn btn-primary" id="save" type="submit">{{ button_label|default('Save') }}</button>
{{ form_end(form, {render_rest: false}) }}
My post can't take more code here are the pictures of the forms code.
CommandeType
ProductOutType
Related
I cannot display session value in my view. I only want to display it to see if it's correctly set inside the controller. Is it correctly set in controller? How can I check?
I have this in view:
<div class="panel panel-success">
<form action="{{ route('get_table') }}" method="POST">
{{ csrf_field() }}
#foreach($tables as $data)
<button type="submit" name="tables" class="btn btn-primary" value="{{ $data->id }}">
{{$data->name }}
</button>
#endforeach
</form>
{{ Session::get('table_id') }}
</div>
This in ListController:
public function index() {
$tables = DB::table('tables')->get();
return view('welcome', compact('tables'));
}
public function getTable(Request $request) {
$table_id = $request->get('tables');
$request->session()->put('table_id', $table_id);
}
And this in web.php routes:
Route::get('/', 'ListController#index')->name('get_table');
Route::post('/', 'ListController#getTable');
I even tried
public function getTable(Request $request) {
$request->session()->put('table_id', '1234');
}
Nothing shows up in the view at {{ Session::get('table_id') }}
What am I doing wrong?
You can try this:
public function getTable(Request $request) {
$table_id = $request->get('tables');
return redirect()->back()->with('table_id',$table_id);
}
if you want to redirect to specific route then:
public function getTable(Request $request) {
$table_id = $request->get('tables');
return redirect()->route('RouteName')->with('table_id',$table_id);
}
and then in view:
#if(Session::has('table_id'))
{{ Session::get('table_id') }}
#endif
Hope you got your answer
I know that this question may have been made but I just can't get it to work. if someone could help me I would be very grateful. I have colletive/form installed but the answer can be an html form tag too.
Now listing my form, my route and my exception.
{{ Form::model( array('route' => array('casas.update', 238), 'method' => 'PUT')) }}
<input type="hidden" name="_method" value="PUT">
-
Route::resource('casas', 'CasasController');
exception:
MethodNotAllowedHttpException in RouteCollection.php line 218:
With plain html / blade
<form action="{{ route('casas.update', $casa->id) }}" method="post">
{{ csrf_field() }}
{{ method_field('put') }}
{{-- Your form fields go here --}}
<input type="submit" value="Update">
</form>
Wirth Laravel Collective it may look like
{{ Form::model($casa, ['route' => ['casas.update', $casa->id], 'method' => 'put']) }}
{{-- Your form fields go here --}}
{{ Form::submit('Update') }}
{{ Form::close() }}
In both cases it's assumed that you pass a model instance $casa into your blade template
In your controller
class CasasController extends Controller
{
public function edit(Casa $casa) // type hint your Model
{
return view('casas.edit')
->with('casa', $casa);
}
public function update(Request $request, Casa $casa) // type hint your Model
{
dd($casa, $request->all());
}
}
I've followed the guide and gotten the registration working just fine.
The only issue I have with this is the Form has a title:
User
I do not want this title. I want to customize this. How do I change this title.
As for code everything is as in the guide except my controller which is:
/**
* #Route("/SignUp", name="wx_exchange_signup")
* #Template("WXExchangeBundle:User:signup.html.twig")
* #Method({"GET"})
* User sign up - Open to public
* Creates new users based on information they provide
*/
public function signupAction(Request $request)
{
if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED'))
{
// redirect authenticated users to homepage
return $this->redirect($this->generateUrl('wx_exchange_default_index'));
}
$registration = new Registration();
$form = $this->createForm(new RegistrationType(), $registration, array(
'action' => $this->generateUrl('wx_exchange_signup_create'),
));
return array('form' => $form->createView());
}
The answer I finally found is to only display the form elements that you want:
<form action="/app_dev.php/SignUp/create" method="post" name="registration">
<div id="registration">
<div>
<div id="registration_user">
<div>
{{ form_label(form.user.email) }}
{{ form_widget(form.user.email) }}
</div>
<div>
{{ form_label(form.user.username) }}
{{ form_widget(form.user.username) }}
</div>
<div>
{{ form_label(form.user.password.password) }}
{{ form_widget(form.user.password.password) }}
</div>
</div>
<div>
{{ form_label(form.terms) }}
{{ form_widget(form.terms) }}
</div>
<div>
<button name="registration[Sign Up]" id="registration_Sign Up" type="submit">Sign up</button>
</div>
{{ form_widget(form._token) }}
</div>
</form>
This is documented in the Symfony forms chapter.
Im taking over a project in Symfony 2 (of which I have little knowledge) and am having problems with one of the existing forms. It should be pre-populating the form fields with existing data but is failing to do so. Can anybody give and suggestions as to why it may not be working?
Heres my code:
/**
* #Route("/admin/pressrelease/{id}")
* #Template("ImagineCorporateBundle:Admin:Pressrelease/edit.html.twig")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('ImagineCorporateBundle:PressRelease');
$pr = $repo->find($id);
if(!$pr->getDocument())
{
$doc = new Document();
$doc->setType('child');
$doc->setTemplate('child');
$pr->setDocument($doc);
}
$dateHelper = $this->get('helper.datehelper');
$years = $dateHelper->dateRangeAction();
$form = $this->createForm(new PressreleaseType(), array($pr , $years) );
if($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if($pr->getDocument())
{
$pr->getDocument()->setType('child');
$pr->getDocument()->setTemplate('child');
$pr->getDocument()->setTitle($pr->getTitle());
}
if($form->isValid())
{
$pr->upload('../web/upload/general/');
$em->persist($pr);
$em->persist($pr->getDocument());
$em->flush();
$pr->index(
$this->get('search.lucene'),
$this->generateUrl(
'imagine_corporate_pressrelease_view',
array('id' => $pr->getId(), 'title' => $pr->getTitle())
)
);
return $this->redirect($this->generateUrl('imagine_corporate_pressrelease_admin'));
}
}
return array('pressrelease' => $pr, 'form' => $form->createView());
}
And the view template:
{% extends "ImagineCorporateBundle:Admin:base.html.twig" %}
{% block heading %}Edit Press Release{% endblock %}
{% block content %}
<p>
Upload Attachment |
New Person
</p>
<form action="" method="post" {{ form_enctype(form) }}>
<div>
{{ form_label(form.title) }}
{{ form_errors(form.title) }}
{{ form_widget(form.title) }}
</div>
<div>
{{ form_label(form.author) }}
{{ form_errors(form.author) }}
{{ form_widget(form.author) }}
</div>
<div>
{{ form_label(form.postdate) }}
{{ form_errors(form.postdate) }}
{{ form_widget(form.postdate) }}
</div>
<div>
{{ form_label(form.imageUpload) }}
{{ form_errors(form.imageUpload) }}
{{ form_widget(form.imageUpload) }}
</div>
<div>
{{ form_label(form.thumbnailUpload) }}
{{ form_errors(form.thumbnailUpload) }}
{{ form_widget(form.thumbnailUpload) }}
</div>
<fieldset>
<div><input type="checkbox" class="checkallWebsites"> Check all</div>
{{ form_label(form.websites) }}
{{ form_errors(form.websites) }}
{{ form_widget(form.websites) }}
</fieldset>
<fieldset>
<div><input type="checkbox" class="checkallMagazines"> Check all</div>
{{ form_label(form.magazines) }}
{{ form_errors(form.magazines) }}
{{ form_widget(form.magazines) }}
</fieldset>
<fieldset>
<div><input type="checkbox" class="checkallDept"> Check all</div>
{{ form_label(form.department) }}
{{ form_errors(form.department) }}
{{ form_widget(form.department) }}
</fieldset>
<script>
$(function () {
$('.checkallWebsites').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
$(function () {
$('.checkallMagazines').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
$(function () {
$('.checkallDept').click(function () {
$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
});
});
</script>
{{ form_widget(form) }}
<div id="submit">
<input type="submit" class="addnew-submit" />
</div>
</form>
{% endblock %}
Thanks in advance!
Your issue is this line in your controller:
$form = $this->createForm(new PressreleaseType(), array($pr , $years) );
If your form is based on an entity then you can bind the entity to the form by just passing the object on it's own like so:
$form = $this->createForm(new PressreleaseType(), $pr);
If it's a more complicated form then your array needs to be key value with the form field names as the keys. For example (you may have to substitute the actual field names if they differ as we cannot see your form class):
$form = $this->createForm(
new PressreleaseType(),
array(
'press_release_name' => $pr->getName(),
'years' => $years
)
);
EDIT:
It's possible that both of those values are needed in the constructor of the form class if it has been customised so if the above doesn't help you then please add your form class code.
I'm trying to update an object:
public function editAction(Artist $artist)
{
if (!$artist) {
throw $this->createNotFoundException('Unable to find Artist entity.');
}
// We create the form from the external re-usable form made in TestBundle/Form/artist.php
$form = $this->createForm( new ArtistType, $artist);
// We get the request type
$request = $this->get('request');
// If it is a POST request, the user validated the form
if ($request->isMethod('POST')) {
// We make the link Request <-> Form
// Now, $request = Values entered by the user
$form->bind($request);
// We validate the values
if ($form->isValid()) {
// We save $artist in the DB
$em = $this->getDoctrine()->getManager();
$em->persist($artist);
$em->flush();
$this->get('session')->getFlashBag()->add('info', 'Artist edited successfully');
// Everything is fine, we redirect the user
return $this->redirect($this->generateUrl('ymtest_Artist'));
}
}
// We pass the createView() form method to the viexw so that it can print the form if the user arrived on this page with a GET method (he didnt validate the form yet)
return $this->render('YMTestBundle:Musician:edit.html.twig', array(
'form' => $form->createView(),
'artist' => $artist
));
}
But when I'm validating the form, I get an exception:
Expected argument of type object or array, string given
My form looks like this:
{# src/YM/TestBundle/Resources/views/Musician/add.html.twig #}
{% extends "YMTestBundle::layout.html.twig" %}
{% block bodyAdmin %}
<div class="container">
<form action="{{ path('ymtest_EditArtist', {'id': artist.id}) }}" method="post" {{ form_enctype(form) }}>
<div class="row">
{% if form_errors(form)|length != 0 %}
<div class="span12 alert alert-error" style="margin-left:0px">
{# Les erreurs générales du formulaire. #}
{{ form_errors(form) }}
</div>
{% endif %}
</div>
<div class="row">
<div class="span10 BoxesW">
<div>
{{ form_label(form.name, "Artist Name") }}
{{ form_errors(form.name) }}
{{ form_widget(form.name) }}
</div>
<div>
{{ form_label(form.biography, "Artist Biography") }}
{{ form_errors(form.biography) }}
{{ form_widget(form.biography, {'attr':{'class': 'span10' }, 'id': 'wysiwyg' }) }}
</div>
{{ form_rest(form) }}
</br>
<div>
<input type="submit" class="btn btn-primary" />
</div>
</div>
</div>
</form>
</div>
{% endblock %}
And the route is correct since I get the form before validating it.
Thanks for your help
UPDATE:
Here is My new controller:
<?php
namespace YM\TestBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityRepository;
use YM\TestBundle\Entity\Artist;
use YM\TestBundle\Form\ArtistType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
class MusicianController extends Controller
{
/**
* #Route("/Artist/edit/{id}")
* #ParamConverter("artist", class="YMTestBundle:Artist")
*/
public function editAction(Artist $artist)
{
if (!$artist) {
throw $this->createNotFoundException('Unable to find Artist entity.');
}
// We create the form from the external re-usable form made in TestBundle/Form/artist.php
$form = $this->createForm( new ArtistType, $artist);
// We get the request type
$request = $this->get('request');
// If it is a POST request, the user validated the form
if ($request->isMethod('POST')) {
// We make the link Request <-> Form
// Now, $request = Values entered by the user
$form->bind($request);
// We validate the values
if ($form->isValid()) {
// We save $artist in the DB
$em = $this->getDoctrine()->getManager();
$em->persist($artist);
$em->flush();
$this->get('session')->getFlashBag()->add('info', 'Artist edited successfully');
// Everything is fine, we redirect the user
return $this->redirect($this->generateUrl('ymtest_Artist'));
}
}
// We pass the createView() form method to the viexw so that it can print the form if the user arrived on this page with a GET method (he didnt validate the form yet)
return $this->render('YMTestBundle:Musician:edit.html.twig', array(
'form' => $form->createView(),
'artist' => $artist
));
}
}
EDIT
We found in the chat that the problem was in the entity annotations.
#Assert\Valid() was used on a string variable.
You have this action="{{ path('ymtest_EditArtist', {'id': artist.id}) }}" that I suppose generates an url like editArtist/1234 (so passing a string).
And then you have this public function editAction(Artist $artist) that's requiring an object of type Artist.
You should change it to something like:
public function editAction($artistid)
{
$em = $this->getDoctrine()->getManager();
$artist= $em->getRepository('YourBundle:Artist')->find($artistid);
if (!$artist) {
throw $this->createNotFoundException('No artist found for id '.$artistid);
}
//Do whatever you want
}
Remark: You don't need to call $em->persist($artist); when updating an object (http://symfony.com/doc/current/book/doctrine.html#updating-an-object).