3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
36 * This class generates form components for Membership Type
39 class CRM_Member_Form_MembershipType
extends CRM_Member_Form_MembershipConfig
{
41 use CRM_Core_Form_EntityFormTrait
;
44 * Fields for the entity to be assigned to the template.
46 * Fields may have keys
47 * - name (required to show in tpl from the array)
48 * - description (optional, will appear below the field)
49 * - not-auto-addable - this class will not attempt to add the field using addField.
50 * (this will be automatically set if the field does not have html in it's metadata
51 * or is not a core field on the form's entity).
52 * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
53 * - template - use a field specific template to render this field
55 * - is_freeze (field should be frozen).
59 protected $entityFields = [];
62 * Set entity fields to be assigned to the form.
64 protected function setEntityFields() {
65 $this->entityFields
= [
69 'description' => ts("e.g. 'Student', 'Senior', 'Honor Society'..."),
72 'name' => 'description',
73 'description' => ts("Description of this membership type for internal use. May include eligibility, benefits, terms, etc."),
75 'member_of_contact_id' => [
76 'name' => 'member_of_contact_id',
77 '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."),
80 'name' => 'minimum_fee',
81 '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.'),
82 'formatter' => 'crmMoney',
84 'financial_type_id' => [
85 'name' => 'financial_type_id',
86 '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.'),
89 'name' => 'auto_renew',
90 'options' => CRM_Core_SelectValues
::memberAutoRenew(),
91 '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.'),
93 'duration_interval' => [
94 'name' => 'duration_interval',
97 'name' => 'duration_unit',
98 'description' => ts('Duration of this membership (e.g. 30 days, 2 months, 5 years, 1 lifetime)'),
101 'name' => 'period_type',
102 'description' => ts("Select 'rolling' if membership periods begin at date of signup. Select 'fixed' if membership periods begin on a set calendar date."),
103 'help' => ['id' => 'period-type', 'file' => "CRM/Member/Page/MembershipType.hlp"],
105 'fixed_period_start_day' => [
106 'name' => 'fixed_period_start_day',
107 '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."),
109 'fixed_period_rollover_day' => [
110 'name' => 'fixed_period_rollover_day',
111 '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.'),
113 'relationship_type_id' => [
114 'name' => 'relationship_type_id',
117 'name' => 'max_related',
118 'description' => ts('Maximum number of related memberships (leave blank for unlimited).'),
121 'name' => 'visibility',
122 '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')."),
128 'name' => 'is_active',
132 if (!CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('Recurring'))) {
133 $this->entityFields
['auto_renew']['not-auto-addable'] = TRUE;
134 $this->entityFields
['auto_renew']['documentation_link'] = ['page' => 'user/contributions/payment-processors'];
139 * Deletion message to be assigned to the form.
143 protected $deleteMessage;
146 * Explicitly declare the entity api name.
148 public function getDefaultEntity() {
149 return 'MembershipType';
153 * Set the delete message.
155 * We do this from the constructor in order to do a translation.
157 public function setDeleteMessage() {
158 $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?');
162 * Explicitly declare the form context.
164 public function getDefaultContext() {
169 * Max number of contacts we will display for membership-organisation
171 const MAX_CONTACTS
= 50;
173 public function preProcess() {
174 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, FALSE, 0);
175 $this->_BAOName
= 'CRM_Member_BAO_MembershipType';
176 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
177 $this->assign('action', $this->_action
);
179 $session = CRM_Core_Session
::singleton();
180 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipType', 'reset=1');
181 $session->pushUserContext($url);
183 $this->setPageTitle(ts('Membership Type'));
187 * Set default values for the form. MobileProvider that in edit/view mode
188 * the default values are retrieved from the database
193 public function setDefaultValues() {
194 $defaults = parent
::setDefaultValues();
196 //finding default weight to be put
197 if (!isset($defaults['weight']) ||
(!$defaults['weight'])) {
198 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Member_DAO_MembershipType');
200 //setting default relationshipType
201 if (isset($defaults['relationship_type_id'])) {
202 //$defaults['relationship_type_id'] = $defaults['relationship_type_id'].'_a_b';
203 // Set values for relation type select box
204 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaults['relationship_type_id']);
205 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaults['relationship_direction']);
206 $defaults['relationship_type_id'] = array();
207 foreach ($relTypeIds as $key => $value) {
208 $defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
212 //setting default fixed_period_start_day & fixed_period_rollover_day
213 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
214 foreach ($periods as $per) {
215 if (isset($defaults[$per])) {
216 $date = $defaults[$per];
218 $defaults[$per] = array();
220 $date = ($date < 999) ?
'0' . $date : $date;
221 $defaults[$per]['M'] = substr($date, 0, 2);
222 $defaults[$per]['d'] = substr($date, 2, 3);
225 //special case when only day is rollover and duration is month
226 $defaults['month_fixed_period_rollover_day']['d'] = $date;
235 * Build the form object.
238 * @throws \CRM_Core_Exception
239 * @throws \CiviCRM_API3_Exception
241 public function buildQuickForm() {
242 self
::buildQuickEntityForm();
244 if ($this->_action
& CRM_Core_Action
::DELETE
) {
247 // This is a temporary variable as we work towards moving over towards using the EntityField.tpl.
248 // Fields in this array have been tested & in the tpl have been switched over to metadata.
249 // Note this kinda 'works from the top' - ie. once we hit a field that needs some thought we need
250 // to stop & make that one work.
251 $this->assign('tpl_standardised_fields', ['name', 'description', 'member_of_contact_id', 'minimum_fee']);
253 $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
254 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id
)
256 $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
258 $props = array('api' => array('params' => array('contact_type' => 'Organization')));
259 $this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
262 $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'),
263 CRM_Core_SelectValues
::date(NULL, 'M d'), FALSE
266 // Add Auto-renew options if we have a payment processor that supports recurring contributions
267 $isAuthorize = FALSE;
269 if (CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('Recurring'))) {
271 $options = CRM_Core_SelectValues
::memberAutoRenew();
274 $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
275 $this->assign('authorize', $isAuthorize);
278 $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
279 CRM_Core_SelectValues
::date(NULL, 'M d'), FALSE
281 $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
282 CRM_Core_SelectValues
::date(NULL, 'd'), FALSE
284 $this->add('select', 'financial_type_id', ts('Financial Type'),
285 array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
), TRUE, array('class' => 'crm-select2')
288 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
289 if (is_array($relTypeInd)) {
292 $memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'),
293 $relTypeInd, FALSE, array('class' => 'crm-select2 huge', 'multiple' => 1));
295 $this->addField('visibility', array('placeholder' => NULL, 'option_url' => NULL));
297 $membershipRecords = FALSE;
298 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
299 $result = civicrm_api3("Membership", "get", array("membership_type_id" => $this->_id
, "options" => array("limit" => 1)));
300 $membershipRecords = ($result["count"] > 0);
301 if ($membershipRecords) {
302 $memberRel->freeze();
306 $this->assign('membershipRecordsExists', $membershipRecords);
308 $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
310 $this->assign('membershipTypeId', $this->_id
);
312 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('deferred_revenue_enabled')) {
313 $deferredFinancialType = CRM_Financial_BAO_FinancialAccount
::getDeferredFinancialType();
314 $this->assign('deferredFinancialType', array_keys($deferredFinancialType));
321 * @param array $params
322 * (ref.) an assoc array of name/value pairs.
325 * mixed true or array of errors
327 public static function formRule($params) {
330 if (!$params['name']) {
331 $errors['name'] = ts('Please enter a membership type name.');
334 if (($params['minimum_fee'] > 0) && !$params['financial_type_id']) {
335 $errors['financial_type_id'] = ts('Please enter the financial Type.');
338 if (empty($params['duration_interval']) and $params['duration_unit'] != 'lifetime') {
339 $errors['duration_interval'] = ts('Please enter a duration interval.');
342 if (in_array(CRM_Utils_Array
::value('auto_renew', $params), array(
346 if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
347 ($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
349 $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.');
353 if ($params['period_type'] == 'fixed' &&
354 $params['duration_unit'] == 'day'
356 $errors['period_type'] = ts('Period type should be Rolling when duration unit is Day');
359 if (($params['period_type'] == 'fixed') &&
360 ($params['duration_unit'] == 'year')
362 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
363 foreach ($periods as $period) {
364 $month = $params[$period]['M'];
365 $date = $params[$period]['d'];
366 if (!$month ||
!$date) {
368 case 'fixed_period_start_day':
369 $errors[$period] = ts('Please enter a valid fixed period start day');
372 case 'fixed_period_rollover_day':
373 $errors[$period] = ts('Please enter a valid fixed period rollover day');
380 if ($params['fixed_period_start_day'] && !empty($params['fixed_period_start_day'])) {
381 $params['fixed_period_start_day']['Y'] = date('Y');
382 if (!CRM_Utils_Rule
::qfDate($params['fixed_period_start_day'])) {
383 $errors['fixed_period_start_day'] = ts('Please enter valid Fixed Period Start Day');
387 if ($params['fixed_period_rollover_day'] && !empty($params['fixed_period_rollover_day'])) {
388 $params['fixed_period_rollover_day']['Y'] = date('Y');
389 if (!CRM_Utils_Rule
::qfDate($params['fixed_period_rollover_day'])) {
390 $errors['fixed_period_rollover_day'] = ts('Please enter valid Fixed Period Rollover Day');
394 return empty($errors) ?
TRUE : $errors;
398 * Process the form submission.
402 public function postProcess() {
403 if ($this->_action
& CRM_Core_Action
::DELETE
) {
405 CRM_Member_BAO_MembershipType
::del($this->_id
);
407 catch (CRM_Core_Exception
$e) {
408 CRM_Core_Error
::statusBounce($e->getMessage(), NULL, ts('Membership Type Not Deleted'));
410 CRM_Core_Session
::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
413 $params = $this->exportValues();
415 if ($params['minimum_fee']) {
416 $params['minimum_fee'] = CRM_Utils_Rule
::cleanMoney($params['minimum_fee']);
419 $hasRelTypeVal = FALSE;
420 if (!CRM_Utils_System
::isNull($params['relationship_type_id'])) {
421 // To insert relation ids and directions with value separator
422 $relTypeDirs = $params['relationship_type_id'];
423 $relIds = $relDirection = array();
424 foreach ($relTypeDirs as $key => $value) {
425 $relationId = explode('_', $value);
426 if (count($relationId) == 3 &&
427 is_numeric($relationId[0])
429 $relIds[] = $relationId[0];
430 $relDirection[] = $relationId[1] . '_' . $relationId[2];
433 if (!empty($relIds)) {
434 $hasRelTypeVal = TRUE;
435 $params['relationship_type_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relIds);
436 $params['relationship_direction'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relDirection);
439 if (!$hasRelTypeVal) {
440 $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'null';
443 if ($params['duration_unit'] == 'lifetime' &&
444 empty($params['duration_interval'])
446 $params['duration_interval'] = 1;
449 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
450 foreach ($periods as $period) {
451 if (!empty($params[$period]['M']) && !empty($params[$period]['d'])) {
452 $mon = $params[$period]['M'];
453 $dat = $params[$period]['d'];
454 $mon = ($mon < 10) ?
'0' . $mon : $mon;
455 $dat = ($dat < 10) ?
'0' . $dat : $dat;
456 $params[$period] = $mon . $dat;
458 elseif ($period == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
459 $params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
460 unset($params['month_fixed_period_rollover_day']);
463 $params[$period] = 'null';
469 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
470 $this->_id
, 'weight', 'id'
473 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Member_DAO_MembershipType',
474 $oldWeight, $params['weight']
477 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
478 $params['id'] = $this->_id
;
481 $membershipTypeResult = civicrm_api3('MembershipType', 'create', $params);
482 $membershipTypeName = $membershipTypeResult['values'][$membershipTypeResult['id']]['name'];
484 CRM_Core_Session
::setStatus(ts("The membership type '%1' has been saved.",
485 array(1 => $membershipTypeName)
486 ), ts('Saved'), 'success');
487 $session = CRM_Core_Session
::singleton();
488 $buttonName = $this->controller
->getButtonName();
489 if ($buttonName == $this->getButtonName('upload', 'new')) {
490 $session->replaceUserContext(
491 CRM_Utils_System
::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
498 * @param int $previousID
499 * @param int $priceSetId
500 * @param int $membershipTypeId
503 public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
505 $editedFieldParams = array(
506 'price_set_id ' => $priceSetId,
507 'name' => $previousID,
509 $editedResults = array();
510 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
511 if (!empty($editedResults)) {
512 $editedFieldParams = array(
513 'price_field_id' => $editedResults['id'],
514 'membership_type_id' => $membershipTypeId,
516 $editedResults = array();
517 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
518 $optionsIds['option_id'][1] = CRM_Utils_Array
::value('id', $editedResults);