protected function handleNotificationForm(User $user, Request $request, UserRepository $userRepo) { $notificationTypes = $this->repo('NotificationType')->findAll(); $currentSubIds = $user->getNotificationSubs()->map(function (NotificationSub $sub) { return $sub->getNotificationType()->getId(); })->toArray(); $formBuilder = $this->createFormBuilder(); $formData = []; $notificationTypesById = []; /** @var NotificationType $notificationType */ foreach ($notificationTypes as $notificationType) { $nid = $notificationType->getId(); $notificationTypesById[$nid] = $notificationType; // kill me $isEG = stripos($notificationType->getCommType()->getTypeName(), 'evolution games') !== false; $formBuilder->add('notification_' . $nid, 'checkbox', ['label' => ($isEG ? '[EG]' : '') . $notificationType->getName(), 'required' => false, 'widget_checkbox_label' => 'widget']); $formData['notification_' . $nid] = in_array($nid, $currentSubIds); } $formBuilder->setData($formData); $form = $formBuilder->getForm(); $form->handleRequest($request); if ($form->isValid()) { foreach ($formData as $key => $x) { $id = (int) str_replace('notification_', '', $key); $enabled = $form->get($key)->getData(); $sub = NotificationSub::make($user, $notificationTypesById[$id]); if ($enabled) { if (!$user->hasNotificationSub($sub)) { $user->addNotificationSub($sub); $this->em()->persist($sub); } } else { if ($oldsub = $user->hasNotificationSub($sub)) { $user->removeNotificationSub($oldsub); $this->em()->remove($oldsub); } } } $this->em()->flush(); $this->flash('success', 'Your profile has been updated.'); return $this->redirectRoute('user_profile_edit', ['tab' => 'notifications']); } return $form; }