Symfony2 I cannot submit a valid form from the Twig template - php

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();
}

Related

Symfony : form with GET method, messy URL

I use a search form in Symfony 4.2.5, with GET method.
But the URL is not very... sexy.
I want to get a clean URL.
I have already disabled CSRF protection, and removed the submit from the FormBuilder ( otherwise, the submit button was ALSO on the URL).
The form :
public function searchForm()
{
//Form search creation
$form = $this->createFormBuilder(null, array('csrf_protection' => false))
->setAction($this->generateUrl('page'))
->setMethod('GET')
->add('object', TextType::class)
->getForm();
return $this->render('page.html.twig', ['searchForm' => $searchForm->createView()]);
}
The view :
<form class="search">
{{ form_start(searchForm) }}
{{ form_row(searchForm.object, {'attr' : {'placeholder': "Search..."}}) }}
<button id="searchSubmit" class="btn btn-success">Search </button>
{{ form_end(searchForm) }}
</form>
With this code, I get localhost/page?form[object]=SearchTerm
I know, it is a detail, but I want to get an URL like localhost/page?object=SearchTerm.

How to submit a form using PUT http verb in Laravel

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());
}
}

delete function Laravel 5.2

I've been learning laravel 5.2 recently, and i've made a delete function which should delete records from my database but instead of deleteing the records it's adding a blank row into my database
This is the Route im using:
Route::resource('producten', 'ProductenController', ['only' => ['index', 'store', 'destroy', 'edit', 'update', 'create']]);
This is the controller function i use for it
public function destroy(request $request , product $product)
{
$product->delete();
return redirect(Route('producten.index'));
}
This is the form i've made for it.
{{ Form::Open(['Route' => 'producten.destroy', $product], ['method' => 'delete']) }}
{{ Form::Submit('delete')}}
{{ Form::close() }}
when i viewed the source-code it said it was using a POST method instead of a delete method, and also when i add($product) i got a blank page, also i found out that when i hit the submit button it goes to the store method i've made and i dont know why,
if u need more information just let me know and i'll add it in the question
route and method should be in the same array, not in two differents arrays.
{{ Form::Open(['method' => 'DELETE', 'route' => ['producten.destroy', $product]]) }}
{{ method_field('DELETE') }}
{{ Form::Submit('delete')}}
{{ Form::close() }}
I think you have something wrong with form. Can you try with this:
<form action="{{ route('producten.destroy', ['product' => $product->id]) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Remove</button>
</form>

Symfony2 Customize the Form from the Simple Registration Tutorial

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.

Method validateConfirm does not exist (Laravel)

I am following Dayle Rees' Laravel tutorial, trying to build a simple registration page.
If I submit the registration form with validation errors, the page reloads and shows me the validation errors. However, when I key in correct values and submit, I get the following error -
BadMethodCallException
Method [validateConfirm] does not exist.
This is my register.blade.php -
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<h1>Registration form</h1>
{{ Form::open(array('url' => '/registration')) }}
{{-- Username field. ------------------------}}
{{ Form::label('username', 'Username') }}
{{ Form::text('username') }}
{{ $errors->first('username', '<span class="error">:message</span>') }}
<br/>
{{-- Email address field. -------------------}}
{{ Form::label('email', 'Email address') }}
{{ Form::email('email') }}
{{ $errors->first('email', '<span class="error">:message</span>') }}
<br/>
{{-- Password field. ------------------------}}
{{ Form::label('password', 'Password') }}
{{ Form::password('password') }}
{{ $errors->first('password', '<span class="error">:message</span>') }}
<br/>
{{-- Password confirmation field. -----------}}
{{ Form::label('password_confirmation', 'Password confirmation') }}
{{ Form::password('password_confirmation') }}
<br/>
{{-- Form submit button. --------------------}}
{{ Form::submit('Register') }}
{{ Form::close() }}
</body>
</html>
And this is my routes.php [NOTE : The issue goes away if I remove the rule for password]
Route::get('/', function()
{
return View::make('register');
});
Route::post('/registration', function()
{
// Fetch all request data.
$data = Input::all();
// Build the validation constraint set.
$rules = array(
'username' => 'required|min:3|max:32',
'email' => 'required|email',
'password' => 'required|confirm|min:3'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if ($validator->passes()) {
// Normally we would do something with the data.
return 'Data was saved.';
}
return Redirect::to('/')->withErrors($validator);
});
Issue seems to be due to using confirm instead of confirmed. Resolved!
you can include ->back() or use
must be changed in your code , its required
return Redirect::to('/')
->back()
->withErrors($validator);

Categories