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.
Related
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
working with Laravel 6 project and I have following CommentController,
public function update(Request $request, $id)
{
$comment = Comment::find($id);
$this->validate($request, array('comment' => 'required'));
$comment->comment = $request->comment;
$comment->save();
Session::flash('success','Comment Created');
return redirect()->route('posts.show', $comment->post->id);
}
public function delete($id)
{
$comment = Comment::find($id);
return view('comments.delete')->withComment($comment);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$comment = Comment::find($id);
$post_id = $comment->post->id;
$comment->delete();
Session::flash('success','Deleted Comment');
return redirect()->route('posts.show', $post_id);
}
and My routes are as following
Route::delete('comments/{id}', ['uses' => 'CommentsController#destroy', 'as' => 'comments.destroy']);
Route::get('comments/{id}/delete', ['uses' => 'CommentsController#delete', 'as' => 'comments.delete']);
but when I try to delete comment got following validation error message
The comment field is required.
how could I fix this problem here?
edit.blade.php
#section('content')
<div class="col-sm-6">
<form action="{{ route('comments.destroy', $comment->id) }}" method="post">
#csrf
{{ method_field('PUT') }}
<button type="submit" class="btn btn-danger btn-block">Delete</button>
</form>
</div>
</div>
</div>
#endsection
Because HTML forms can't send PUT, PATCH and DELETE requests, we must "spoof" the request and include an input field that tells Laravel which type it is sending. You can read about that here.
Technically, this means inserting the following for your delete form.
<input type="hidden" name="_method" value="delete">
Laravel comes with different helpers that help you achieve this. In your update form, you have already done this by adding the method_field('PUT');. Here, you are instructing Laravel that this is a PUT request, and we need to do this too in your delete form.
The {{ method_field('PUT') }} simply needs to change to {{ method_field('DELETE') }} or you can use the built-in #method('delete')
Like this
#section('content')
<div class="col-sm-6">
<form action="{{ route('comments.destroy', $comment->id) }}" method="post">
#csrf
#method('delete')
<button type="submit" class="btn btn-danger btn-block">Delete</button>
</form>
</div>
</div>
</div>
#endsection
You can inspect your form HTML in the browser and notice the hidden input field added automatically.
$this->validate($request, array('comment' => 'required'));
In your blade view, if you are not posting a comment in your form, you will be facing this error The comment field is required
Make sure you are posting a comment, or any typo's.
Posting your blade view would help us alot more.
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 am trying to make a search by date form to work on Symfony 2.3. I have an entity with a few fields (5) the name of the entity is Schedule and two of this fields are datetime, for start date time and end Date time. I want to search by dates, but it is giving me headaches.
I have this action:
public function indexAction(Request $request)
{
//time form creation
$aSchedule = new Schedule();
$dateTimeForm = $this->createFormBuilder($aSchedule)
->add('startDateTime', 'datetime')
->add('endDateTime', 'datetime')
->add('search', 'submit')
->getForm();
//getting the formr using post
$dateTimeForm->handleRequest($request);
if ($dateTimeForm->isSubmitted()){
echo 'Submited';
}
if ($dateTimeForm->isValid()){
echo 'Is Valid';
}
}
I have show the form in template like this:
<form action="{{ path('osd_sch_homepage') }}" method="post"
{{ form_enctype(dateTimeForm) }} >
<div id="start-date-time">
{{ form_label(dateTimeForm.startDateTime) }}
{{ form_errors(dateTimeForm.startDateTime) }}
{{ form_widget(dateTimeForm.startDateTime) }}
</div>
<div id="end-date-time">
{{ form_label(dateTimeForm.endDateTime) }}
{{ form_errors(dateTimeForm.endDateTime) }}
{{ form_widget(dateTimeForm.endDateTime) }}
</div>
<div>
{{ form_widget(dateTimeForm.search) }}
</div>
</form>
Now in the action every time in send the form the "$dateTimeForm->isSubmitted()" works fine, but the "$dateTimeForm->isValid()" is not getting true, I mean is never going the "echo 'Is Valid';". what am I doing wrong?
Thank you in advanced.
Abel Guzman
It's probably not putting the auto generated CSRF token. Try putting {{ form_rest }} at the end.
Have you tried to debug your form errors?
foreach($form->getErrors() as $err){
echo $err->getMessage();
}
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.