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 // TODO: Add fields here per CRM/Admin/Form/RelationshipType.php.
66 // ... It's not as easy because MembershipType has multiple conditional fields/javascript etc.
67 $this->entityFields
= [];
71 * Deletion message to be assigned to the form.
75 protected $deleteMessage;
78 * Explicitly declare the entity api name.
80 public function getDefaultEntity() {
81 return 'MembershipType';
85 * Set the delete message.
87 * We do this from the constructor in order to do a translation.
89 public function setDeleteMessage() {
90 $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?');
94 * Explicitly declare the form context.
96 public function getDefaultContext() {
101 * Max number of contacts we will display for membership-organisation
103 const MAX_CONTACTS
= 50;
105 public function preProcess() {
106 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, FALSE, 0);
107 $this->_BAOName
= 'CRM_Member_BAO_MembershipType';
108 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
109 $this->assign('action', $this->_action
);
111 $session = CRM_Core_Session
::singleton();
112 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipType', 'reset=1');
113 $session->pushUserContext($url);
115 $this->setPageTitle(ts('Membership Type'));
119 * Set default values for the form. MobileProvider that in edit/view mode
120 * the default values are retrieved from the database
125 public function setDefaultValues() {
126 $defaults = parent
::setDefaultValues();
128 //finding default weight to be put
129 if (!isset($defaults['weight']) ||
(!$defaults['weight'])) {
130 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Member_DAO_MembershipType');
132 //setting default relationshipType
133 if (isset($defaults['relationship_type_id'])) {
134 //$defaults['relationship_type_id'] = $defaults['relationship_type_id'].'_a_b';
135 // Set values for relation type select box
136 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaults['relationship_type_id']);
137 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaults['relationship_direction']);
138 $defaults['relationship_type_id'] = array();
139 foreach ($relTypeIds as $key => $value) {
140 $defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
144 //setting default fixed_period_start_day & fixed_period_rollover_day
145 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
146 foreach ($periods as $per) {
147 if (isset($defaults[$per])) {
148 $date = $defaults[$per];
150 $defaults[$per] = array();
152 $date = ($date < 999) ?
'0' . $date : $date;
153 $defaults[$per]['M'] = substr($date, 0, 2);
154 $defaults[$per]['d'] = substr($date, 2, 3);
157 //special case when only day is rollover and duration is month
158 $defaults['month_fixed_period_rollover_day']['d'] = $date;
167 * Build the form object.
170 * @throws \CRM_Core_Exception
171 * @throws \CiviCRM_API3_Exception
173 public function buildQuickForm() {
174 self
::buildQuickEntityForm();
176 if ($this->_action
& CRM_Core_Action
::DELETE
) {
180 $this->applyFilter('__ALL__', 'trim');
181 $this->addField('name', [], TRUE);
182 $this->addField('description');
183 $this->addField('minimum_fee');
184 $this->addField('duration_unit', [], TRUE);
185 $this->addField('period_type', [], TRUE);
186 $this->addField('is_active');
187 $this->addField('weight');
188 $this->addField('max_related');
190 $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
191 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id
)
193 $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
195 $this->add('text', 'duration_interval', ts('Duration Interval'),
196 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')
199 $props = array('api' => array('params' => array('contact_type' => 'Organization')));
200 $this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
203 $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'),
204 CRM_Core_SelectValues
::date(NULL, 'M d'), FALSE
207 // Add Auto-renew options if we have a payment processor that supports recurring contributions
208 $isAuthorize = FALSE;
210 if (CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('Recurring'))) {
212 $options = CRM_Core_SelectValues
::memberAutoRenew();
215 $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
216 $this->assign('authorize', $isAuthorize);
219 $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
220 CRM_Core_SelectValues
::date(NULL, 'M d'), FALSE
222 $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
223 CRM_Core_SelectValues
::date(NULL, 'd'), FALSE
225 $this->add('select', 'financial_type_id', ts('Financial Type'),
226 array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
), TRUE, array('class' => 'crm-select2')
229 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
230 if (is_array($relTypeInd)) {
233 $memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'),
234 $relTypeInd, FALSE, array('class' => 'crm-select2 huge', 'multiple' => 1));
236 $this->addField('visibility', array('placeholder' => NULL, 'option_url' => NULL));
238 $membershipRecords = FALSE;
239 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
240 $result = civicrm_api3("Membership", "get", array("membership_type_id" => $this->_id
, "options" => array("limit" => 1)));
241 $membershipRecords = ($result["count"] > 0);
242 if ($membershipRecords) {
243 $memberRel->freeze();
247 $this->assign('membershipRecordsExists', $membershipRecords);
249 $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
251 $this->assign('membershipTypeId', $this->_id
);
253 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('deferred_revenue_enabled')) {
254 $deferredFinancialType = CRM_Financial_BAO_FinancialAccount
::getDeferredFinancialType();
255 $this->assign('deferredFinancialType', array_keys($deferredFinancialType));
262 * @param array $params
263 * (ref.) an assoc array of name/value pairs.
266 * mixed true or array of errors
268 public static function formRule($params) {
271 if (!$params['name']) {
272 $errors['name'] = ts('Please enter a membership type name.');
275 if (($params['minimum_fee'] > 0) && !$params['financial_type_id']) {
276 $errors['financial_type_id'] = ts('Please enter the financial Type.');
279 if (empty($params['duration_interval']) and $params['duration_unit'] != 'lifetime') {
280 $errors['duration_interval'] = ts('Please enter a duration interval.');
283 if (in_array(CRM_Utils_Array
::value('auto_renew', $params), array(
287 if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
288 ($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
290 $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.');
294 if ($params['period_type'] == 'fixed' &&
295 $params['duration_unit'] == 'day'
297 $errors['period_type'] = ts('Period type should be Rolling when duration unit is Day');
300 if (($params['period_type'] == 'fixed') &&
301 ($params['duration_unit'] == 'year')
303 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
304 foreach ($periods as $period) {
305 $month = $params[$period]['M'];
306 $date = $params[$period]['d'];
307 if (!$month ||
!$date) {
309 case 'fixed_period_start_day':
310 $errors[$period] = ts('Please enter a valid fixed period start day');
313 case 'fixed_period_rollover_day':
314 $errors[$period] = ts('Please enter a valid fixed period rollover day');
321 if ($params['fixed_period_start_day'] && !empty($params['fixed_period_start_day'])) {
322 $params['fixed_period_start_day']['Y'] = date('Y');
323 if (!CRM_Utils_Rule
::qfDate($params['fixed_period_start_day'])) {
324 $errors['fixed_period_start_day'] = ts('Please enter valid Fixed Period Start Day');
328 if ($params['fixed_period_rollover_day'] && !empty($params['fixed_period_rollover_day'])) {
329 $params['fixed_period_rollover_day']['Y'] = date('Y');
330 if (!CRM_Utils_Rule
::qfDate($params['fixed_period_rollover_day'])) {
331 $errors['fixed_period_rollover_day'] = ts('Please enter valid Fixed Period Rollover Day');
335 return empty($errors) ?
TRUE : $errors;
339 * Process the form submission.
343 public function postProcess() {
344 if ($this->_action
& CRM_Core_Action
::DELETE
) {
346 CRM_Member_BAO_MembershipType
::del($this->_id
);
348 catch (CRM_Core_Exception
$e) {
349 CRM_Core_Error
::statusBounce($e->getMessage(), NULL, ts('Membership Type Not Deleted'));
351 CRM_Core_Session
::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
354 $params = $this->exportValues();
356 if ($params['minimum_fee']) {
357 $params['minimum_fee'] = CRM_Utils_Rule
::cleanMoney($params['minimum_fee']);
360 $hasRelTypeVal = FALSE;
361 if (!CRM_Utils_System
::isNull($params['relationship_type_id'])) {
362 // To insert relation ids and directions with value separator
363 $relTypeDirs = $params['relationship_type_id'];
364 $relIds = $relDirection = array();
365 foreach ($relTypeDirs as $key => $value) {
366 $relationId = explode('_', $value);
367 if (count($relationId) == 3 &&
368 is_numeric($relationId[0])
370 $relIds[] = $relationId[0];
371 $relDirection[] = $relationId[1] . '_' . $relationId[2];
374 if (!empty($relIds)) {
375 $hasRelTypeVal = TRUE;
376 $params['relationship_type_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relIds);
377 $params['relationship_direction'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relDirection);
380 if (!$hasRelTypeVal) {
381 $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'null';
384 if ($params['duration_unit'] == 'lifetime' &&
385 empty($params['duration_interval'])
387 $params['duration_interval'] = 1;
390 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
391 foreach ($periods as $period) {
392 if (!empty($params[$period]['M']) && !empty($params[$period]['d'])) {
393 $mon = $params[$period]['M'];
394 $dat = $params[$period]['d'];
395 $mon = ($mon < 10) ?
'0' . $mon : $mon;
396 $dat = ($dat < 10) ?
'0' . $dat : $dat;
397 $params[$period] = $mon . $dat;
399 elseif ($period == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
400 $params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
401 unset($params['month_fixed_period_rollover_day']);
404 $params[$period] = 'null';
410 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
411 $this->_id
, 'weight', 'id'
414 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Member_DAO_MembershipType',
415 $oldWeight, $params['weight']
418 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
419 $params['id'] = $this->_id
;
422 $membershipTypeResult = civicrm_api3('MembershipType', 'create', $params);
423 $membershipTypeName = $membershipTypeResult['values'][$membershipTypeResult['id']]['name'];
425 CRM_Core_Session
::setStatus(ts("The membership type '%1' has been saved.",
426 array(1 => $membershipTypeName)
427 ), ts('Saved'), 'success');
428 $session = CRM_Core_Session
::singleton();
429 $buttonName = $this->controller
->getButtonName();
430 if ($buttonName == $this->getButtonName('upload', 'new')) {
431 $session->replaceUserContext(
432 CRM_Utils_System
::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
439 * @param int $previousID
440 * @param int $priceSetId
441 * @param int $membershipTypeId
444 public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
446 $editedFieldParams = array(
447 'price_set_id ' => $priceSetId,
448 'name' => $previousID,
450 $editedResults = array();
451 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
452 if (!empty($editedResults)) {
453 $editedFieldParams = array(
454 'price_field_id' => $editedResults['id'],
455 'membership_type_id' => $membershipTypeId,
457 $editedResults = array();
458 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
459 $optionsIds['option_id'][1] = CRM_Utils_Array
::value('id', $editedResults);