2 /*********************************************************************************
3 * SugarCRM Community Edition is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6 * This program is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU Affero General Public License version 3 as published by the
8 * Free Software Foundation with the addition of the following permission added
9 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
18 * You should have received a copy of the GNU Affero General Public License along with
19 * this program; if not, see http://www.gnu.org/licenses or write to the Free
20 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26 * The interactive user interfaces in modified source and object code versions
27 * of this program must display Appropriate Legal Notices, as required under
28 * Section 5 of the GNU Affero General Public License version 3.
30 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31 * these Appropriate Legal Notices must retain the display of the "Powered by
32 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33 * technical reasons, the Appropriate Legal Notices must display the words
34 * "Powered by SugarCRM".
35 ********************************************************************************/
37 require_once('include/SugarFields/Fields/Collection/SugarFieldCollection.php');
40 class ViewSugarFieldCollection{
41 var $ss; // Sugar Smarty Object
46 var $displayParams; // DisplayParams for the collection field (defined in the metadata)
47 var $vardef; // vardef of the collection field.
48 var $related_module; // module name of the related module
49 var $module_dir; // name of the module where the collection field is.
54 var $skipModuleQuickSearch = false;
55 var $field_to_name_array; //mapping of fields for the return of the select popup
56 var $showSelectButton = true;
57 var $hideShowHideButton = false;
61 function ViewSugarFieldCollection($fill_data = true){
62 $this->json = getJSONobj();
64 $this->displayParams = $this->json->decode(html_entity_decode($_REQUEST['displayParams']));
65 $this->vardef = $this->json->decode(html_entity_decode($_REQUEST['vardef']));
66 $this->module_dir = $_REQUEST['module_dir'];
67 $this->action_type = $_REQUEST['action_type'];
68 $this->name = $this->vardef['name'];
69 $this->value_name = $this->name . '_values';
71 $this->ss = new Sugar_Smarty();
72 $this->edit_tpl_path = $this->findTemplate('CollectionEditView');
73 $this->detail_tpl_path = $this->findTemplate('CollectionDetailView');
74 $this->extra_var = array();
75 $this->field_to_name_array = array();
79 * Retrieve the related module and load the bean and the relationship
80 * call retrieve values()
83 if(!class_exists('Relationship')){
86 $rel = new Relationship();
87 if(!empty($this->vardef['relationship'])){
88 $rel->retrieve_by_name($this->vardef['relationship']);
90 if($rel->relationship_type == 'many-to-many'){
91 if($rel->lhs_module == $this->module_dir){
92 $this->related_module = $rel->rhs_module;
93 $module_dir = $rel->lhs_module;
94 }else if($rel->rhs_module == $this->module_dir){
95 $this->related_module = $rel->lhs_module;
96 $module_dir = $rel->rhs_module;
98 die("this field has no relationships mapped with this module");
100 if($module_dir != $this->module_dir){
101 die('These modules do not match : '. $this->module_dir . ' and ' . $module_dir);
103 if(isset($GLOBALS['beanList'][$this->module_dir])){
104 $class = $GLOBALS['beanList'][$this->module_dir];
105 if(file_exists($GLOBALS['beanFiles'][$class])){
106 $this->bean = loadBean($this->module_dir);
107 $this->bean->retrieve($_REQUEST['bean_id']);
108 if($this->bean->load_relationship($this->vardef['name'])){
109 $this->retrieve_values();
111 die('failed to load the relationship');
114 die('class file do not exist');
117 die($this->module_dir . ' is not in the beanList.');
121 die("the relationship is not a many-to-many");
125 * Retrieve the values from the DB using the get method of the link class
126 * Organize and save the value into the bean
128 function retrieve_values(){
129 if(empty($this->bean->{$this->value_name}) && isset($this->bean->{$this->name})){
131 $values = $this->bean->{$this->name}->get(true);
132 $role_field = $this->bean->{$this->name}->_get_link_table_role_field($this->bean->{$this->name}->_relationship_name);
133 foreach($values as $v){
135 foreach($v as $kk=>$vv){
136 if($kk == $role_field){
140 if($role == 'primary'){
141 $primary_id = $v['id'];
143 $secondary_ids[] = array('id'=>$v['id'], 'role'=>$role);
146 $this->bean->{$this->value_name} = array('role_field'=>$role_field);
147 if(isset($primary_id) || isset($secondary_ids)){
148 if(!isset($primary_id)){
149 $primary_id = $secondary_ids[0]['id'];
150 unset($secondary_ids[0]);
152 if(isset($GLOBALS['beanList'][ $this->related_module])){
153 $class = $GLOBALS['beanList'][$this->related_module];
154 if(file_exists($GLOBALS['beanFiles'][$class])){
155 $mod = loadBean($this->module_dir);
156 $mod->relDepth = $this->bean->relDepth + 1;
157 $mod->retrieve($primary_id);
158 if (isset($mod->name)) {
159 $this->bean->{$this->value_name}=array_merge($this->bean->{$this->value_name}, array('primary'=>array('id'=>$primary_id, 'name'=>$mod->name)));
161 $secondaries = array();
162 if(isset($secondary_ids)){
163 foreach($secondary_ids as $v){
164 if($mod->retrieve($v['id'])){
165 if (isset($mod->name)){
166 $secondaries['secondaries'][]=array('id'=>$v['id'], 'name'=>$mod->name);
171 $this->bean->{$this->value_name}=array_merge($this->bean->{$this->value_name}, $secondaries);
172 if(isset($field['additionalFields'])){
173 foreach($field['additionalFields'] as $field=>$to){
174 if(isset($mod->$field)){
175 $this->bean->$to = $mod->$field;
185 * redirect to the good process method.
188 if($this->action_type == 'editview'){
189 $this->process_editview();
190 }else if($this->action_type == 'detailview'){
191 $this->process_detailview();
194 function process_detailview(){
198 * Build the DisplayParams array
200 function process_editview(){
201 if(isset($this->bean->{$this->value_name}['secondaries'])){
202 $this->numFields=count($this->bean->{$this->value_name}['secondaries'])+1;
204 if(!isset($this->displayParams['readOnly'])) {
205 $this->displayParams['readOnly'] = '';
207 $this->displayParams['readOnly'] = $this->displayParams['readOnly'] == false ? '' : 'READONLY';
209 // If there is extra field to show.
210 if(isset($this->displayParams['collection_field_list'])){
212 $relatedObject = BeanFactory::getObjectName($this->related_module);
213 vardefmanager::loadVardef($this->related_module, $relatedObject);
214 foreach($this->displayParams['collection_field_list'] as $k=>$v){
216 $collection_field_vardef = $GLOBALS['dictionary'][$relatedObject]['fields'][$v['name']];
218 // For each extra field the params which are not displayParams will be consider as params to override the vardefs values.
219 foreach($v as $k_override=>$v_override){
220 if($k_override != 'displayParams'){
221 $collection_field_vardef[$k_override] = $v_override;
225 // If relate field : enable quick search by creating the sqs_object array.
226 if($collection_field_vardef['type'] == 'relate'){
227 require_once('include/TemplateHandler/TemplateHandler.php');
228 $tph = new TemplateHandler();
229 $javascript = $tph->createQuickSearchCode(array($collection_field_vardef['name']=>$collection_field_vardef), array($v), $this->form_name);
230 $javascript = str_replace('<script language="javascript">'."if(typeof sqs_objects == 'undefined'){var sqs_objects = new Array;}sqs_objects['{$collection_field_vardef['name']}']=","",$javascript);
231 $javascript = substr($javascript, 0, -10);//remove ";</script>"
232 $javascriptPHP = $this->json->decode($javascript);
233 foreach($javascriptPHP['populate_list'] as $kk=>$vv){
234 $javascriptPHP['populate_list'][$kk] .= "_" . $this->vardef['name'] . "_collection_extra_0";
236 foreach($javascriptPHP['required_list'] as $kk=>$vv){
237 $javascriptPHP['required_list'][$kk] .= "_" . $this->vardef['name'] . "_collection_extra_0";
239 foreach($javascriptPHP['field_list'] as $kk=>$vv){
241 $javascriptPHP['populate_list'][$kk];
244 $javascript = $this->json->encode($javascriptPHP);
245 $javascript = "<script language='javascript'>if(typeof sqs_objects == 'undefined'){var sqs_objects = new Array;}sqs_objects['{$collection_field_vardef['name']}_" . $this->vardef['name'] . "_collection_extra_0']=".$javascript.';</script>';
248 $collection_field_vardef['name'] .= "_" . $this->vardef['name'] . "_collection_extra_0";
249 if(isset($collection_field_vardef['id_name'])){
250 $collection_field_vardef['id_name'] .= "_" . $this->vardef['name'] . "_collection_extra_0";
252 if(isset($this->displayParams['allow_update']) && ($this->displayParams['allow_update'] === false || $this->displayParams['allow_update'] === 'false')){
253 $this->displayParams['allow_update']='false';
254 $v['displayParams']['field']['disabled']='';
256 $this->displayParams['allow_update']='true';
257 if(!isset($v['displayParams'])){
258 $v['displayParams']=array();
261 $viewtype='EditView';
262 $name = $collection_field_vardef['name'];
263 // Rearranging the array with name as key instaead of number. This is required for displaySmarty() to assign the good variable.
264 $this->displayParams['collection_field_list'][$name]['vardefName'] = $this->displayParams['collection_field_list'][$k]['name'];
265 $this->displayParams['collection_field_list'][$name]['name'] = $name;
266 if($collection_field_vardef['type'] == 'relate'){
267 $this->displayParams['collection_field_list'][$name]['id_name'] = $collection_field_vardef['id_name'];
268 $this->displayParams['collection_field_list'][$name]['module'] = $collection_field_vardef['module'];
270 $this->displayParams['collection_field_list'][$name]['label'] = "{sugar_translate label='{$collection_field_vardef['vname']}' module='{$this->related_module}'}";//translate($collection_field_vardef['vname'], $this->related_module);
271 $this->displayParams['collection_field_list'][$name]['field'] = $sfh->displaySmarty('displayParams.collection_field_list', $collection_field_vardef, $viewtype, $v['displayParams'], 1);
272 $this->displayParams['collection_field_list'][$name]['field'] .= '{literal}'.$javascript;
273 // Handle update_field array ONCHANGE
274 $this->displayParams['collection_field_list'][$name]['field'] .= <<<FRA
275 <script language='javascript'>
276 var oldonchange = '';
277 if(typeof(document.getElementById('{$collection_field_vardef['name']}').attributes.onchange) != 'undefined')
279 oldonchange=document.getElementById('{$collection_field_vardef['name']}').attributes.onchange.value;
282 $this->displayParams['collection_field_list'][$name]['field'] .= "eval(\"document.getElementById('{$collection_field_vardef['name']}').onchange = function onchange(event){collection['{$this->vardef['name']}'].update_fields.{$collection_field_vardef['name']}=true;";
283 if($collection_field_vardef['type'] == 'relate'){
284 // If relate add the ID field to the array
285 $this->displayParams['collection_field_list'][$name]['field'] .= "collection['{$this->vardef['name']}'].update_fields.{$collection_field_vardef['id_name']}=true;";
287 $this->displayParams['collection_field_list'][$name]['field'] .= "document.getElementById('update_fields_{$this->vardef['name']}_collection').value = YAHOO.lang.JSON.stringify(collection['{$this->vardef['name']}'].update_fields);\" + oldonchange + \"};\");</script>{/literal}";
288 //we need to get rid of the old value;
289 unset($this->displayParams['collection_field_list'][$k]);
292 if(!isset($this->displayParams['class'])) $this->displayParams['class']='';
293 if(isset($this->displayParams['allow_new']) && ($this->displayParams['allow_new'] === false || $this->displayParams['allow_new'] === 'false')){
294 $this->displayParams['allow_new']='false';
295 $this->displayParams['class']=str_replace('sqsNoAutofill','',$this->displayParams['class']);
297 $this->displayParams['allow_new']='true';
298 $this->displayParams['class'].=' sqsNoAutofill';
300 if(isset($this->displayParams['new_on_update']) && ($this->displayParams['new_on_update'] !== false || $this->displayParams['new_on_update'] !== 'false' || $this->displayParams['new_on_update'] !== 'FALSE' || $this->displayParams['new_on_update'] !== '0')){
301 $this->displayParams['new_on_update']='true';
303 $this->displayParams['new_on_update']='false';
308 * Init the template with the variables
311 foreach($this->extra_var as $k=>$v){
312 $this->ss->assign($k,$v);
314 if($this->action_type == 'editview'){
315 $this->ss->assign('quickSearchCode',$this->createQuickSearchCode());
316 $this->createPopupCode();// this code populate $this->displayParams with popupdata.
317 $this->tpl_path = $this->edit_tpl_path;
318 }else if($this->action_type == 'detailview'){
319 $this->tpl_path = $this->detail_tpl_path;
322 $this->ss->assign('displayParams',$this->displayParams);
323 $this->ss->assign('vardef',$this->vardef);
324 $this->ss->assign('module',$this->related_module);
325 $this->ss->assign('values',$this->bean->{$this->value_name});
326 $this->ss->assign('showSelectButton',$this->showSelectButton);
327 $this->ss->assign('hideShowHideButton',$this->hideShowHideButton);
328 $this->ss->assign('APP',$GLOBALS['app_strings']);
331 * Display the collection field after retrieving the cached row.
334 $cacheRowFile = sugar_cached('modules/') . $this->module_dir . '/collections/'. $this->name . '.tpl';
335 if(!$this->checkTemplate($cacheRowFile)){
336 $dir = dirname($cacheRowFile);
337 if(!file_exists($dir)) {
339 mkdir_recursive($dir, null, true);
341 $cacheRow = $this->ss->fetch($this->findTemplate('CollectionEditViewRow'));
342 file_put_contents($cacheRowFile, $cacheRow);
344 $this->ss->assign('cacheRowFile', $cacheRowFile);
345 return $this->ss->fetch($this->tpl_path);
348 * Check if the template is cached
351 function checkTemplate($cacheRowFile){
352 if(inDeveloperMode() || !empty($_SESSION['developerMode'])){
355 return file_exists($cacheRowFile);
360 * Create the quickSearch code for the collection field.
361 * return the javascript code which define sqs_objects.
363 function createQuickSearchCode($returnAsJavascript = true){
364 $sqs_objects = array();
365 require_once('include/QuickSearchDefaults.php');
366 $qsd = QuickSearchDefaults::getQuickSearchDefaults();
367 $qsd->setFormName($this->form_name);
368 for($i=0; $i<$this->numFields; $i++){
369 $name1 = "{$this->form_name}_{$this->name}_collection_{$i}";
370 if(!$this->skipModuleQuickSearch && preg_match('/(Campaigns|Teams|Users|Accounts)/si', $this->related_module, $matches)) {
371 if($matches[0] == 'Users'){
372 $sqs_objects[$name1] = $qsd->getQSUser();
373 } else if($matches[0] == 'Campaigns') {
374 $sqs_objects[$name1] = $qsd->getQSCampaigns();
376 } else if($matches[0] == 'Users'){
377 $sqs_objects[$name1] = $qsd->getQSUser();
379 } else if($matches[0] == 'Accounts') {
380 $nameKey = "{$this->name}_collection_{$i}";
381 $idKey = "id_{$this->name}_collection_{$i}";
383 //There are billingKey, shippingKey and additionalFields entries you can define in editviewdefs.php
384 //entry to allow quick search to autocomplete fields with a suffix value of the
385 //billing/shippingKey value (i.e. 'billingKey' => 'primary' in Contacts will populate
386 //primary_XXX fields with the Account's billing address values).
387 //addtionalFields are key/value pair of fields to fill from Accounts(key) to Contacts(value)
388 $billingKey = isset($this->displayParams['billingKey']) ? $this->displayParams['billingKey'] : null;
389 $shippingKey = isset($this->displayParams['shippingKey']) ? $this->displayParams['shippingKey'] : null;
390 $additionalFields = isset($this->displayParams['additionalFields']) ? $this->displayParams['additionalFields'] : null;
391 $sqs_objects[$name1] = $qsd->getQSAccount($nameKey, $idKey, $billingKey, $shippingKey, $additionalFields);
392 } else if($matches[0] == 'Contacts'){
393 $sqs_objects[$name1] = $qsd->getQSContact($name1, "id_".$name1);
397 $temp_array = array('field_list'=>array(),'populate_list'=>array());
398 foreach($sqs_objects[$name1]['field_list'] as $k=>$v){
399 if(!in_array($v, array('name','id'))){
400 $sqs_objects[$name1]['primary_field_list'][]=$v;
401 $sqs_objects[$name1]['primary_populate_list'][]=$sqs_objects[$name1]['populate_list'][$k];
403 $temp_array['field_list'][]=$v;
404 $temp_array['populate_list'][]=$sqs_objects[$name1]['populate_list'][$k];
407 $sqs_objects[$name1]['field_list'] = $temp_array['field_list'];
408 $sqs_objects[$name1]['populate_list'] = $temp_array['populate_list'];
409 if(isset($this->displayParams['collection_field_list'])){
410 foreach($this->displayParams['collection_field_list'] as $v){
411 $sqs_objects[$name1]['populate_list'][]= $v['vardefName']."_".$this->name."_collection_extra_".$i;
412 $sqs_objects[$name1]['field_list'][] = $v['vardefName'];
416 $sqs_objects[$name1] = $qsd->getQSParent($this->related_module);
417 $sqs_objects[$name1]['populate_list'] = array("{$this->vardef['name']}_collection_{$i}", "id_{$this->vardef['name']}_collection_{$i}");
418 $sqs_objects[$name1]['field_list'] = array('name', 'id');
419 if(isset($this->displayParams['collection_field_list'])){
420 foreach($this->displayParams['collection_field_list'] as $v){
421 $sqs_objects[$name1]['populate_list'][] = $v['vardefName']."_".$this->name."_collection_extra_".$i;
422 $sqs_objects[$name1]['field_list'][] = $v['vardefName'];
425 if(isset($this->displayParams['field_to_name_array'])){
426 foreach($this->displayParams['field_to_name_array'] as $k=>$v){
428 * "primary_populate_list" and "primary_field_list" are used when the field is selected as a primary.
429 * At this time the JS function changePrimary() will copy "primary_populate_list" and "primary_field_list"
430 * into "populate_list" and "field_list" and remove the values from all the others which are secondaries.
431 * "primary_populate_list" and "primary_field_list" contain the fields which has to be populated outside of
432 * the collection field. For example the "Address Information" are populated with the "billing address" of the
433 * selected account in a contact editview.
435 $sqs_objects[$name1]['primary_populate_list'][] = $v;
436 $sqs_objects[$name1]['primary_field_list'][] = $k;
438 }else if(isset($field['field_list']) && isset($field['populate_list'])){
439 $sqs_objects[$name1]['primary_populate_list'] = array_merge($sqs_objects[$name1]['populate_list'], $field['field_list']);
440 $sqs_objects[$name1]['primary_field_list'] = array_merge($sqs_objects[$name1]['field_list'], $field['populate_list']);
442 $sqs_objects[$name1]['primary_populate_list'] = array();
443 $sqs_objects[$name1]['primary_field_list'] = array();
448 $id = "{$this->form_name}_{$this->name}_collection_0";
450 if(!empty($sqs_objects) && count($sqs_objects) > 0) {
451 foreach($sqs_objects[$id]['field_list'] as $k=>$v){
452 $this->field_to_name_array[$v] = $sqs_objects[$id]['populate_list'][$k];
454 if($returnAsJavascript){
455 $quicksearch_js = '<script language="javascript">';
456 $quicksearch_js.= "if(typeof sqs_objects == 'undefined'){var sqs_objects = new Array;}";
458 foreach($sqs_objects as $sqsfield=>$sqsfieldArray){
459 $quicksearch_js .= "sqs_objects['$sqsfield']={$this->json->encode($sqsfieldArray)};";
462 return $quicksearch_js .= '</script>';
470 * Always call createQuickSearchCode() before createPopupCode() to define field_to_name_array
472 function createPopupCode(){
473 // TODO the 'select' button is not fully working. We should use the sqs_objects in open_popup instead of the parameter.
474 if(isset($this->field_to_name_array) && !empty($this->field_to_name_array)){
475 $call_back_function = 'set_return';
477 if(isset($this->displayParams['formName'])) {
478 $form = $this->displayParams['formName'];
479 } else if($this->action_type == 'editview'){
481 } else if($this->action_type == 'quickcreate'){
482 $form = "QuickCreate_{$this->module_dir}";
485 if(isset($this->displayParams['call_back_function'])) {
486 $call_back_function = $this->displayParams['call_back_function'];
489 $popup_request_data= array(
490 'call_back_function' => $call_back_function,
491 'form_name' => $form,
492 'field_to_name_array' => $this->field_to_name_array,
495 //Make sure to replace {{ and }} with spacing in between because Smarty template parsing will treat {{ or }} specially
496 $this->displayParams['popupData'] = '{literal}'. str_replace(array('{{', '}}'), array('{ {', '} }'), $this->json->encode($popup_request_data)) . '{/literal}';
502 function findTemplate($view){
503 static $tplCache = array();
505 if ( isset($tplCache[$this->type][$view]) ) {
506 return $tplCache[$this->type][$view];
509 $lastClass = get_class($this);
510 $classList = array($this->type,str_replace('ViewSugarField','',$lastClass));
511 while ( $lastClass = get_parent_class($lastClass) ) {
512 $classList[] = str_replace('ViewSugarField','',$lastClass);
516 foreach ( $classList as $className ) {
517 global $current_language;
518 if(isset($current_language)) {
519 $tplName = 'include/SugarFields/Fields/'. $className .'/'. $current_language . '.' . $view .'.tpl';
520 if ( file_exists('custom/'.$tplName) ) {
521 $tplName = 'custom/'.$tplName;
524 if ( file_exists($tplName) ) {
528 $tplName = 'include/SugarFields/Fields/'. $className .'/'. $view .'.tpl';
529 if ( file_exists('custom/'.$tplName) ) {
530 $tplName = 'custom/'.$tplName;
533 if ( file_exists($tplName) ) {
538 $tplCache[$this->type][$view] = $tplName;