我的twig文件中有以下代码:
<form method ="POST" action="{{path('deleteMessages')}}">
{% for message in pmReceived %}
{% if message.isread == false %}
{% if message.showincoming == true %}
<div class="border">
<div class="pmbox">
<p class="pmsender">{{message.sender}}</p><p class="pmdate">{{message.date|date('d-m-Y H:i:s') }}</p><p class="pmsubject">{{message.subject}}</p><input type="checkbox" name="deletePm" value="{{message.pmid}}">
</div>
<div class="pmcontents">
<p class="titleContent">Contents:</p>
<p>{{message.contents}}</p>
</div>
</div>
{% endif %}
{% endif %}
{% endfor %}
{% for message in pmReceived %}
{% if message.isread == true %}
{% if message.showincoming == true %}
<div class="border">
<div class="pmbox">
<p class="pmsender">{{message.sender}}</p><p class="pmdate">{{message.date|date('d-m-Y H:i:s') }}</p><p class="pmsubject">{{message.subject}}</p><input type="checkbox" name="deletePm" value="{{message.pmid}}">
</div>
<div class="pmcontents">
<p class="titleContent">Contents:</p>
<p>{{message.contents}}</p>
</div>
</div>
{% endif %}
{% endif %}
{% endfor %}
<button class="deleteButton" type="submit">Delete selected messages</button>
</form>
这是我的控制器代码:
public function deleteMessagesAction(Request $request) {
if (false === $this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
throw $this->createAccessDeniedException('Unable to access this page!');
}
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->get('sentValue'));
$deleteMessages = $request->get('deletePm');
var_dump($deleteMessages);
$user = $this->get('security.context')->getToken()->getUser();
$pmReceived = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findByReceiver($user->getUsername());
$pmSent = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBySender($user->getUsername());
return $this->render('LoginLoginBundle:Default:pmPage.html.twig', array('pmReceived' => $pmReceived, 'pmSent' => $pmSent, 'toDelete'=>$deleteMessages));
}
现在我希望得到所有“勾选”的价值。复选框,我认为$ deleteMessages将是一个值数组,但它只保留勾选的最后一个复选框。
如何获取控制器中所有值的数组?
答案 0 :(得分:5)
您需要更改输入的名称。 这样,您将收到一系列已选中的复选框,而不是仅收到最后一个选中的复选框:
<input type="checkbox" name="deletePm[]" value="{{message.pmid}}">
这将导致数组等于:
[
0 => 1,
1 => 10,
2 => ...,
]
然后,你可以循环这个数组来删除:
$deleteMessages = $request->get('deletePm');
foreach($deleteMessages as $deleteMessageId) {
//Do something with the ID
}