I have a list of friends, new freinds are added via a form. When you click on a friend you see all the information about him and there is an Edit button. When clicking it, I want a form to be displayed (the same as the form for adding) but already filled with the current information about the friend. It is working this way:
class FriendController extends Controller
{
public function editDisplayAction($id, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$friend = $em->getRepository('EMMyFriendsBundle:Friend')->find($id);
if (!$friend)
{
throw $this->createNotFoundException('There is no such friend');
}
$edit_fr_form = $this->createForm(new FriendType(), $friend);
if($request->getMethod() != 'POST')
{
return $this->render('EMMyFriendsBundle:Friend:edit.html.twig', array(
'id'=>$id, 'friend'=>$friend, 'fr_form' => $edit_fr_form->createView()));
}
}
/*
* @Edits the friend with the current id
*/
public function editAction($id, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$friend = $em->getRepository('EMMyFriendsBundle:Friend')->find($id);
$edit_fr_form = $this->createForm(new FriendType(), $friend);
//if($request->getMethod() == 'POST')
{
$edit_fr_form->bindRequest($request);
if ($edit_fr_form->isValid())
{
$em->flush();
}
return $this->redirect($this->generateUrl('friend_id', array('id' => $id)));
}
}
}
and this is the template:
{% block body %}
{{ parent() }}
<div>
<h2>Edit a friend</h2>
<form class="register" action="{{ path('friend_edit', {'id': friend.id})}}" method="post" {{ form_enctype(fr_form) }}>
{% form_theme fr_form 'form_table_layout.html.twig' %}
<div class="error">
{{ form_errors(fr_form) }}
</div>
{% for field in fr_form %}
{{ form_row(field) }}
{% endfor %}
<div class="woo">
<input class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
{% endblock %}
Is there some way this to work properly, without having two actions in the controller? And isn't it unrational and not very optimized in my way? Each suggestion how to make it better will be appreciated!