forms - 用循环显示 Twig Form
问题描述
我目前正在一个私人社交网络上工作,以获得乐趣并提高我的技能。无论如何,我想显示一个表单以使用循环对帖子发表评论,但我在尝试时遇到了问题。我正在使用 Symfony、twig 和 bootstrap,我想远离 js、jquery 或 ajax。
这是我的代码:
我的表单生成器:
class CommentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', null, [
"label" => "Your title"
])
->add('content', null, [
"label" => "Your content"
])
->add('submit', SubmitType::class, [
"label" => "Publish your shitty comment!"
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
]);
}
}
和我的观点:
<ul class="nav col-4 offset-3">
{% for post in posts %}
<li class="postItem">
<article class="postItem">
<p> {{ post.title }} </p>
<img id="postPics" src="{{ asset('./pictures/posts/' ~ post.picture) }}">
{{ form(leaveCommentForm) }}
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<author>{{ post.user.username }}</author>
<div class="commentPost">
{% for comment in post.comments %}
<article>
<h6 style="font-weight: bold">{{ comment.title }} -
By
<author>{{ comment.user.username }}
on {{ comment.dateCreated | date('Y-M-d') }}</author>
</h6>
<p>{{ comment.content }}</p>
</article>
{% endfor %}
</div>
<input type="hidden" value="{{ post.id }}" name="postId"> {{ post.id }}
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Leave a comment
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Leave a comment</h4>
</div>
<div class="modal-body">
{{ form_start(leaveCommentForm) }}
<input type="hidden" value="{{ post.id }}" name="postId"> {{ post.id }}
{{ form_end(leaveCommentForm) }}
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</article>
</li>
{% endfor %}
</ul>
如您所见,我想在帖子的每次迭代中显示我的表单(有或没有模态,我真的不在乎我只是在尝试一些事情)。
我的问题是:
*如果我使用模态,我无法在我的模态中获取我的 post.id,因此我无法将其发送到我的控制器。实际上,我得到每个帖子的第一个 post.id 的值。
*如果我不使用模式,我什至无法在我的页面上看到我的表单。
如果你有一个很棒的解决方案!
提前谢谢各位!
解决方案
推荐阅读
- google-cloud-platform - 将 sonarqube 与 cloudbuild 集成
- vb.net - 使用 VB.net 监控远程 FTP 服务器
- asp.net - 如何为 ASP.NET 实现 GoJS 组织结构图编辑器?
- php - 以编程方式为每个租户(客户)创建自定义电子邮件收件箱
- apache-spark - Apache Spark 驱动程序、应用程序和计算资源
- python - ValueError: `x` 中的所有数组都应该具有相同的长度。找到一对: len(x[0]) = 97, len(x[?]) = 205
- type-conversion - 表达式生成器:迄今为止的时间戳
- django - 在 Django 中,当登录用户提交表单时,如何自动将用户名添加到模型中
- cypress - 赛普拉斯在登录后截断 URL
- java - 如何在 Spring Boot 中使用内部类并将其映射为列字段变量?