1

我创建了简单的表单,允许用户输入评论。但我想要实现的是为特定用户保存到数据库中的评论(让我们说用户 id)我不知道该怎么做。这是我所做的:

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

但是通过这种方式,不会为特定用户保存评论,而是在数据库中创建新行:/

此外还有树枝代码:

  {% 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> &nbsp;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 %}

对于第一个用户,评论正文的空白字段也只显示一次......谢谢你们。

4

1 回答 1

1

与第 1 项相关:

form->bind($request);

将表单中的数据放入实体中;因此,您需要在绑定后坚持。尝试:

    $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";
    }

此外,为什么要持久化一个空对象也不是很明显,但这样做显然不是一个坏主意。

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.

于 2013-03-29T23:43:20.013 回答