我正在尝试创建一个表单,允许经理批准休假请求列表(也计划有一个待办事项列表,并希望能够将它们标记为完成)。
我已经阅读了[在同一页面上多次生成相同的表单类型Symfony2(以及其他几个),我接近理解,但我对Symfony相当陌生,不清楚代码的哪些部分应该放在哪些文件中。我正在使用带有Doctrine的Symfony3中的表单类型和控制器。
我有从控制器中的查询($em->createQuery)返回的实体实例的列表,我希望为每个实体实例生成一个表单,甚至为每个实体生成两个表单(一个用于批准,一个用于拒绝)。
引用的问题说你需要一个循环来显示和保存它们。我的目的是一次只处理(提交)一个。我假设这部分代码会进入控制器?
我正在为控制器使用 indexAction,但使用它更像是编辑操作,因为我将处理表单,所以我传入一个 Request 对象和对象作为参数。
>
class HRMgrController extends Controller
{
/**
* Lists all manager role requests and provide a means to approve/deny.
*
* @Route("/", name="hrmgr_index")
* @Method({"GET", "POST"})
* @Security("has_role('ROLE_APP_MANAGER')")
*/
public function indexAction(Request $request, TimeOffRequest $timeOffRequest)
{
if (!empty($timeOffRequest)) {
$form = $this->createForm('CockpitBundleFormTORApprovalType', $timeOffRequest);
print "TOR Id = " . $timeOffRequest->getId() . "<BR>";
$em = $this->getDoctrine()->getManager();
$form->handleRequest($request);
print "Form name = " . $form->getName() . "<BR>";
if ($form->isSubmitted() && $form->isValid()) {
if ($form->get('approve')->isClicked()) {
print "This puppy was approved";
$timeOffRequest['status'] = 4;
}
if ($form->get('reject')->isClicked()) {
print "This puppy was rejected";
$timeOffRequest['status'] = 1;
}
$this->getDoctrine()->getManager()->flush();
print "At least its there<BR>";
// return $this->redirectToRoute('hrmgr_index');
} else {
print "did not detect form submission<BR>";
}
}
$emp = new CockpitBundleEntityEmployee();
$date = new DateTime();
$year = $date->format('Y');
$username = $this->getUser()->getUserName();
$user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
$employees = $em->getRepository('CockpitBundle:Employee')->htmlContact($user);
$tors = $em->getRepository('CockpitBundle:TimeOffRequest')->findMgrUnapprovedTORs($user->getId());
$timeoff = "<h3>Unapproved Time Off Requests</h3>";
$actions = true;
$torforms = [];
foreach ($tors as $tor) {
$target = $this->generateUrl('hrmgr_index',array("tor_id" => $tor->getId()));
$torforms[] = $this->actionForm($tor,$target)->createView();
}
return $this->render('hrmgr/index.html.twig', array(
'torforms' => $torforms,
));
我现在有表单工作但是当我提交它们时,isSubmitted() 似乎不起作用。它当前输出"未检测到表单提交"。
因此,当我有多个表单并提交一个表单时,handleRequest 是否得到正确的表单?我想我在这里也可能混淆了两个概念。我最近更改了代码,将 timeOffRequest 的 ID 作为参数提交给路由。它正确地拾取了它,这使我有可能更新表单,但该部分代码似乎不起作用。
我注意到,如果我查看调试器,我会得到类似以下内容:
> approval_form_2
[▼
"reject" => ""
"_token" => "IE1rGa5c0vaJYk74_ncxgFsoDU7wWlkAAWWjLe3Jr1w"
]
如果我单击拒绝按钮。如果我单击批准按钮,我会得到一个类似的带有"批准"的表单,所以看起来我很接近。此外,正确的 ID 会显示在操作中给出的路由中。
这是表单生成器:
<?php
namespace CockpitBundleForm;
use CockpitBundleEntityEmployee;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentFormFormEvents;
use SymfonyComponentFormFormEvent;
use SymfonyComponentFormExtensionCoreTypeDateType;
use SymfonyComponentFormExtensionCoreTypeHiddenType;
use SymfonyComponentFormExtensionCoreTypeButtonType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
class TORApprovalType extends AbstractType
{
private $nameSuffix = null;
private $name = 'time_req_approval';
public function __constructor(string $suffix = null) {
//parent::__construct();
$this->nameSuffix = $this->generateNameSuffix();
}
private function generateNameSuffix() {
if ($this->nameSuffix == null || $this->nameSuffix == '') {
$generator = new SecureRandom();
//change data to alphanumeric string
return bin2hex($generator->nextBytes(10));
}
return $this->nameSuffix;
}
public function setNameSuffix($suffix){
$this->nameSuffix = $suffix;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Build your form...
$builder->add('approve', SubmitType::class, array(
'label' => "Approve",
'attr' => array("class"=>"action-approve"),
));
$builder->add('reject', SubmitType::class, array(
'label' => "Reject",
'attr' => array("class"=>"action-reject"),
));
//$builder->add('employee');
}
public function getName() {
if ($this->nameSuffix == null || $this->nameSuffix == "" ) {
$this->nameSuffix = $this->generateNameSuffix();
}
return $this->name .'_'. $this->nameSuffix;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CockpitBundleEntityTimeOffRequest'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'cockpitbundle_timeoffrequest';
}
}
有什么线索吗?(对不起,我在度假,所以更新不是特别快。
您可以执行多个提交按钮:检查表单类型
->add('approve', 'submit')
->add('reject', 'submit')
然后在您的控制器中
if ($form->isValid()) {
// ... do something
// the save_and_add button was clicked
if ($form->get('approve')->isClicked()) {
// probably redirect to the add page again
}
if ($form->get('reject')->isClicked()) {
// probably redirect to the add page again
}
// redirect to the show page for the just submitted item
}
我能够让它与以下构建器一起工作。
$builder->add('approve', SubmitType::class, array(
'label' => "Approve",
'attr' => array("class"=>"action-approve"),
));
$builder->add('reject', SubmitType::class, array(
'label' => "Reject",
'attr' => array("class"=>"action-reject"),
));
然后在控制器形式中,我生成并处理表单。不确定这是否是最佳方法,但它可以找到。当然,这种方法每次都会重新绘制整个列表,但这对我正在做的事情来说很好。
class HRMgrController extends Controller
{
/**
* Lists all manager role requests and provide a means to approve/deny.
*
* @Route("/", name="manager_home")
* @Method({"GET"})
* @Security("has_role('ROLE_APP_MANAGER')")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$emp = new CockpitBundleEntityEmployee();
$employeeSummary = [];
$date = new DateTime();
$year = $date->format('Y');
$username = $this->getUser()->getUserName();
$user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
$myemployees = $em->getRepository('CockpitBundle:Employee')->findManagersEmployees($user);
$torRep = $em->getRepository('CockpitBundle:TimeOffRequest');
$toas = [];
$torforms = [];
foreach ($myemployees as $employee) {
$tors = $torRep->findAllMine($employee,$year);
$toas[$employee->getDisplayName()] = $em->getRepository('CockpitBundle:TimeOffAllocation')->getEmpAllocation($employee->getId(),$year);
$employeeSummary[$employee->getDisplayName()] = $torRep->mySummary($tors,$toas[$employee->getDisplayName()]);
if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Vacation']['Requested'])) {
foreach ($employeeSummary[$employee->getDisplayName()]['Vacation']['Requested']['items'] as $tor) {
$target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
$torforms[] = $this->actionForm($tor,$target)->createView();
}
}
if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested'])) {
foreach ($employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested']['items'] as $tor) {
$target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
$torforms[] = $this->actionForm($tor,$target)->createView();
}
}
if (array_key_exists('Time Off',$employeeSummary[$employee->getDisplayName()]) &&
array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Time Off']['Requested'])) {
foreach ($employeeSummary[$employee->getDisplayName()]['Time Off']['Requested']['items'] as $tor) {
$target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
$torforms[] = $this->actionForm($tor,$target)->createView();
}
}
}
return $this->render('hrmgr/index.html.twig', array(
'employeeSummary' => $employeeSummary,
'torforms' => $torforms,
'year' => $year,
));
}
/**
* Lists all manager role requests and provide a means to approve/deny.
*
* @Route("/{tor_id}", name="hrmgr_tor_approval")
* @Method({ "POST" })
* @ParamConverter("timeOffRequest", class="CockpitBundle:TimeOffRequest", options={"id"="tor_id"})
* @Security("has_role('ROLE_APP_MANAGER')")
*/
public function approvalAction(Request $request, TimeOffRequest $timeOffRequest)
{
if (!empty($timeOffRequest)) {
$form = $this->createForm('CockpitBundleFormTORApprovalType', $timeOffRequest);
$id = $timeOffRequest->getId();
$em = $this->getDoctrine()->getManager();
$form->handleRequest($request);
$postparams = $request->request->all();
if (array_key_exists("approval_form_$id",$postparams)) {
// Form was submitted
if (array_key_exists("approve",$postparams["approval_form_$id"])) {
$status = $em->getReference('CockpitBundleEntityTimeOffStatus', 4);
$timeOffRequest->setStatus($status);
$timeOffRequest->setApprovedDate(new DateTime);
$em->persist($timeOffRequest);
$em->flush($timeOffRequest);
}
if (array_key_exists("reject",$postparams["approval_form_$id"])) {
$status = $em->getReference('CockpitBundleEntityTimeOffStatus', 1);
$timeOffRequest->setStatus($status);
$timeOffRequest->setApprovedDate(new DateTime);
$em->persist($timeOffRequest);
$em->flush($timeOffRequest);
}
} else {
print "Form did not exist<BR>";
}
return $this->redirectToRoute('manager_home');
}
}
public function actionForm($tor,$target) {
return $this->get('form.factory')->createNamedBuilder('approval_form_'.$tor->getId(), CockpitBundleFormTORApprovalType::class, $tor,
array("action"=> $target))->getForm();
}
}