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.
Related
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'd like to use the same view for both editing and viewing. Unfortunatly, I cannot edit my view. In symfony3, I think there is no way to index a form. I tried every thing I could but I don't know how I can use the same form. In my project, I use also JEE (linked directly to data base) to communicate with symfony using UniRest API. Here are my view and edit controllers:
/**
* #Method({"GET"})
*/
public function viewAction($id) {
$phone = new Phone();
$form = $this->createForm(PhoneType::class, $phone);
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get(link/phones/'.$id,$headers);
//$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
return $this->render('AppBundle:Phone:PhoneView.html.twig', array (
'form' => $form->createView(),
'phone' => $response->body,
) );
}
/**
* #Method({"PUT"})
*/
public function updateAction(Request $request, $id) {
$phone = new Phone();
$form = $this->createForm(PhoneType::class, $phone);
dump($request->getMethod());
if ($request->isMethod('PUT')) {
$form->handleRequest($request);
$headers = array('Content-Type' => 'application/json');
$data = json_encode($phone);
$response = Unirest\Request::put('link/phones/'.$id,$headers,$data);
//$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
dump($response->code);
return $this->redirect($this->generateUrl('phones_list'));
}
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get('link/phones/'.$id,$headers);
//$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
dump($response->code);
dump($response->body);
return $this->render('AppBundle:Phone:PhoneUpdate.html.twig', array(
'form'=> $form->createView(),
'phone'=> $response->body,
));
And here is my file PhoneView.html.twig
{% extends "::base.html.twig" %}
{% block title %}Accedant - {{ parent() }}{% endblock %}
{% block body %}
<form novalidate="novalidate" method = "get">
<p>
<label> color </label> :<input type="text" value= {{ phone.color }} />
<label> price </label> :<input type="text" value= {{ phone.price }} />
<div class="form-group col-md-offset-5">
<button type="submit" class="btn btn-default">Save</button>
</div>
</p>
</form>
{# Updating Phone #}
<p class="left-center">
<a href="{{ path('phones_update', {'id': phone.id}) }}" class="btn btn-mini btn-danger" class="btn btn-mini btn-danger">
Modify phone
</a>
</p>
{% endblock %}
And here is my PhoneUpdate.html.twig
{% extends "::base.html.twig" %}
{% block title %} Phone - {{ parent() }}{% endblock %}
{% block body %}
<div class="container">
{{ form_start(form, {'method': 'PUT'}) }}
<input type="hidden" name'_METHOD' value="PUT">
{{ form_widget(form) }}
<input type="submit" value="Sauvegarder" class="btn btn-default" />
{{ form_end(form) }}
</div>
{% endblock %}
and here is my file routing.yml
phones_view:
path: /phones/{id}
defaults: { _controller: AppBundle:Phone:view }
methods: [GET]
requirements:
id: \d+
phones_update:
path: /phones/{id}
methods: [PUT]
defaults: { _controller: AppBundle:Phone:update }
requirements:
id: \d+
Thank you for your help.
First of all, my put and delete method was not configurated. Moreover, my problem was that I thought that the put method in my routing file routing.yml has no relation with my web services. So I change my path in order to edit my form /update/{id}, and after that I got a 404 error that was because of my implementation in J2EE side.
I have started to study Symfony2 since I will probably need in my work.
routing.yml:
account_register:
path: /register
defaults: {_controller: AppBundle:Register:index}
RegisterController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\User;
class RegisterController extends Controller
{
/**
* #Route("/register")
*/
public function indexAction(Request $request)
{
$register = new User();
$form = $this->createFormBuilder($register)
->add('email', 'email', array('required' => false))
->add('password', 'password', array('required' => false))
->add('alias', 'text', array('required' => false))
->add('register', 'submit', array('label' => 'Register'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database
$em = $this->getDoctrine()->getManager();
$em->persist($register);
$em->flush();
exit("Error");
//return $this->redirectToRoute('task_success');
}
return $this->render('pages/register.html.twig', array(
'form' => $form->createView(),
));
}
}
regiser.html.twig:
{% extends 'base.html.twig' %}
{% block body %}
<br /><br />
<div class = "window">
<form>
<br /><br /><br /><br /><br /><br /><br />
{{ form_start(form) }}
{{ form_errors(form) }}
<div id=center-text>Email</div>
<div class="textfield" id=center> {{ form_widget(form.email, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }} </div>
<br />
<div id=center-text>Password</div>
<div class="textfield" id=center> {{ form_widget(form.password, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }} </div>
<br />
<div id=center-text>Alias</div>
<div class="textfield" id=center> {{ form_widget(form.alias, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }}</div>
<br /><br />
<br />
<center>
{{ form_widget(form.register, {'attr': {'class': 'button'}}) }}
</center>
{{ form_end(form) }}
</form>
{% endblock %}
When i press the submit button only the url changes from http://localhost/website/web/app_dev.php/register
to
http://localhost/website/web/app_dev.php/register?form%5Bemail%5D=&form%5Bpassword%5D=&form%5Balias%5D=&form%5Bregister%5D=&form%5B_token%5D=hd70y_KjUEY8v51dQjnjU0ZMTJ0BYOihurV6IcIvghY
What is happening is the expected form's flow. The form that you are submitting is redirecting to the same page.
If you don't want your form to be in GET, you can change it for POST :
$form = $this->createFormBuilder($register)
->setMethod('POST')
->...
When you are redirected after submitting the form, $form->handleRequest($request) binds the request (your data submitted) with the form that is just created. $form->isValid() then checks if your data is valid according to your form.
If you don't see any change after being redirected, you should check if $form->isValid() returns true.
If you want to redirect your form to another controller method, you should create another resource and then set the action attribute of your form thanks to the setAction() method.
To sum up, everything that I just told you is written and explained on this page, and you definitely should read it ! :-).
Silly me, the html was my test code and then i added the symfony {{ blocks }} and forgot to remove the old tags
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.
I have a form that asks the user to make 10 game picks and then sort the picks based on confidence. I'm using jQuery's sortable function and then populating a hidden form element (order-array) with a serialized string on each update to the order. My problem is how to deal with this array of serialized data in my controller after submission so I can store it (plus the actual game picks) into my database.
My Form View
{{ Form::open() }}
<h1>Games for Week {{ $weeknum }} </h1>
<h3>Visitors # Hometeam</h3>
<input type="hidden" name="order-array" id="order-array" value="">
<ul id="gamelist">
<?php $count = 1; ?>
#foreach($games as $game)
<li class="game-rank" id="c_{{ $count }}">
<input type="radio" name="{{ "pick_".$game->id }}" value="{{ $game->visitor }}">
{{ $game->visitor }} #
<input type="radio" name="{{ "pick_".$game->id }}" value="{{ $game->hometeam }}">
{{ $game->hometeam }}
<input type="hidden" name="{{ "game_".$count }}" value="{{ $game->id }}">
</li>
<?php $count++; ?>
#endforeach
</ul>
#if(Auth::check())
{{ Form::hidden('player', $player) }}
{{ Form::submit('Submit Picks', array('class' => 'link-button')) }}
#endif
{{ Form::close() }}
The serialized confidence data being passed to the controller
"c[]=1&c[]=3&c[]=9&c[]=4&c[]=5&c[]=6&c[]=2&c[]=7&c[]=8&c[]=10"
My controller function
public function post_new()
{
$confidence = Input::get('order-array');
for ($i=1;$i<=10;$i++) {
$array_index = $i-1;
$pick = new Pick;
$pick->user_id = Input::get('player');
$pick->game_id = Input::get("game_$i"); // game number
$pick->pick = Input::get("pick_$i"); // teamname
$pick->confidence = $confidence[$array_index];
$pick->save();
}
return Redirect::to ('users');
}
Everything works except for the confidence data. What adjustments do I need to make to my controller?
Thanks!!