/** * @param Form $form */ protected function validateFormAndSendMail(Form $form) { if (!$form->validate()) { return; } global $container; /** @var EventDispatcher $eventDispatcher */ $eventDispatcher = $container['event-dispatcher']; /** @var TransportInterface $transport */ $transport = $container['avisota.transport.default']; $values = $form->fetchAll(); $email = $values['email']; $repository = EntityHelper::getRepository('Avisota\\Contao:Recipient'); $recipient = $repository->findOneBy(array('email' => $email)); if ($recipient) { /** @var \Avisota\Contao\Entity\Recipient $recipient */ if ($this->avisota_unsubscribe_show_mailing_lists) { $mailingListIds = $values['mailingLists']; } if (!$this->avisota_unsubscribe_show_mailing_lists) { $mailingListIds = deserialize($this->avisota_mailing_lists); } $subscriptions = $recipient->getSubscriptions(); $subscriptions = array_filter($subscriptions->toArray(), function (\Avisota\Contao\Entity\Subscription $subscription) use($mailingListIds) { return $subscription->getMailingList() && in_array($subscription->getMailingList()->getId(), $mailingListIds); }); /** @var SubscriptionManager $subscriptionManager */ $subscriptionManager = $container['avisota.subscription']; /** @var Subscription[] $subscriptions */ $subscriptionManager->unsubscribe($subscriptions); \Session::getInstance()->set('AVISOTA_LAST_SUBSCRIPTIONS', $subscriptions); if (count($subscriptions)) { if ($this->avisota_unsubscribe_confirmation_message) { $messageRepository = EntityHelper::getRepository('Avisota\\Contao:Message'); $message = $messageRepository->find($this->avisota_unsubscribe_confirmation_message); if ($message) { /** @var MessageRendererInterface $renderer */ $renderer = $container['avisota.message.renderer']; $data = array('subscriptions' => $subscriptions); $template = $renderer->renderMessage($message); $mail = $template->render($recipient, $data); $transport->send($mail); } } if ($this->avisota_unsubscribe_confirmation_page) { $event = new GetPageDetailsEvent($this->avisota_unsubscribe_confirmation_page); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_PAGE_DETAILS, $event); $event = new GenerateFrontendUrlEvent($event->getPageDetails()); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GENERATE_FRONTEND_URL, $event); $event = new RedirectEvent($event->getUrl()); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, $event); } } $this->Template->subscriptions = $subscriptions; } else { $this->Template->subscriptions = array(); } }
/** * Automatically add Billpay conditions to checkout form * * @param Form $objForm * @param \Module $objModule */ public static function addOrderCondition(Form $objForm, \Module $objModule) { if (Isotope::getCart()->hasPayment() && Isotope::getCart()->getPaymentMethod() instanceof BillpayWithSaferpay) { $strLabel = $GLOBALS['TL_LANG']['MSC']['billpay_agb_' . Isotope::getCart()->getBillingAddress()->country]; if ($strLabel == '') { throw new \LogicException('Missing BillPay AGB for country "' . Isotope::getCart()->getBillingAddress()->country . '" and language "' . $GLOBALS['TL_LANGUAGE'] . '"'); } $objForm->addFormField('billpay_confirmation', array('label' => array('', $strLabel), 'inputType' => 'checkbox', 'eval' => array('mandatory' => true))); } }
/** * Validates a widget * * @param mixed $varValue Widget value * @param \Widget $objWidget * @param Form $objForm * * @return mixed Widget value * * @throws \Exception If value is not provided */ public function validate($varValue, $objWidget, $objForm) { foreach ($this->arrMatches as $strFieldName => $arrValues) { $objTarget = $objForm->getWidget($strFieldName); // @todo if the target widget isn't validated, we have no value here // can we do anything about it? $varTargetValue = $objTarget->value; if (trim($varValue) == '' && $this->arrMatches[$objTarget->name] && in_array($varTargetValue, $this->arrMatches[$objTarget->name])) { throw new \Exception($GLOBALS['TL_LANG']['MSC']['mandatory']); } } return $varValue; }
public function testBindModelDefaultValues() { $objInstance = new Form('someid', 'POST', function () { return false; }); $objModel = \PageModel::findByPk(13); $objInstance->bindModel($objModel); $objInstance->addFormField('id', array('inputType' => 'text'))->addFormField('pageTitle', array('inputType' => 'text'))->addFormField('jumpTo', array('inputType' => 'text')); $objInstance->createWidgets(); $this->assertEquals(13, $objInstance->getWidget('id')->value); $this->assertEquals('My page', $objInstance->getWidget('pageTitle')->value); $this->assertEquals(11, $objInstance->getWidget('jumpTo')->value); }
/** * Return array of tokens for notification * @param IsotopeProductCollection * @return array */ public function getNotificationTokens(IsotopeProductCollection $objCollection) { $arrTokens = array(); foreach ($this->objForm->getFormFields() as $strField => $arrConfig) { $varValue = null; if (isset($_SESSION['FORM_DATA'][$strField])) { $varValue = $_SESSION['FORM_DATA'][$strField]; if ('textarea' === $arrConfig['type']) { $varValue = nl2br($varValue); } } if (isset($GLOBALS['ISO_HOOKS']['getOrderConditionsValue']) && is_array($GLOBALS['ISO_HOOKS']['getOrderConditionsValue'])) { foreach ($GLOBALS['ISO_HOOKS']['getOrderConditionsValue'] as $callback) { $objCallback = \System::importStatic($callback[0]); $varValue = $objCallback->{$callback}[1]($strField, $varValue, $arrConfig, $this->objForm); } } if (null !== $varValue) { $arrTokens['form_' . $strField] = $varValue; } } return $arrTokens; }
/** * Generate the module */ protected function compile() { /** @var Message|\Model\Collection $objMessages */ /** @noinspection PhpUndefinedMethodInspection */ $objMessages = Message::findBy(array('pid IN (' . implode(',', $this->nc_member_customizable_notifications) . ') AND member_customizable<>\'\''), array()); $arrOptions = array(); $arrSelected = array(); while ($objMessages->next()) { if (MemberMessages::memberHasSelected(\FrontendUser::getInstance()->id, $objMessages->id)) { $arrSelected[$objMessages->pid][] = $objMessages->id; } // Fetch tokens for parsing the option labels $objNotification = $objMessages->getRelated('pid'); $objGateway = $objMessages->getRelated('gateway'); $arrTokens = array_merge(array_combine(array_map(function ($key) { return 'message_' . $key; }, array_keys($objMessages->row())), $objMessages->row()), array_combine(array_map(function ($key) { return 'notification_' . $key; }, array_keys($objNotification->row())), $objNotification->row()), array_combine(array_map(function ($key) { return 'gateway_' . $key; }, array_keys($objGateway->row())), $objGateway->row())); $arrOptions[$objMessages->pid][$objMessages->id] = \StringUtil::parseSimpleTokens($this->nc_member_customizable_label ?: '##message_title## (##gateway_title##)', $arrTokens); } $objForm = new Form('tl_select_notifications', 'POST', function ($objHaste) { /** @noinspection PhpUndefinedMethodInspection */ return \Input::post('FORM_SUBMIT') === $objHaste->getFormId(); }); foreach ($arrOptions as $k => $options) { /** @noinspection PhpUndefinedMethodInspection */ $objForm->addFormField('notification_' . $k, array('label' => Notification::findByPk($objMessages->pid)->title, 'inputType' => $this->nc_member_customizable_inputType, 'options' => $options, 'eval' => array('mandatory' => $this->nc_member_customizable_mandatory), 'value' => !empty($arrSelected[$k]) ? $arrSelected[$k] : array())); // Add a validator // We check whether it is possible to send the message to the recipient by means of the gateway // E.g. a sms message requires a phone number set by the member which is not default $objForm->addValidator('notification_' . $k, function ($varValue, $objWidget, $objForm) use($k, $arrOptions) { if (empty($varValue)) { return $varValue; } foreach ($varValue as $msg) { /** @noinspection PhpUndefinedMethodInspection */ /** @var Message|\Model $objMessage */ $objMessage = Message::findByPk($msg); /** @noinspection PhpUndefinedMethodInspection */ /** @var GatewayInterface|MessageDraftCheckSendInterface $objGateway */ $objGateway = $objMessage->getRelated('gateway')->getGateway(); if (!$objGateway instanceof MessageDraftCheckSendInterface) { continue; } // Throw the error message as exception if the method has not yet if (!$objGateway->canSendDraft($objMessage)) { throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['messageNotSelectable'], $arrOptions[$k][$msg])); } } return $varValue; }); } $objForm->addSubmitFormField('submit', $GLOBALS['TL_LANG']['MSC']['saveSettings']); // Process form submit if ($objForm->validate()) { $arrData = $objForm->fetchAll(); foreach ($arrData as $field => $notification) { if (strpos($field, 'notification_') !== 0) { continue; } list(, $notificationId) = trimsplit('_', $field); // Delete foreach (array_diff((array) $arrSelected[$notificationId], (array) $notification) as $msg) { /** @noinspection PhpUndefinedMethodInspection */ MemberMessages::findByMemberAndMessage(\FrontendUser::getInstance()->id, $msg)->delete(); } // Create foreach (array_diff((array) $notification, (array) $arrSelected[$notificationId]) as $msg) { /** @var MemberMessages|\Model $objMemberMessage */ $objMemberMessage = new MemberMessages(); $objMemberMessage->member_id = \FrontendUser::getInstance()->id; $objMemberMessage->message_id = $msg; $objMemberMessage->save(); } } } $this->Template->form = $objForm->generate(); }
/** * Bind the form widget values to an MetaModels Item * * @param Form $hasteForm * @throws \Exception When an MetaModels Item is missing */ public function bindFormToItem(Form $hasteForm) { if (is_null($this->mmItem)) { throw new \Exception('Trying to bind fields on non existing mmItem - aborting'); return false; } $this->fields->reset(); while ($this->fields->next()) { $field = $this->fields->current(); $widget = $hasteForm->getWidget($field->getColName()); if (!is_a($field, 'Teamsisu\\MetaModelsFrontendInput\\DataContainer\\Field\\FieldsetField')) { $saveHandler = $field->getSaveHandler(); $saveHandler->setItem($this->mmItem); $value = $saveHandler->parseWidget($widget); if ($value) { $saveHandler->setValue($value); } } } }
/** * Edit an address record. Based on the PersonalData core module * @param integer * @return void */ protected function edit($intAddressId = 0) { $table = Address::getTable(); \System::loadLanguageFile(\MemberModel::getTable()); $this->Template = new \Isotope\Template($this->memberTpl); $this->Template->hasError = false; $this->Template->slabel = specialchars($GLOBALS['TL_LANG']['MSC']['saveData']); if ($intAddressId === 0) { $objAddress = Address::createForMember(\FrontendUser::getInstance()->id); } else { $objAddress = Address::findOneForMember($intAddressId, \FrontendUser::getInstance()->id); } if (null === $objAddress) { global $objPage; \Controller::redirect(\Controller::generateFrontendUrl($objPage->row())); } $objForm = new Form($table . '_' . $this->id, 'POST', function ($objForm) { return \Input::post('FORM_SUBMIT') === $objForm->getFormId(); }, (bool) $this->tableless); $objForm->bindModel($objAddress); // Add form fields and modify for the address book $arrFields = $this->arrFields; $objForm->addFieldsFromDca($table, function ($strName, &$arrDca) use($arrFields) { if (!in_array($strName, $arrFields) || !$arrDca['eval']['feEditable']) { return false; } // Map checkboxWizard to regular checkbox widget if ($arrDca['inputType'] == 'checkboxWizard') { $arrDca['inputType'] = 'checkbox'; } // Special field "country" if ($strName == 'country') { $arrCountries = array_merge(Isotope::getConfig()->getBillingCountries(), Isotope::getConfig()->getShippingCountries()); $arrDca['reference'] = $arrDca['options']; $arrDca['options'] = array_values(array_intersect(array_keys($arrDca['options']), $arrCountries)); $arrDca['default'] = Isotope::getConfig()->billing_country; } return true; }); if ($objForm->isSubmitted()) { if ($objForm->validate()) { $objAddress->save(); // Call onsubmit_callback if (is_array($GLOBALS['TL_DCA'][$table]['config']['onsubmit_callback'])) { foreach ($GLOBALS['TL_DCA'][$table]['config']['onsubmit_callback'] as $callback) { $objCallback = \System::importStatic($callback[0]); $objCallback->{$callback}[1]($objAddress); } } global $objPage; \Controller::redirect(\Controller::generateFrontendUrl($objPage->row())); } else { $this->Template->hasError = true; } } $objForm->addToTemplate($this->Template); // Add groups $arrGroups = array(); foreach ($objForm->getFormFields() as $strName => $arrConfig) { if ($arrConfig['feGroup'] != '') { $arrGroups[$arrConfig['feGroup']][$strName] = $objForm->getWidget($strName)->parse(); } } foreach ($arrGroups as $k => $v) { $this->Template->{$k} = $v; } $this->Template->addressDetails = $GLOBALS['TL_LANG'][$table]['addressDetails']; $this->Template->contactDetails = $GLOBALS['TL_LANG'][$table]['contactDetails']; $this->Template->personalData = $GLOBALS['TL_LANG'][$table]['personalData']; $this->Template->loginDetails = $GLOBALS['TL_LANG'][$table]['loginDetails']; }
/** * Generate the module */ protected function compile() { $this->Template->hasError = false; $this->Template->slabel = specialchars($GLOBALS['TL_LANG']['MSC']['saveAddressButton']); $table = Address::getTable(); \System::loadLanguageFile($table); \Controller::loadDataContainer($table); // Call onload_callback (e.g. to check permissions) if (is_array($GLOBALS['TL_DCA'][$table]['config']['onload_callback'])) { foreach ($GLOBALS['TL_DCA'][$table]['config']['onload_callback'] as $callback) { $objCallback = \System::importStatic($callback[0]); $objCallback->{$callback}[1](); } } $arrFields = $this->iso_addressFields; $useBilling = in_array('billing', $this->iso_address); $objAddress = $this->getDefaultAddress($useBilling); $objForm = new Form('iso_cart_address_' . $this->id, 'POST', function ($objHaste) { /** @type Form $objHaste */ return \Input::post('FORM_SUBMIT') === $objHaste->getFormId(); }, (bool) $this->tableless); $objForm->bindModel($objAddress); // Add form fields $objForm->addFieldsFromDca($table, function ($strName, &$arrDca) use($arrFields, $useBilling) { if (!in_array($strName, $arrFields) || !$arrDca['eval']['feEditable'] || $arrDca['eval']['membersOnly'] && FE_USER_LOGGED_IN !== true) { return false; } // Special field "country" if ($strName == 'country') { if ($useBilling) { $arrCountries = Isotope::getConfig()->getBillingCountries(); $arrDca['default'] = Isotope::getConfig()->billing_country; } else { $arrCountries = Isotope::getConfig()->getShippingCountries(); $arrDca['default'] = Isotope::getConfig()->shipping_country; } $arrDca['reference'] = $arrDca['options']; $arrDca['options'] = array_values(array_intersect(array_keys($arrDca['options']), $arrCountries)); } return true; }); $objCart = Isotope::getCart(); // Save the data if ($objForm->validate()) { if (!$objCart->id) { $objCart->save(); } $objAddress->tstamp = time(); $objAddress->pid = $objCart->id; $objAddress->save(); // Call onsubmit_callback if (is_array($GLOBALS['TL_DCA'][$table]['config']['onsubmit_callback'])) { foreach ($GLOBALS['TL_DCA'][$table]['config']['onsubmit_callback'] as $callback) { $objCallback = \System::importStatic($callback[0]); $objCallback->{$callback}[1]($objAddress); } } // Set the billing address if ($useBilling) { $objCart->setBillingAddress($objAddress); } // Set the shipping address if (in_array('shipping', $this->iso_address)) { $objCart->setShippingAddress($objAddress); } $this->jumpToOrReload($this->jumpTo); } $objForm->addToTemplate($this->Template); // Predefine the group order (other groups will be appended automatically) $arrGroups = array(); $categories = array('personal' => array(), 'address' => array(), 'contact' => array(), 'login' => array(), 'profile' => array()); foreach ($objForm->getFormFields() as $strName => $arrConfig) { if ($arrConfig['feGroup'] != '') { $arrGroups[$arrConfig['feGroup']][$strName] = $objForm->getWidget($strName)->parse(); } } foreach ($arrGroups as $k => $v) { $this->Template->{$k} = $v; // backwards compatibility $key = $k . ($k == 'personal' ? 'Data' : 'Details'); $categories[$GLOBALS['TL_LANG']['tl_member'][$key]] = $v; } $this->Template->categories = $categories; $this->Template->addressDetails = $GLOBALS['TL_LANG'][$table]['addressDetails']; $this->Template->contactDetails = $GLOBALS['TL_LANG'][$table]['contactDetails']; $this->Template->personalData = $GLOBALS['TL_LANG'][$table]['personalData']; $this->Template->loginDetails = $GLOBALS['TL_LANG'][$table]['loginDetails']; }
/** * @param array $availableFieldNames * @param array $values * * @return Form * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ protected function createForm(array $availableFieldNames, array $values = array()) { global $TL_DCA; $class = new \ReflectionClass($this); $form = new Form('avisota_' . strtolower($class->getShortName()) . '_' . $this->id, 'POST', function (Form $haste) { return \Input::post('FORM_SUBMIT') === $haste->getFormId(); }, (bool) $this->tableless); foreach ($availableFieldNames as $availableFieldName) { if (isset($TL_DCA['orm_avisota_recipient']['fields'][$availableFieldName])) { $dca = $TL_DCA['orm_avisota_recipient']['fields'][$availableFieldName]; if (isset($values[$availableFieldName])) { $dca['value'] = $values[$availableFieldName]; } $form->addFormField($availableFieldName, $dca); } } if ($this->avisota_form_target) { $form->setFormActionFromPageId($this->avisota_form_target); } return $form; }