3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Base class for offline membership / membership type / membership renewal and membership status forms
22 class CRM_Member_Form
extends CRM_Contribute_Form_AbstractEditPayment
{
24 use CRM_Core_Form_EntityFormTrait
;
33 * Array of from email ids
36 protected $_fromEmails = [];
39 * Details of all enabled membership types.
43 protected $allMembershipTypeDetails = [];
46 * Array of membership type IDs and whether they permit autorenewal.
50 protected $membershipTypeRenewalStatus = [];
53 * Price set ID configured for the form.
60 * Price set details as an array.
67 * The order being processed.
69 * @var \CRM_Financial_BAO_Order
74 * This string is the used for passing to the buildAmount hook.
78 protected $formContext = 'membership';
83 public function getFormContext(): string {
84 return $this->formContext
;
88 * Explicitly declare the entity api name.
90 public function getDefaultEntity() {
97 protected $statusMessage = [];
100 * Add to the status message.
104 protected function addStatusMessage($message) {
105 $this->statusMessage
[] = $message;
109 * Get the status message.
113 protected function getStatusMessage() {
114 return implode(' ', $this->statusMessage
);
118 * Values submitted to the form, processed along the way.
122 protected $_params = [];
125 * Fields for the entity to be assigned to the template.
127 * Fields may have keys
128 * - name (required to show in tpl from the array)
129 * - description (optional, will appear below the field)
130 * - not-auto-addable - this class will not attempt to add the field using addField.
131 * (this will be automatically set if the field does not have html in it's metadata
132 * or is not a core field on the form's entity).
133 * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
134 * - template - use a field specific template to render this field
136 * - is_freeze (field should be frozen).
140 protected $entityFields = [];
142 public function preProcess() {
143 // Check for edit permission.
144 if (!CRM_Core_Permission
::checkActionPermission('CiviMember', $this->_action
)) {
145 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
147 if (!CRM_Member_BAO_Membership
::statusAvailabilty()) {
148 // all possible statuses are disabled - redirect back to contact form
149 CRM_Core_Error
::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
152 parent
::preProcess();
154 $params['context'] = CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
155 $params['id'] = CRM_Utils_Request
::retrieve('id', 'Positive', $this);
156 $params['mode'] = CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this);
158 $this->setContextVariables($params);
160 $this->assign('context', $this->_context
);
161 $this->assign('membershipMode', $this->_mode
);
162 $this->allMembershipTypeDetails
= CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, [], TRUE);
163 foreach ($this->allMembershipTypeDetails
as $index => $membershipType) {
164 if ($membershipType['auto_renew']) {
165 $this->_recurMembershipTypes
[$index] = $membershipType;
166 $this->membershipTypeRenewalStatus
[$index] = $membershipType['auto_renew'];
172 * Set default values for the form. MobileProvider that in edit/view mode
173 * the default values are retrieved from the database
179 public function setDefaultValues() {
181 if (isset($this->_id
)) {
182 $params = ['id' => $this->_id
];
183 CRM_Member_BAO_Membership
::retrieve($params, $defaults);
184 if (isset($defaults['minimum_fee'])) {
185 $defaults['minimum_fee'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($defaults['minimum_fee']);
188 if (isset($defaults['status'])) {
189 $this->assign('membershipStatus', $defaults['status']);
192 if (!empty($defaults['is_override'])) {
193 $defaults['is_override'] = CRM_Member_StatusOverrideTypes
::PERMANENT
;
195 if (!empty($defaults['status_override_end_date'])) {
196 $defaults['is_override'] = CRM_Member_StatusOverrideTypes
::UNTIL_DATE
;
200 if ($this->_action
& CRM_Core_Action
::ADD
) {
201 $defaults['is_active'] = 1;
204 if (isset($defaults['member_of_contact_id']) &&
205 $defaults['member_of_contact_id']
207 $defaults['member_org'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
208 $defaults['member_of_contact_id'], 'display_name'
211 if (!empty($defaults['membership_type_id'])) {
212 $this->_memType
= $defaults['membership_type_id'];
214 if (is_numeric($this->_memType
)) {
215 $defaults['membership_type_id'] = [];
216 $defaults['membership_type_id'][0] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
218 'member_of_contact_id',
221 $defaults['membership_type_id'][1] = $this->_memType
;
224 $defaults['membership_type_id'] = $this->_memType
;
230 * Build the form object.
232 public function buildQuickForm() {
233 $this->assignSalesTaxMetadataToTemplate();
235 $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
236 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
237 $this->assign('recurProcessor', json_encode($this->_recurPaymentProcessors
));
238 // Build the form for auto renew. This is displayed when in credit card mode or update mode.
239 // The reason for showing it in update mode is not that clear.
240 if ($this->_mode ||
($this->_action
& CRM_Core_Action
::UPDATE
)) {
241 if (!empty($this->_recurPaymentProcessors
)) {
242 $this->assign('allowAutoRenew', TRUE);
245 $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
246 NULL, ['onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );"]
248 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
249 $autoRenewElement->freeze();
252 $this->addElement('checkbox',
254 ts('Membership renewed automatically')
258 $this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus
));
260 if ($this->_action
& CRM_Core_Action
::RENEW
) {
264 'name' => ts('Renew'),
269 'name' => ts('Cancel'),
273 elseif ($this->_action
& CRM_Core_Action
::DELETE
) {
277 'name' => ts('Delete'),
282 'name' => ts('Cancel'),
290 'name' => ts('Save'),
295 'name' => ts('Save and New'),
300 'name' => ts('Cancel'),
307 * Extract values from the contact create boxes on the form and assign appropriately to
309 * - $this->_contributorEmail,
310 * - $this->_memberEmail &
311 * - $this->_contributionName
312 * - $this->_memberName
313 * - $this->_contactID (effectively memberContactId but changing might have spin-off effects)
314 * - $this->_contributorContactId - id of the contributor
315 * - $this->_receiptContactId
317 * If the member & contributor are the same then the values will be the same. But if different people paid
318 * then they weill differ
320 * @param array $formValues
321 * values from form. The important values we are looking for are.
323 * - soft_credit_contact_id
325 public function storeContactFields($formValues) {
326 // in a 'standalone form' (contact id not in the url) the contact will be in the form values
327 if (!empty($formValues['contact_id'])) {
328 $this->_contactID
= $formValues['contact_id'];
331 [$this->_memberDisplayName
, $this->_memberEmail
] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
333 //CRM-10375 Where the payer differs to the member the payer should get the email.
334 // here we store details in order to do that
335 if (!empty($formValues['soft_credit_contact_id'])) {
336 $this->_receiptContactId
= $this->_contributorContactID
= $formValues['soft_credit_contact_id'];
337 [$this->_contributorDisplayName
, $this->_contributorEmail
] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contributorContactID
);
340 $this->_receiptContactId
= $this->_contributorContactID
= $this->_contactID
;
341 $this->_contributorDisplayName
= $this->_memberDisplayName
;
342 $this->_contributorEmail
= $this->_memberEmail
;
347 * Set variables in a way that can be accessed from different places.
349 * This is part of refactoring for unit testability on the submit function.
351 * @param array $params
353 protected function setContextVariables($params) {
355 'action' => '_action',
356 'context' => '_context',
358 'cid' => '_contactID',
361 foreach ($variables as $paramKey => $classVar) {
362 if (isset($params[$paramKey]) && !isset($this->$classVar)) {
363 $this->$classVar = $params[$paramKey];
368 $this->_memType
= CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'membership_type_id');
369 $this->_membershipIDs
[] = $this->_id
;
371 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
375 * Create a recurring contribution record.
377 * @param array $contributionRecurParams
379 * @param int $membershipTypeID
382 * @throws \CiviCRM_API3_Exception
384 protected function processRecurringContribution($contributionRecurParams, $membershipTypeID) {
387 'frequency_interval' => 'duration_interval',
388 'frequency_unit' => 'duration_unit',
390 $membershipType = civicrm_api3('MembershipType', 'getsingle', [
391 'id' => $membershipTypeID,
392 'return' => $mapping,
395 $returnParams = ['is_recur' => TRUE];
396 foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
397 $contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
398 $returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
401 $contributionRecur = civicrm_api3('ContributionRecur', 'create', $contributionRecurParams);
402 $returnParams['contributionRecurID'] = $contributionRecur['id'];
403 return $returnParams;
407 * Ensure price parameters are set.
409 * If they are not set it means a quick config option has been chosen so we
410 * fill them in here to make the two flows the same. They look like 'price_2' => 2 etc.
412 * @param array $formValues
414 protected function ensurePriceParamsAreSet(&$formValues) {
415 foreach ($formValues as $key => $value) {
416 if ((substr($key, 0, 6) == 'price_') && is_numeric(substr($key, 6))) {
420 $priceFields = CRM_Member_BAO_Membership
::setQuickConfigMembershipParameters(
421 $formValues['membership_type_id'][0],
422 $formValues['membership_type_id'][1],
423 CRM_Utils_Array
::value('total_amount', $formValues),
426 $formValues = array_merge($formValues, $priceFields['price_fields']);
430 * Get the details for the selected price set.
432 * @param array $params
433 * Parameters submitted to the form.
437 protected function getPriceSetDetails(array $params): ?
array {
438 $priceSetID = $params['price_set_id'] ??
NULL;
440 return CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
443 $priceSet = CRM_Price_BAO_PriceSet
::getDefaultPriceSet('membership');
444 $priceSet = reset($priceSet);
445 return CRM_Price_BAO_PriceSet
::getSetDetail($priceSet['setID']);
450 * Get the selected price set id.
452 * @param array $params
453 * Parameters submitted to the form.
457 protected function getPriceSetID(array $params): int {
458 $priceSetID = $params['price_set_id'] ??
NULL;
460 $priceSetDetails = $this->getPriceSetDetails($params);
461 return (int) key($priceSetDetails);
463 return (int) $priceSetID;
467 * Store parameters relating to price sets.
469 * @param array $formValues
473 protected function setPriceSetParameters(array $formValues): array {
474 // process price set and get total amount and line items.
475 $this->_priceSetId
= $this->getPriceSetID($formValues);
476 $this->ensurePriceParamsAreSet($formValues);
477 $priceSetDetails = $this->getPriceSetDetails($formValues);
478 $this->_priceSet
= $priceSetDetails[$this->_priceSetId
];
479 $this->order
= new CRM_Financial_BAO_Order();
480 $this->order
->setPriceSelectionFromUnfilteredInput($formValues);
481 $this->order
->setPriceSetID($this->getPriceSetID($formValues));
482 $this->order
->setForm($this);
483 if ($priceSetDetails[$this->order
->getPriceSetID()]['is_quick_config'] && isset($formValues['total_amount'])) {
484 // Amount overrides only permitted on quick config.
485 // Possibly Order object should enforce this...
486 $this->order
->setOverrideTotalAmount($formValues['total_amount']);
488 $this->order
->setOverrideFinancialTypeID((int) $formValues['financial_type_id']);
493 * Wrapper function for unit tests.
495 * @param array $formValues
497 public function testSubmit(array $formValues): void
{
498 $this->exportedValues
= $formValues;
499 $this->setContextVariables($formValues);
500 $this->_memType
= $formValues['membership_type_id'][1];
501 $this->_params
= $formValues;
506 * Get order related params.
508 * In practice these are contribution params but later they cann be used with the Order api.
512 * @throws \CiviCRM_API3_Exception
514 protected function getOrderParams(): array {
516 'lineItems' => [$this->_priceSetId
=> $this->order
->getLineItems()],
517 // This is one of those weird & wonderful legacy params we aim to get rid of.
518 'processPriceSet' => TRUE,
519 'tax_amount' => $this->order
->getTotalTaxAmount(),
524 * Get the currency in use.
526 * This just defaults to getting the default currency
527 * as other currencies are not supported on the membership
528 * forms at the moment.
530 * @param array $submittedValues
534 public function getCurrency($submittedValues = []): string {
535 return CRM_Core_Config
::singleton()->defaultCurrency
;