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 * This class generates form components for Membership Type
22 class CRM_Member_Form_MembershipType
extends CRM_Member_Form_MembershipConfig
{
24 use CRM_Core_Form_EntityFormTrait
;
27 * Fields for the entity to be assigned to the template.
29 * Fields may have keys
30 * - name (required to show in tpl from the array)
31 * - description (optional, will appear below the field)
32 * - not-auto-addable - this class will not attempt to add the field using addField.
33 * (this will be automatically set if the field does not have html in it's metadata
34 * or is not a core field on the form's entity).
35 * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
36 * - template - use a field specific template to render this field
38 * - is_freeze (field should be frozen).
42 protected $entityFields = [];
45 * Set entity fields to be assigned to the form.
47 protected function setEntityFields() {
48 $this->entityFields
= [
52 'description' => ts("e.g. 'Student', 'Senior', 'Honor Society'..."),
55 'name' => 'description',
56 'description' => ts("Description of this membership type for internal use. May include eligibility, benefits, terms, etc."),
58 'member_of_contact_id' => [
59 'name' => 'member_of_contact_id',
60 'description' => ts("Members assigned this membership type belong to which organization (e.g. this is for membership in 'Save the Whales - Northwest Chapter'). NOTE: This organization/group/chapter must exist as a CiviCRM Organization type contact."),
63 'name' => 'minimum_fee',
64 'description' => ts('Minimum fee required for this membership type. For free/complimentary memberships - set minimum fee to zero (0). NOTE: When using CiviCRM to process sales taxes this should be the tax exclusive amount.'),
65 'formatter' => 'crmMoney',
67 'financial_type_id' => [
68 'name' => 'financial_type_id',
69 'description' => ts('Select the financial type assigned to fees for this membership type (for example \'Membership Fees\'). This is required for all membership types - including free or complimentary memberships.'),
72 'name' => 'auto_renew',
73 'options' => CRM_Core_SelectValues
::memberAutoRenew(),
74 'place_holder' => ts('You will need to select and configure a supported payment processor (currently Authorize.Net, PayPal Pro, or PayPal Website Standard) in order to offer automatically renewing memberships.'),
76 'duration_interval' => [
77 'name' => 'duration_interval',
81 'name' => 'duration_unit',
82 'description' => ts('Duration of this membership (e.g. 30 days, 2 months, 5 years, 1 lifetime)'),
86 'name' => 'period_type',
87 'description' => ts("Select 'rolling' if membership periods begin at date of signup. Select 'fixed' if membership periods begin on a set calendar date."),
88 'help' => ['id' => 'period-type', 'file' => "CRM/Member/Page/MembershipType.hlp"],
91 'fixed_period_start_day' => [
92 'name' => 'fixed_period_start_day',
93 'description' => ts("Month and day on which a <strong>fixed</strong> period membership or subscription begins. Example: A fixed period membership with Start Day set to Jan 01 means that membership periods would be 1/1/06 - 12/31/06 for anyone signing up during 2006."),
95 'fixed_period_rollover_day' => [
96 'name' => 'fixed_period_rollover_day',
97 'description' => ts('Membership signups on or after this date cover the following calendar year as well. Example: If the rollover day is November 30, membership period for signups during December will cover the following year.'),
99 'relationship_type_id' => [
100 'name' => 'relationship_type_id',
103 'name' => 'max_related',
104 'description' => ts('Maximum number of related memberships (leave blank for unlimited).'),
107 'name' => 'visibility',
108 'description' => ts("Can this membership type be used for self-service signups ('Public'), or is it only for CiviCRM users with 'Edit Contributions' permission ('Admin')."),
114 'name' => 'is_active',
118 if (!CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(['Recurring'])) {
119 $this->entityFields
['auto_renew']['not-auto-addable'] = TRUE;
120 $this->entityFields
['auto_renew']['documentation_link'] = ['page' => 'user/contributions/payment-processors'];
125 * Deletion message to be assigned to the form.
129 protected $deleteMessage;
132 * Explicitly declare the entity api name.
134 public function getDefaultEntity() {
135 return 'MembershipType';
139 * Set the delete message.
141 * We do this from the constructor in order to do a translation.
143 public function setDeleteMessage() {
144 $this->deleteMessage
= ts('WARNING: Deleting this option will result in the loss of all membership records of this type.') . ts('This may mean the loss of a substantial amount of data, and the action cannot be undone.') . ts('Do you want to continue?');
148 * Explicitly declare the form context.
150 public function getDefaultContext() {
155 * Max number of contacts we will display for membership-organisation
157 const MAX_CONTACTS
= 50;
159 public function preProcess() {
160 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, FALSE, 0);
161 $this->_BAOName
= 'CRM_Member_BAO_MembershipType';
162 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
163 $this->assign('action', $this->_action
);
165 $session = CRM_Core_Session
::singleton();
166 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipType', 'reset=1');
167 $session->pushUserContext($url);
169 $this->setPageTitle(ts('Membership Type'));
173 * Set default values for the form. MobileProvider that in edit/view mode
174 * the default values are retrieved from the database
179 public function setDefaultValues() {
180 $defaults = parent
::setDefaultValues();
182 //finding default weight to be put
183 if (!isset($defaults['weight']) ||
(!$defaults['weight'])) {
184 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Member_DAO_MembershipType');
186 //setting default relationshipType
187 if (isset($defaults['relationship_type_id'])) {
188 //$defaults['relationship_type_id'] = $defaults['relationship_type_id'].'_a_b';
189 // Set values for relation type select box
190 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaults['relationship_type_id']);
191 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaults['relationship_direction']);
192 $defaults['relationship_type_id'] = [];
193 foreach ($relTypeIds as $key => $value) {
194 $defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
198 //setting default fixed_period_start_day & fixed_period_rollover_day
199 $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
200 foreach ($periods as $per) {
201 if (isset($defaults[$per])) {
202 $date = $defaults[$per];
204 $defaults[$per] = [];
206 $date = ($date < 999) ?
'0' . $date : $date;
207 $defaults[$per]['M'] = substr($date, 0, 2);
208 $defaults[$per]['d'] = substr($date, 2, 3);
211 //special case when only day is rollover and duration is month
212 $defaults['month_fixed_period_rollover_day']['d'] = $date;
221 * Build the form object.
224 * @throws \CRM_Core_Exception
225 * @throws \CiviCRM_API3_Exception
227 public function buildQuickForm() {
228 self
::buildQuickEntityForm();
230 if ($this->_action
& CRM_Core_Action
::DELETE
) {
233 // This is a temporary variable as we work towards moving over towards using the EntityField.tpl.
234 // Fields in this array have been tested & in the tpl have been switched over to metadata.
235 // Note this kinda 'works from the top' - ie. once we hit a field that needs some thought we need
236 // to stop & make that one work.
237 $this->assign('tpl_standardised_fields', ['name', 'description', 'member_of_contact_id', 'minimum_fee']);
239 $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
240 'objectExists', ['CRM_Member_DAO_MembershipType', $this->_id
]
242 $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
244 $props = ['api' => ['params' => ['contact_type' => 'Organization']]];
245 $this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
248 $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'),
249 CRM_Core_SelectValues
::date(NULL, 'M d'), FALSE
252 // Add Auto-renew options if we have a payment processor that supports recurring contributions
253 $isAuthorize = FALSE;
255 if (CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(['Recurring'])) {
257 $options = CRM_Core_SelectValues
::memberAutoRenew();
260 $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
261 $this->assign('authorize', $isAuthorize);
264 $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
265 CRM_Core_SelectValues
::date(NULL, 'M d'), FALSE
267 $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
268 CRM_Core_SelectValues
::date(NULL, 'd'), FALSE
270 $this->add('select', 'financial_type_id', ts('Financial Type'),
271 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
), TRUE, ['class' => 'crm-select2']
274 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
275 if (is_array($relTypeInd)) {
278 $memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'),
279 $relTypeInd, FALSE, ['class' => 'crm-select2 huge', 'multiple' => 1]);
281 $this->addField('visibility', ['placeholder' => NULL, 'option_url' => NULL]);
283 $membershipRecords = FALSE;
284 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
285 $result = civicrm_api3("Membership", "get", ["membership_type_id" => $this->_id
, "options" => ["limit" => 1]]);
286 $membershipRecords = ($result["count"] > 0);
287 if ($membershipRecords) {
288 $memberRel->freeze();
292 $this->assign('membershipRecordsExists', $membershipRecords);
294 $this->addFormRule(['CRM_Member_Form_MembershipType', 'formRule']);
296 $this->assign('membershipTypeId', $this->_id
);
298 if (Civi
::settings()->get('deferred_revenue_enabled')) {
299 $deferredFinancialType = CRM_Financial_BAO_FinancialAccount
::getDeferredFinancialType();
300 $this->assign('deferredFinancialType', array_keys($deferredFinancialType));
307 * @param array $params
308 * (ref.) an assoc array of name/value pairs.
311 * mixed true or array of errors
313 public static function formRule($params) {
316 if (!$params['name']) {
317 $errors['name'] = ts('Please enter a membership type name.');
320 if (($params['minimum_fee'] > 0) && !$params['financial_type_id']) {
321 $errors['financial_type_id'] = ts('Please enter the financial Type.');
324 if (empty($params['duration_interval']) and $params['duration_unit'] != 'lifetime') {
325 $errors['duration_interval'] = ts('Please enter a duration interval.');
328 if (in_array(CRM_Utils_Array
::value('auto_renew', $params), [
332 if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
333 ($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
335 $errors['duration_unit'] = ts('Automatic renewals are not supported by the currently available payment processors when the membership duration is greater than 1 year / 12 months.');
339 if ($params['period_type'] == 'fixed' &&
340 $params['duration_unit'] == 'day'
342 $errors['period_type'] = ts('Period type should be Rolling when duration unit is Day');
345 if (($params['period_type'] == 'fixed') &&
346 ($params['duration_unit'] == 'year')
348 $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
349 foreach ($periods as $period) {
350 $month = $params[$period]['M'];
351 $date = $params[$period]['d'];
352 if (!$month ||
!$date) {
354 case 'fixed_period_start_day':
355 $errors[$period] = ts('Please enter a valid fixed period start day');
358 case 'fixed_period_rollover_day':
359 $errors[$period] = ts('Please enter a valid fixed period rollover day');
366 if ($params['fixed_period_start_day'] && !empty($params['fixed_period_start_day'])) {
367 $params['fixed_period_start_day']['Y'] = date('Y');
368 if (!CRM_Utils_Rule
::qfDate($params['fixed_period_start_day'])) {
369 $errors['fixed_period_start_day'] = ts('Please enter valid Fixed Period Start Day');
373 if ($params['fixed_period_rollover_day'] && !empty($params['fixed_period_rollover_day'])) {
374 $params['fixed_period_rollover_day']['Y'] = date('Y');
375 if (!CRM_Utils_Rule
::qfDate($params['fixed_period_rollover_day'])) {
376 $errors['fixed_period_rollover_day'] = ts('Please enter valid Fixed Period Rollover Day');
380 return empty($errors) ?
TRUE : $errors;
384 * Process the form submission.
388 public function postProcess() {
389 if ($this->_action
& CRM_Core_Action
::DELETE
) {
391 CRM_Member_BAO_MembershipType
::del($this->_id
);
393 catch (CRM_Core_Exception
$e) {
394 CRM_Core_Error
::statusBounce($e->getMessage(), NULL, ts('Membership Type Not Deleted'));
396 CRM_Core_Session
::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
399 $params = $this->exportValues();
401 if ($params['minimum_fee']) {
402 $params['minimum_fee'] = CRM_Utils_Rule
::cleanMoney($params['minimum_fee']);
405 $hasRelTypeVal = FALSE;
406 if (!CRM_Utils_System
::isNull($params['relationship_type_id'])) {
407 // To insert relation ids and directions with value separator
408 $relTypeDirs = $params['relationship_type_id'];
409 $relIds = $relDirection = [];
410 foreach ($relTypeDirs as $key => $value) {
411 $relationId = explode('_', $value);
412 if (count($relationId) == 3 &&
413 is_numeric($relationId[0])
415 $relIds[] = $relationId[0];
416 $relDirection[] = $relationId[1] . '_' . $relationId[2];
419 if (!empty($relIds)) {
420 $hasRelTypeVal = TRUE;
421 $params['relationship_type_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relIds);
422 $params['relationship_direction'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relDirection);
425 if (!$hasRelTypeVal) {
426 $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'null';
429 if ($params['duration_unit'] == 'lifetime' &&
430 empty($params['duration_interval'])
432 $params['duration_interval'] = 1;
435 $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
436 foreach ($periods as $period) {
437 if (!empty($params[$period]['M']) && !empty($params[$period]['d'])) {
438 $mon = $params[$period]['M'];
439 $dat = $params[$period]['d'];
440 $mon = ($mon < 10) ?
'0' . $mon : $mon;
441 $dat = ($dat < 10) ?
'0' . $dat : $dat;
442 $params[$period] = $mon . $dat;
444 elseif ($period == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
445 $params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
446 unset($params['month_fixed_period_rollover_day']);
449 $params[$period] = 'null';
455 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
456 $this->_id
, 'weight', 'id'
459 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Member_DAO_MembershipType',
460 $oldWeight, $params['weight']
463 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
464 $params['id'] = $this->_id
;
467 $membershipTypeResult = civicrm_api3('MembershipType', 'create', $params);
468 $membershipTypeName = $membershipTypeResult['values'][$membershipTypeResult['id']]['name'];
470 CRM_Core_Session
::setStatus(ts("The membership type '%1' has been saved.",
471 [1 => $membershipTypeName]
472 ), ts('Saved'), 'success');
473 $session = CRM_Core_Session
::singleton();
474 $buttonName = $this->controller
->getButtonName();
475 if ($buttonName == $this->getButtonName('upload', 'new')) {
476 $session->replaceUserContext(
477 CRM_Utils_System
::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
484 * @param int $previousID
485 * @param int $priceSetId
486 * @param int $membershipTypeId
489 public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
491 $editedFieldParams = [
492 'price_set_id ' => $priceSetId,
493 'name' => $previousID,
496 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
497 if (!empty($editedResults)) {
498 $editedFieldParams = [
499 'price_field_id' => $editedResults['id'],
500 'membership_type_id' => $membershipTypeId,
503 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
504 $optionsIds['option_id'][1] = $editedResults['id'] ??
NULL;