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
18 use Civi\Api4\Product
;
21 * This class generates form components for Premiums.
23 class CRM_Contribute_Form_ManagePremiums
extends CRM_Contribute_Form
{
26 * Classes extending CRM_Core_Form should implement this method.
30 public function getDefaultEntity() {
35 * Set default values for the form.
37 public function setDefaultValues() {
38 $defaults = parent
::setDefaultValues();
40 $tempDefaults = Product
::get()->addWhere('id', '=', $this->_id
)->execute()->first();
41 if (isset($tempDefaults['image']) && isset($tempDefaults['thumbnail'])) {
42 $defaults['imageUrl'] = $tempDefaults['image'];
43 $defaults['thumbnailUrl'] = $tempDefaults['thumbnail'];
44 $defaults['imageOption'] = 'thumbnail';
45 // assign thumbnailUrl to template so we can display current image in update mode
46 $this->assign('thumbnailUrl', $defaults['thumbnailUrl']);
49 $defaults['imageOption'] = 'noImage';
51 if (isset($tempDefaults['thumbnail']) && isset($tempDefaults['image'])) {
52 $this->assign('thumbURL', $tempDefaults['thumbnail']);
53 $this->assign('imageURL', $tempDefaults['image']);
55 if (isset($tempDefaults['period_type'])) {
56 $this->assign('showSubscriptions', TRUE);
64 * Build the form object.
66 * @throws \CiviCRM_API3_Exception
68 public function buildQuickForm() {
69 parent
::buildQuickForm();
70 $this->setPageTitle(ts('Premium Product'));
72 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
73 CRM_Contribute_BAO_Premium
::buildPremiumPreviewBlock($this, $this->_id
);
77 if ($this->_action
& CRM_Core_Action
::DELETE
) {
81 $this->applyFilter('__ALL__', 'trim');
82 $this->add('text', 'name', ts('Name'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'name'), TRUE);
83 $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', [
84 'CRM_Contribute_DAO_Product',
87 $this->add('text', 'sku', ts('SKU'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'sku'));
89 $this->add('textarea', 'description', ts('Description'), ['cols' => 60, 'rows' => 3]);
91 $image['image'] = ts('Upload from my computer');
92 $imageJS['image'] = ['onclick' => 'add_upload_file_block(\'image\');', 'class' => 'required'];
93 $image['thumbnail'] = ts('Display image and thumbnail from these locations on the web:');
94 $imageJS['thumbnail'] = ['onclick' => 'add_upload_file_block(\'thumbnail\');', 'class' => 'required'];
95 $image['default_image'] = ts('Use default image');
96 $imageJS['default_image'] = ['onclick' => 'add_upload_file_block(\'default\');', 'class' => 'required'];
97 $image['noImage'] = ts('Do not display an image');
98 $imageJS['noImage'] = ['onclick' => 'add_upload_file_block(\'noImage\');', 'class' => 'required'];
100 $this->addRadio('imageOption', ts('Premium Image'), $image, [], NULL, FALSE, $imageJS);
101 $this->addRule('imageOption', ts('Please select an option for the premium image.'), 'required');
103 $this->addElement('text', 'imageUrl', ts('Image URL'));
104 $this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
106 $this->add('file', 'uploadFile', ts('Image File Name'), ['onChange' => 'select_option();']);
108 $this->add('text', 'price', ts('Market Value'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'price'), TRUE);
109 $this->addRule('price', ts('Please enter the Market Value for this product.'), 'money');
111 $this->add('text', 'cost', ts('Actual Cost of Product'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'cost'));
112 $this->addRule('price', ts('Please enter the Actual Cost of Product.'), 'money');
114 $this->add('text', 'min_contribution', ts('Minimum Contribution Amount'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'min_contribution'), TRUE);
115 $this->addRule('min_contribution', ts('Please enter a monetary value for the Minimum Contribution Amount.'), 'money');
117 $this->add('textarea', 'options', ts('Options'), ['cols' => 60, 'rows' => 3]);
119 $this->add('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues
::periodType(), FALSE, ['placeholder' => TRUE]);
121 $this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
123 $this->addField('duration_unit', ['placeholder' => ts('- select period -')], FALSE);
124 $this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
125 $this->addField('frequency_unit', ['placeholder' => ts('- select period -')], FALSE);
126 $this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
128 //Financial Type CRM-11106
129 $financialType = CRM_Contribute_PseudoConstant
::financialType();
130 $premiumFinancialType = [];
131 CRM_Core_PseudoConstant
::populate(
132 $premiumFinancialType,
133 'CRM_Financial_DAO_EntityFinancialAccount',
135 $retrieve = 'entity_id',
137 'account_relationship = 8'
140 $costFinancialType = [];
141 CRM_Core_PseudoConstant
::populate(
143 'CRM_Financial_DAO_EntityFinancialAccount',
145 $retrieve = 'entity_id',
147 'account_relationship = 7'
149 $productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
150 foreach ($financialType as $key => $financialTypeName) {
151 if (!in_array($key, $productFinancialType)) {
152 unset($financialType[$key]);
155 if (count($financialType)) {
156 $this->assign('financialType', $financialType);
161 ts('Financial Type'),
164 ['placeholder' => TRUE]
167 $this->add('checkbox', 'is_active', ts('Enabled?'));
169 $this->addFormRule(['CRM_Contribute_Form_ManagePremiums', 'formRule']);
174 'name' => ts('Save'),
179 'name' => ts('Cancel'),
182 $this->assign('productId', $this->_id
);
186 * Function for validation.
188 * @param array $params
189 * (ref.) an assoc array of name/value pairs.
193 * mixed true or array of errors
195 public static function formRule($params, $files) {
197 // If choosing to upload an image, then an image must be provided
198 if (CRM_Utils_Array
::value('imageOption', $params) == 'image'
199 && empty($files['uploadFile']['name'])
201 $errors['uploadFile'] = ts('A file must be selected');
204 // If choosing to use image URLs, then both URLs must be present
205 if (CRM_Utils_Array
::value('imageOption', $params) == 'thumbnail') {
206 if (!$params['imageUrl']) {
207 $errors['imageUrl'] = ts('Image URL is Required');
209 if (!$params['thumbnailUrl']) {
210 $errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
214 // CRM-13231 financial type required if product has cost
215 if (!empty($params['cost']) && empty($params['financial_type_id'])) {
216 $errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
219 if (!$params['period_type']) {
220 if ($params['fixed_period_start_day'] ||
$params['duration_unit'] ||
$params['duration_interval'] ||
221 $params['frequency_unit'] ||
$params['frequency_interval']
223 $errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
227 if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
228 $errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
231 if ($params['duration_unit'] && !$params['duration_interval']) {
232 $errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
235 if ($params['duration_interval'] && !$params['duration_unit']) {
236 $errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
239 if ($params['frequency_interval'] && !$params['frequency_unit']) {
240 $errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
243 if ($params['frequency_unit'] && !$params['frequency_interval']) {
244 $errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
247 return empty($errors) ?
TRUE : $errors;
251 * Process the form submission.
253 public function postProcess() {
254 // If previewing, don't do any post-processing
255 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
259 // If deleting, then only delete and skip the rest of the post-processing
260 if ($this->_action
& CRM_Core_Action
::DELETE
) {
262 CRM_Contribute_BAO_Product
::del($this->_id
);
264 catch (CRM_Core_Exception
$e) {
265 $message = ts("This Premium is linked to an <a href='%1'>Online Contribution page</a>. Please remove it before deleting this Premium.", [1 => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1')]);
266 CRM_Core_Session
::setStatus($message, ts('Cannot delete Premium'), 'error');
267 CRM_Core_Session
::singleton()->pushUserContext(CRM_Utils_System
::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
270 CRM_Core_Session
::setStatus(
271 ts('Selected Premium Product type has been deleted.'),
272 ts('Deleted'), 'info');
276 $params = $this->controller
->exportValues($this->_name
);
278 // Clean the the money fields
279 $moneyFields = ['cost', 'price', 'min_contribution'];
280 foreach ($moneyFields as $field) {
281 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
284 // If we're updating, we need to pass in the premium product Id
285 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
286 $params['id'] = $this->_id
;
289 $this->_processImages($params);
291 // Save the premium product to database
292 $premium = Product
::save()->addRecord($params)->execute()->first();
294 CRM_Core_Session
::setStatus(
295 ts("The Premium '%1' has been saved.", [1 => $premium['name']]),
296 ts('Saved'), 'success');
300 * Look at $params to find form info about images. Manipulate images if
301 * necessary. Then alter $params to point to the newly manipulated images.
303 * @param array $params
305 protected function _processImages(&$params) {
307 'imageOption' => 'noImage',
308 'uploadFile' => ['name' => ''],
312 'thumbnailUrl' => '',
314 $params = array_merge($defaults, $params);
316 // User is uploading an image
317 if ($params['imageOption'] == 'image') {
318 $imageFile = $params['uploadFile']['name'];
320 $params['image'] = CRM_Utils_File
::resizeImage($imageFile, 200, 200, "_full");
321 $params['thumbnail'] = CRM_Utils_File
::resizeImage($imageFile, 50, 50, "_thumb");
323 catch (CRM_Core_Exception
$e) {
324 $params['image'] = self
::_defaultImage();
325 $params['thumbnail'] = self
::_defaultThumbnail();
326 $msg = ts('The product has been configured to use a default image.');
327 CRM_Core_Session
::setStatus($e->getMessage() . " $msg", ts('Notice'), 'alert');
331 // User is specifying existing URLs for the images
332 elseif ($params['imageOption'] == 'thumbnail') {
333 $params['image'] = $params['imageUrl'];
334 $params['thumbnail'] = $params['thumbnailUrl'];
337 // User wants a default image
338 elseif ($params['imageOption'] == 'default_image') {
339 $params['image'] = self
::_defaultImage();
340 $params['thumbnail'] = self
::_defaultThumbnail();
345 * Returns the path to the default premium image
348 protected static function _defaultImage() {
349 $config = CRM_Core_Config
::singleton();
350 return $config->resourceBase
. 'i/contribute/default_premium.jpg';
354 * Returns the path to the default premium thumbnail
357 protected static function _defaultThumbnail() {
358 $config = CRM_Core_Config
::singleton();
359 return $config->resourceBase
. 'i/contribute/default_premium_thumb.jpg';