Reputation: 123
I've created simple form which allows users to enter comments. But what i want to achieve is the comment to be saved to the database for particular user ( lets say for the user id ) I have not idea how to do that. Here is what i ve done :
function some Controller(){
$baza = new baza();
$em = $this->getDoctrine()->getManager();
$em->persist($baza);
$comment = $this->createFormBuilder($baza)
->add('comment', 'text')
->getForm();
if ($request->getMethod() == 'POST') {
$comment->bind($request);
if ($comment->isValid()) {
$em->flush();
echo "your comment have been submited";
}
return $this->render('AcmeWebBundle:Default:index.html.twig'
,array('users' => $users
,'count' => $total
,'comment' => $comment->createView()
));
}
But in this way the comment is not saved for particular user, instead new row in the database is created :/
And in addition is twig code:
{% extends 'AcmeWebBundle:Default:master.html.twig' %}
{% block strana %}
<h3>Total users: {{ count }} </h3>
{% endblock %}
{% block body %}
<h1> Recently booked</h1><br></br>
{% for user in users %}
<strong><em>{{ user.username}}</em></strong><p> From : <b>{{ user.from }}</b> To : <b>{{ user.to }}</b><br></br>
Car: <b>{{ user.car}}</b> Leaving on : <b>{{ user.date }}</b><br><br>
Price: <b>{{ user.price }} </b><br></br>
Comments:<br></br> {{ user.comment }} //* first to display all the comments, and than add another one *//
<br><br>
<form action="{{ path('acme_web_homepage') }}" method="post" {{ form_enctype(comment) }}>
{{ form_widget(comment) }}{{ form_widget(comment['comment']) }}
{{ form_rest(comment) }}
<input type="submit" value=" New Comment" />
</form>
<br><br>-------------------------------
</p>
{% endfor %}{% endblock %}
Also empty field for comment body is displayed only once, for the first user... Thank you guys.
Upvotes: 1
Views: 108
Reputation: 3656
Related to item 1:
form->bind($request);
puts the data from the form into the entity; therefore you need to persist after bind. Try:
$baza = new baza();
$em = $this->getDoctrine()->getManager();
$em->persist($baza);
$comment = $this->createFormBuilder($baza)
->add('comment', 'text')
->getForm();
if ($request->getMethod() == 'POST') {
$comment->bind($request);
if ($comment->isValid()) {
$em->persist($baza); // Lighthart's change
$em->flush();
echo "your comment have been submited";
}
Also, it is not obvious why you would persist an empty object, but it is not explicitly a bad idea to do so.
The second item cannot be addressed without seeing controller code, and I recommend you submit a new question so crosstalk does not dilute the answer.
Upvotes: 1