Example #1
0
    /**
     * Build the form object.
     *
     * @return void
     */
    public function buildQuickForm()
    {
        if ($this->_cdType) {
            return CRM_Custom_Form_CustomData::buildQuickForm($this);
        }
        $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
        $config = CRM_Core_Config::singleton();
        $this->assign('currency', $config->defaultCurrencySymbol);
        $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
        $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
        if (isset($invoicing)) {
            $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
        }
        // build price set form.
        $buildPriceSet = FALSE;
        if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
            if (!empty($_POST['price_set_id'])) {
                $buildPriceSet = TRUE;
            }
            $getOnlyPriceSetElements = TRUE;
            if (!$this->_priceSetId) {
                $this->_priceSetId = $_POST['price_set_id'];
                $getOnlyPriceSetElements = FALSE;
            }
            $this->set('priceSetId', $this->_priceSetId);
            CRM_Price_BAO_PriceSet::buildPriceSet($this);
            $optionsMembershipTypes = array();
            foreach ($this->_priceSet['fields'] as $pField) {
                if (empty($pField['options'])) {
                    continue;
                }
                foreach ($pField['options'] as $opId => $opValues) {
                    $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
                }
            }
            $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
            $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
            $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
            // get only price set form elements.
            if ($getOnlyPriceSetElements) {
                return;
            }
        }
        // use to build form during form rule.
        $this->assign('buildPriceSet', $buildPriceSet);
        if ($this->_action & CRM_Core_Action::ADD) {
            $buildPriceSet = FALSE;
            $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
            if (!empty($priceSets)) {
                $buildPriceSet = TRUE;
            }
            if ($buildPriceSet) {
                $this->add('select', 'price_set_id', ts('Choose price set'), array('' => ts('Choose price set')) + $priceSets, NULL, array('onchange' => "buildAmount( this.value );"));
            }
            $this->assign('hasPriceSets', $buildPriceSet);
        }
        //need to assign custom data type and subtype to the template
        $this->assign('customDataType', 'Membership');
        $this->assign('customDataSubType', $this->_memType);
        $this->assign('entityID', $this->_id);
        if ($this->_action & CRM_Core_Action::DELETE) {
            $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '         ', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
            return;
        }
        if ($this->_context == 'standalone') {
            $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
        }
        $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
        $dao = new CRM_Member_DAO_MembershipType();
        $dao->domain_id = CRM_Core_Config::domainID();
        $dao->find();
        // retrieve all memberships
        $allMemberships = CRM_Member_BAO_Membership::buildMembershipTypeValues($this);
        $allMembershipInfo = $membershipType = array();
        foreach ($allMemberships as $key => $values) {
            if (!empty($values['is_active'])) {
                $membershipType[$key] = CRM_Utils_Array::value('name', $values);
                if ($this->_mode && empty($values['minimum_fee'])) {
                    continue;
                } else {
                    $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
                    if (empty($selMemTypeOrg[$memberOfContactId])) {
                        $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $memberOfContactId, 'display_name', 'id');
                        $selOrgMemType[$memberOfContactId][0] = ts('- select -');
                    }
                    if (empty($selOrgMemType[$memberOfContactId][$key])) {
                        $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
                    }
                }
                // build membership info array, which is used when membership type is selected to:
                // - set the payment information block
                // - set the max related block
                $allMembershipInfo[$key] = array('financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values), 'total_amount' => CRM_Utils_Money::format($values['minimum_fee'], NULL, '%a'), 'total_amount_numeric' => CRM_Utils_Array::value('minimum_fee', $values), 'auto_renew' => CRM_Utils_Array::value('auto_renew', $values), 'has_related' => isset($values['relationship_type_id']), 'max_related' => CRM_Utils_Array::value('max_related', $values));
            }
        }
        $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
        // show organization by default, if only one organization in
        // the list
        if (count($selMemTypeOrg) == 2) {
            unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
        }
        //sort membership organization and type, CRM-6099
        natcasesort($selMemTypeOrg);
        foreach ($selOrgMemType as $index => $orgMembershipType) {
            natcasesort($orgMembershipType);
            $selOrgMemType[$index] = $orgMembershipType;
        }
        $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
        //build the form for auto renew.
        $recurProcessor = $autoRenew = array();
        if ($this->_mode || $this->_action & CRM_Core_Action::UPDATE) {
            $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'), NULL, array('onclick' => "buildReceiptANDNotice( );"));
            if ($this->_mode) {
                //get the valid recurring processors.
                $test = strtolower($this->_mode) == 'test' ? TRUE : FALSE;
                $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, $test, 'is_recur = 1');
                $recurProcessor = array_intersect_key($this->_processors, $recurring);
                $autoRenew = array();
                if (!empty($recurProcessor)) {
                    if (!empty($membershipType)) {
                        $sql = '
SELECT  id,
        auto_renew,
        duration_unit,
        duration_interval
 FROM   civicrm_membership_type
WHERE   id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
                        $recurMembershipTypes = CRM_Core_DAO::executeQuery($sql);
                        while ($recurMembershipTypes->fetch()) {
                            $autoRenew[$recurMembershipTypes->id] = $recurMembershipTypes->auto_renew;
                            foreach (array('id', 'auto_renew', 'duration_unit', 'duration_interval') as $fld) {
                                $this->_recurMembershipTypes[$recurMembershipTypes->id][$fld] = $recurMembershipTypes->{$fld};
                            }
                        }
                    }
                    $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );");
                }
            }
        }
        $allowAutoRenew = FALSE;
        if ($this->_mode && !empty($recurProcessor)) {
            $allowAutoRenew = TRUE;
        }
        $this->assign('allowAutoRenew', $allowAutoRenew);
        $this->assign('autoRenewOptions', json_encode($autoRenew));
        $this->assign('recurProcessor', json_encode($recurProcessor));
        // for max_related: a little JS to show/hide & set default value
        $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
        $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related'));
        $sel =& $this->addElement('hierselect', 'membership_type_id', ts('Membership Organization and Type'), $memTypeJs);
        $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
        $elements = array();
        if ($sel) {
            $elements[] = $sel;
        }
        $this->applyFilter('__ALL__', 'trim');
        if ($this->_action & CRM_Core_Action::ADD) {
            $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
        }
        $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
        $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
        $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
        if ($endDate) {
            $elements[] = $endDate;
        }
        $this->add('text', 'source', ts('Source'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source'));
        //CRM-7362 --add campaigns.
        $campaignId = NULL;
        if ($this->_id) {
            $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
        }
        CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
        if (!$this->_mode) {
            $this->add('select', 'status_id', ts('Membership Status'), array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'));
            $statusOverride = $this->addElement('checkbox', 'is_override', ts('Status Override?'), NULL, array('onClick' => 'showHideMemberStatus()'));
            if ($statusOverride) {
                $elements[] = $statusOverride;
            }
            $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
            $this->add('text', 'total_amount', ts('Amount'));
            $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
            $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
            $this->add('select', 'payment_instrument_id', ts('Paid By'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
            $this->add('text', 'trxn_id', ts('Transaction ID'));
            $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id'));
            $allowStatuses = array();
            $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
            if ($this->_onlinePendingContributionId) {
                $statusNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
                foreach ($statusNames as $val => $name) {
                    if (in_array($name, array('In Progress', 'Overdue'))) {
                        continue;
                    }
                    $allowStatuses[$val] = $statuses[$val];
                }
            } else {
                $allowStatuses = $statuses;
            }
            $this->add('select', 'contribution_status_id', ts('Payment Status'), $allowStatuses);
            $this->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
        } else {
            //add field for amount to allow an amount to be entered that differs from minimum
            $this->add('text', 'total_amount', ts('Amount'));
        }
        $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType());
        //CRM-10223 - allow contribution to be recorded against different contact
        // causes a conflict in standalone mode so skip in standalone for now
        $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
        $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
        $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
        $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL, array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);"));
        $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
        $this->add('textarea', 'receipt_text_signup', ts('Receipt Message'));
        // Retrieve the name and email of the contact - this will be the TO for receipt email
        if ($this->_contactID) {
            list($this->_memberDisplayName, $this->_memberEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
            $this->assign('emailExists', $this->_memberEmail);
            $this->assign('displayName', $this->_memberDisplayName);
        }
        $isRecur = FALSE;
        if ($this->_action & CRM_Core_Action::UPDATE) {
            $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id');
            if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
                $isRecur = TRUE;
                if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
                    $this->assign('cancelAutoRenew', CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}"));
                }
                foreach ($elements as $elem) {
                    $elem->freeze();
                }
            }
        }
        $this->assign('isRecur', $isRecur);
        $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
        $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend');
        $this->assign('outBound_option', $mailingInfo['outBound_option']);
        parent::buildQuickForm();
    }
Example #2
0
 /**
  * Global validation rules for the form.
  *
  * @param array $fields
  *   Posted values of the form.
  *
  * @param $files
  * @param CRM_Core_Form $form
  *
  * @return array
  *   if errors then list of errors to be posted back to the form,
  *                  true otherwise
  */
 public static function formRule($fields, $files, $form)
 {
     // all option fields are of type "money"
     $errors = array();
     /** Check the option values entered
      *  Appropriate values are required for the selected datatype
      *  Incomplete row checking is also required.
      */
     if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['price'] == NULL) {
         $errors['price'] = ts('Price is a required field');
     }
     if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['financial_type_id'] == '') {
         $errors['financial_type_id'] = ts('Financial Type is a required field');
     }
     //avoid the same price field label in Within PriceSet
     $priceFieldLabel = new CRM_Price_DAO_PriceField();
     $priceFieldLabel->label = $fields['label'];
     $priceFieldLabel->price_set_id = $form->_sid;
     $dupeLabel = FALSE;
     if ($priceFieldLabel->find(TRUE) && $form->_fid != $priceFieldLabel->id) {
         $dupeLabel = TRUE;
     }
     if ($dupeLabel) {
         $errors['label'] = ts('Name already exists in Database.');
     }
     if (is_numeric(CRM_Utils_Array::value('count', $fields)) && CRM_Utils_Array::value('count', $fields) == 0 && CRM_Utils_Array::value('html_type', $fields) == 'Text') {
         $errors['count'] = ts('Participant Count must be greater than zero.');
     }
     if ($form->_action & CRM_Core_Action::ADD) {
         if ($fields['html_type'] != 'Text') {
             $countemptyrows = 0;
             $_flagOption = $_rowError = 0;
             $_showHide = new CRM_Core_ShowHideBlocks('', '');
             for ($index = 1; $index <= self::NUM_OPTION; $index++) {
                 $noLabel = $noAmount = $noWeight = 1;
                 if (!empty($fields['option_label'][$index])) {
                     $noLabel = 0;
                     $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index], $fields['option_label']);
                     if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) {
                         $errors["option_label[{$index}]"] = ts('Duplicate label value');
                         $_flagOption = 1;
                     }
                 }
                 if ($form->_useForMember) {
                     if (!empty($fields['membership_type_id'][$index])) {
                         $memTypesIDS[] = $fields['membership_type_id'][$index];
                     }
                 }
                 // allow for 0 value.
                 if (!empty($fields['option_amount'][$index]) || strlen($fields['option_amount'][$index]) > 0) {
                     $noAmount = 0;
                 }
                 if (!empty($fields['option_weight'][$index])) {
                     $noWeight = 0;
                     $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index], $fields['option_weight']);
                     if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) {
                         $errors["option_weight[{$index}]"] = ts('Duplicate weight value');
                         $_flagOption = 1;
                     }
                 }
                 if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') {
                     $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.');
                 }
                 if ($noLabel && !$noAmount) {
                     $errors["option_label[{$index}]"] = ts('Label cannot be empty.');
                     $_flagOption = 1;
                 }
                 if (!$noLabel && $noAmount) {
                     $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.');
                     $_flagOption = 1;
                 }
                 if ($noLabel && $noAmount) {
                     $countemptyrows++;
                     $_emptyRow = 1;
                 } elseif (!empty($fields['option_max_value'][$index]) && !empty($fields['option_count'][$index]) && $fields['option_count'][$index] > $fields['option_max_value'][$index]) {
                     $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.');
                     $_flagOption = 1;
                 }
                 $showBlocks = 'optionField_' . $index;
                 if ($_flagOption) {
                     $_showHide->addShow($showBlocks);
                     $_rowError = 1;
                 }
                 if (!empty($_emptyRow)) {
                     $_showHide->addHide($showBlocks);
                 } else {
                     $_showHide->addShow($showBlocks);
                 }
                 if ($index == self::NUM_OPTION) {
                     $hideBlock = 'additionalOption';
                     $_showHide->addHide($hideBlock);
                 }
                 $_flagOption = $_emptyRow = 0;
             }
             if (!empty($memTypesIDS)) {
                 // check for checkboxes allowing user to select multiple memberships from same membership organization
                 if ($fields['html_type'] == 'CheckBox') {
                     $foundDuplicate = FALSE;
                     $orgIds = array();
                     foreach ($memTypesIDS as $key => $val) {
                         $org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val);
                         if (in_array($org[$val], $orgIds)) {
                             $foundDuplicate = TRUE;
                             break;
                         }
                         $orgIds[$val] = $org[$val];
                     }
                     if ($foundDuplicate) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity.');
                     }
                 }
                 // CRM-10390 - Only one price field in a set can include auto-renew membership options
                 $foundAutorenew = FALSE;
                 foreach ($memTypesIDS as $key => $val) {
                     // see if any price field option values in this price field are for memberships with autorenew
                     $memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($val);
                     if (!empty($memTypeDetails['auto_renew'])) {
                         $foundAutorenew = TRUE;
                         break;
                     }
                 }
                 if ($foundAutorenew) {
                     // if so, check for other fields in this price set which also have auto-renew membership options
                     $otherFieldAutorenew = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_sid);
                     if ($otherFieldAutorenew) {
                         $errors['_qf_default'] = ts('You can include auto-renew membership choices for only one price field in a price set. Another field in this set already contains one or more auto-renew membership options.');
                     }
                 }
             }
             $_showHide->addToTemplate();
             if ($countemptyrows == 15) {
                 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
                 $_flagOption = 1;
             }
         } elseif (!empty($fields['max_value']) && !empty($fields['count']) && $fields['count'] > $fields['max_value']) {
             $errors['max_value'] = ts('Participant count can not be greater than max participants.');
         }
         // do not process if no option rows were submitted
         if (empty($fields['option_amount']) && empty($fields['option_label'])) {
             return TRUE;
         }
         if (empty($fields['option_name'])) {
             $fields['option_amount'] = array();
         }
         if (empty($fields['option_label'])) {
             $fields['option_label'] = array();
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
 /**
  * Build Membership  Block in Contribution Pages.
  *
  * @param int $cid
  *   Contact checked for having a current membership for a particular membership.
  * @param bool $isContributionMainPage
  *   Is this the main page? If so add form input fields.
  *   (or better yet don't have this functionality in a function shared with forms that don't share it).
  * @param int $selectedMembershipTypeID
  *   Selected membership id.
  * @param bool $thankPage
  *   Thank you page.
  * @param null $isTest
  *
  * @return bool
  *   Is this a separate membership payment
  */
 protected function buildMembershipBlock($cid, $isContributionMainPage = FALSE, $selectedMembershipTypeID = NULL, $thankPage = FALSE, $isTest = NULL)
 {
     $separateMembershipPayment = FALSE;
     if ($this->_membershipBlock) {
         $this->_currentMemberships = array();
         $membershipTypeIds = $membershipTypes = $radio = array();
         $membershipPriceset = !empty($this->_priceSetId) && $this->_useForMember ? TRUE : FALSE;
         $allowAutoRenewMembership = $autoRenewOption = FALSE;
         $autoRenewMembershipTypeOptions = array();
         $separateMembershipPayment = CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock);
         if ($membershipPriceset) {
             foreach ($this->_priceSet['fields'] as $pField) {
                 if (empty($pField['options'])) {
                     continue;
                 }
                 foreach ($pField['options'] as $opId => $opValues) {
                     if (empty($opValues['membership_type_id'])) {
                         continue;
                     }
                     $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
                 }
             }
         } elseif (!empty($this->_membershipBlock['membership_types'])) {
             $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
         }
         if (!empty($membershipTypeIds)) {
             //set status message if wrong membershipType is included in membershipBlock
             if (isset($this->_mid) && !$membershipPriceset) {
                 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
                 if (!in_array($membershipTypeID, $membershipTypeIds)) {
                     CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
                 }
             }
             $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
             $this->_membershipTypeValues = $membershipTypeValues;
             $endDate = NULL;
             foreach ($membershipTypeIds as $value) {
                 $memType = $membershipTypeValues[$value];
                 if ($selectedMembershipTypeID != NULL) {
                     if ($memType['id'] == $selectedMembershipTypeID) {
                         $this->assign('minimum_fee', CRM_Utils_Array::value('minimum_fee', $memType));
                         $this->assign('membership_name', $memType['name']);
                         if (!$thankPage && $cid) {
                             $membership = new CRM_Member_DAO_Membership();
                             $membership->contact_id = $cid;
                             $membership->membership_type_id = $memType['id'];
                             if ($membership->find(TRUE)) {
                                 $this->assign('renewal_mode', TRUE);
                                 $memType['current_membership'] = $membership->end_date;
                                 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
                             }
                         }
                         $membershipTypes[] = $memType;
                     }
                 } elseif ($memType['is_active']) {
                     $javascriptMethod = NULL;
                     $allowAutoRenewOpt = (int) $memType['auto_renew'];
                     if (is_array($this->_paymentProcessors)) {
                         foreach ($this->_paymentProcessors as $id => $val) {
                             if (!$val['is_recur']) {
                                 $allowAutoRenewOpt = 0;
                                 continue;
                             }
                         }
                     }
                     $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
                     $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array::value($value, CRM_Utils_Array::value('auto_renew', $this->_membershipBlock));
                     if ($allowAutoRenewOpt) {
                         $allowAutoRenewMembership = TRUE;
                     }
                     //add membership type.
                     $radio[$memType['id']] = $this->createElement('radio', NULL, NULL, NULL, $memType['id'], $javascriptMethod);
                     if ($cid) {
                         $membership = new CRM_Member_DAO_Membership();
                         $membership->contact_id = $cid;
                         $membership->membership_type_id = $memType['id'];
                         //show current membership, skip pending and cancelled membership records,
                         //because we take first membership record id for renewal
                         $membership->whereAdd('status_id != 5 AND status_id !=6');
                         if (!is_null($isTest)) {
                             $membership->is_test = $isTest;
                         }
                         //CRM-4297
                         $membership->orderBy('end_date DESC');
                         if ($membership->find(TRUE)) {
                             if (!$membership->end_date) {
                                 unset($radio[$memType['id']]);
                                 $this->assign('islifetime', TRUE);
                                 continue;
                             }
                             $this->assign('renewal_mode', TRUE);
                             $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
                             $memType['current_membership'] = $membership->end_date;
                             if (!$endDate) {
                                 $endDate = $memType['current_membership'];
                                 $this->_defaultMemTypeId = $memType['id'];
                             }
                             if ($memType['current_membership'] < $endDate) {
                                 $endDate = $memType['current_membership'];
                                 $this->_defaultMemTypeId = $memType['id'];
                             }
                         }
                     }
                     $membershipTypes[] = $memType;
                 }
             }
         }
         $this->assign('membershipBlock', $this->_membershipBlock);
         $this->assign('showRadio', $isContributionMainPage);
         $this->assign('membershipTypes', $membershipTypes);
         $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
         $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
         //give preference to user submitted auto_renew value.
         $takeUserSubmittedAutoRenew = !empty($_POST) || $this->isSubmitted() ? TRUE : FALSE;
         $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
         if ($isContributionMainPage) {
             if (!$membershipPriceset) {
                 if (!$this->_membershipBlock['is_required']) {
                     $this->assign('showRadioNoThanks', TRUE);
                     $radio[''] = $this->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
                     $this->addGroup($radio, 'selectMembership', NULL);
                 } elseif ($this->_membershipBlock['is_required'] && count($radio) == 1) {
                     $temp = array_keys($radio);
                     $this->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
                     $this->assign('singleMembership', TRUE);
                     $this->assign('showRadio', FALSE);
                 } else {
                     $this->addGroup($radio, 'selectMembership', NULL);
                 }
                 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
             } else {
                 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId);
                 $this->assign('autoRenewOption', $autoRenewOption);
             }
             if (!$this->_values['is_pay_later'] && is_array($this->_paymentProcessors) && ($allowAutoRenewMembership || $autoRenewOption)) {
                 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
             }
         }
     }
     return $separateMembershipPayment;
 }
Example #4
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
     $this->assign('currency', CRM_Core_Config::singleton()->defaultCurrencySymbol);
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     if (isset($invoicing)) {
         $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
     }
     // build price set form.
     $buildPriceSet = FALSE;
     if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
         if (!empty($_POST['price_set_id'])) {
             $buildPriceSet = TRUE;
         }
         $getOnlyPriceSetElements = TRUE;
         if (!$this->_priceSetId) {
             $this->_priceSetId = $_POST['price_set_id'];
             $getOnlyPriceSetElements = FALSE;
         }
         $this->set('priceSetId', $this->_priceSetId);
         CRM_Price_BAO_PriceSet::buildPriceSet($this);
         $optionsMembershipTypes = array();
         foreach ($this->_priceSet['fields'] as $pField) {
             if (empty($pField['options'])) {
                 continue;
             }
             foreach ($pField['options'] as $opId => $opValues) {
                 $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
             }
         }
         $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
         $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
         $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
         // get only price set form elements.
         if ($getOnlyPriceSetElements) {
             return;
         }
     }
     // use to build form during form rule.
     $this->assign('buildPriceSet', $buildPriceSet);
     if ($this->_action & CRM_Core_Action::ADD) {
         $buildPriceSet = FALSE;
         $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
         if (!empty($priceSets)) {
             $buildPriceSet = TRUE;
         }
         if ($buildPriceSet) {
             $this->add('select', 'price_set_id', ts('Choose price set'), array('' => ts('Choose price set')) + $priceSets, NULL, array('onchange' => "buildAmount( this.value );"));
         }
         $this->assign('hasPriceSets', $buildPriceSet);
     }
     //need to assign custom data type and subtype to the template
     $this->assign('customDataType', 'Membership');
     $this->assign('customDataSubType', $this->_memType);
     $this->assign('entityID', $this->_id);
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if ($this->_context == 'standalone') {
         $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
     }
     $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
     // Throw status bounce when no Membership type or priceset is present
     if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && empty($this->allMembershipTypeDetails) && empty($priceSets)) {
         CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
     }
     // retrieve all memberships
     $allMembershipInfo = array();
     foreach ($this->allMembershipTypeDetails as $key => $values) {
         if ($this->_mode && empty($values['minimum_fee'])) {
             continue;
         } else {
             $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
             if (empty($selMemTypeOrg[$memberOfContactId])) {
                 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $memberOfContactId, 'display_name', 'id');
                 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
             }
             if (empty($selOrgMemType[$memberOfContactId][$key])) {
                 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
             }
         }
         $totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
         //CRM-18827 - override the default value if total_amount is submitted
         if (!empty($this->_submitValues['total_amount'])) {
             $totalAmount = $this->_submitValues['total_amount'];
         }
         // build membership info array, which is used when membership type is selected to:
         // - set the payment information block
         // - set the max related block
         $allMembershipInfo[$key] = array('financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values), 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'), 'total_amount_numeric' => $totalAmount, 'auto_renew' => CRM_Utils_Array::value('auto_renew', $values), 'has_related' => isset($values['relationship_type_id']), 'max_related' => CRM_Utils_Array::value('max_related', $values));
     }
     $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
     // show organization by default, if only one organization in
     // the list
     if (count($selMemTypeOrg) == 2) {
         unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
     }
     //sort membership organization and type, CRM-6099
     natcasesort($selMemTypeOrg);
     foreach ($selOrgMemType as $index => $orgMembershipType) {
         natcasesort($orgMembershipType);
         $selOrgMemType[$index] = $orgMembershipType;
     }
     $memTypeJs = array('onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);");
     if (!empty($this->_recurPaymentProcessors)) {
         $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . "buildAutoRenew(this.value, null, '{$this->_mode}');";
     }
     $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related'));
     $sel =& $this->addElement('hierselect', 'membership_type_id', ts('Membership Organization and Type'), $memTypeJs);
     $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
     $elements = array();
     if ($sel) {
         $elements[] = $sel;
     }
     $this->applyFilter('__ALL__', 'trim');
     if ($this->_action & CRM_Core_Action::ADD) {
         $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
     }
     $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
     $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
     $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
     if ($endDate) {
         $elements[] = $endDate;
     }
     $this->add('text', 'source', ts('Source'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source'));
     //CRM-7362 --add campaigns.
     $campaignId = NULL;
     if ($this->_id) {
         $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
     }
     CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
     if (!$this->_mode) {
         $this->add('select', 'status_id', ts('Membership Status'), array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'));
         $statusOverride = $this->addElement('checkbox', 'is_override', ts('Status Override?'), NULL, array('onClick' => 'showHideMemberStatus()'));
         if ($statusOverride) {
             $elements[] = $statusOverride;
         }
         $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
         $this->add('text', 'total_amount', ts('Amount'));
         $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
         $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
         $this->add('select', 'payment_instrument_id', ts('Payment Method'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
         $this->add('text', 'trxn_id', ts('Transaction ID'));
         $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id'));
         $allowStatuses = array();
         $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
         if ($this->_onlinePendingContributionId) {
             $statusNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
             foreach ($statusNames as $val => $name) {
                 if (in_array($name, array('In Progress', 'Overdue'))) {
                     continue;
                 }
                 $allowStatuses[$val] = $statuses[$val];
             }
         } else {
             $allowStatuses = $statuses;
         }
         $this->add('select', 'contribution_status_id', ts('Payment Status'), $allowStatuses);
         $this->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
     } else {
         //add field for amount to allow an amount to be entered that differs from minimum
         $this->add('text', 'total_amount', ts('Amount'));
     }
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action));
     $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
     $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
     $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
     $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL, array('onclick' => "showEmailOptions()"));
     $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
     $this->add('textarea', 'receipt_text', ts('Receipt Message'));
     // Retrieve the name and email of the contact - this will be the TO for receipt email
     if ($this->_contactID) {
         list($this->_memberDisplayName, $this->_memberEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('emailExists', $this->_memberEmail);
         $this->assign('displayName', $this->_memberDisplayName);
     }
     $isRecur = FALSE;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id');
         if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
             $isRecur = TRUE;
             if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
                 $this->assign('cancelAutoRenew', CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}"));
             }
             foreach ($elements as $elem) {
                 $elem->freeze();
             }
         }
     }
     $this->assign('isRecur', $isRecur);
     $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
     $mailingInfo = Civi::settings()->get('mailing_backend');
     $this->assign('isEmailEnabledForSite', $mailingInfo['outBound_option'] != 2);
     parent::buildQuickForm();
 }