Example #1
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $formTool =& Dataface_FormTool::getInstance();
     $factory =& Dataface_FormTool::factory();
     if (isset($field['fields'])) {
         $els = array();
         foreach (array_keys($field['fields']) as $field_key) {
             $els[] = $formTool->buildWidget($record, $field['fields'][$field_key], $factory, $field['fields'][$field_key]['name']);
         }
         $el =& $factory->addGroup($els, $field['name'], $field['widget']['label']);
     } else {
         $el =& $factory->addElement('text', $field['name'], $widget['label']);
     }
     if (!@$field['widget']['layout']) {
         $field['widget']['layout'] = 'table';
     }
     if (!@$field['widget']['layout']) {
         $field['widget']['columns'] = 1;
     }
     if (!@$field['widget']['separator']) {
         $field['widget']['separator'] = '<br />';
     }
     $el->setFieldDef($field);
     return $el;
 }
Example #2
0
 function &pushValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName = $element->getName();
     $val = $element->getValue();
     //print_r($val);exit;
     if (is_array($val)) {
         $val = $val[$field['name']];
     }
     if (preg_match('/int/', @$field['Type']) and $val !== '' and $val !== null) {
         //print_r($_POST);
         //echo "Val is $val";exit;
         $out = intval($val);
     } else {
         //echo "Out is $val";exit;
         $out = $val;
     }
     //$res =& $s->setValue($fieldname, $val);
     if (PEAR::isError($val)) {
         $val->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushValue.ERROR_PUSHING_VALUE', "Error pushing value for field '{$field['name']}' in QuickForm::pushWidget() on line " . __LINE__ . " of file " . __FILE__, array('name' => $field['name'], 'file' => __FILE__, 'line' => __LINE__)));
         return $val;
     }
     return $out;
 }
    /**
     * @brief Initializes the datepicker module and registers all of the event listener.
     *
     */
    function __construct()
    {
        $app = Dataface_Application::getInstance();
        // Now work on our dependencies
        $mt = Dataface_ModuleTool::getInstance();
        // We require the XataJax module
        // The XataJax module activates and embeds the Javascript and CSS tools
        $mt->loadModule('modules_XataJax', 'modules/XataJax/XataJax.php');
        // Register the geopicker widget with the form tool so that it responds
        // to widget:type=geopicker
        import('Dataface/FormTool.php');
        $ft = Dataface_FormTool::getInstance();
        $ft->registerWidgetHandler('geopicker', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'widget.php', 'Dataface_FormTool_geopicker');
        if (!@$app->_conf['modules_geopicker'] or !@$app->_conf['modules_geopicker']['key']) {
            $msg = <<<END
                 <p>Google Maps Module is installed but no API key is specified.</p>
                 <p>For information about obtaining your API key see <a href="https://developers.google.com/maps/documentation/javascript/tutorial#api_key">this page</a>.</p>
                 <p>After obtaining your key, add the following section to your application's conf.ini file:</p>
                 <p><code><pre>
[modules_geopicker]
    key=YOUR_API_KEY_HERE
                    </pre></code></p>
END;
            die($msg);
        }
        $app->addHeadContent('<script>XF_GEOPICKER_API_KEY="' . htmlspecialchars($app->_conf['modules_geopicker']['key']) . '";</script>');
        foreach (Dataface_Table::loadTable('', df_db(), true) as $t) {
            $evt = new StdClass();
            $evt->table = $t;
            $this->afterTableInit($evt);
        }
        $app->registerEventListener("afterTableInit", array($this, 'afterTableInit'));
        $app->registerEventListener("Dataface_Record__htmlValue", array($this, 'Dataface_Record__htmlValue'));
    }
Example #4
0
 /**
  * Defines how a radio button widget should be built.
  *
  * @param Dataface_Record $record The Dataface_Record that is being edited.
  * @param array &$field The field configuration data structure that the widget is being generated for.
  * @param HTML_QuickForm The form to which the field is to be added.
  * @param string $formFieldName The name of the field in the form.
  * @param boolean $new Whether this widget is being built for a new record form.
  * @return HTML_QuickForm_element The element that can be added to a form.
  *
  */
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $widget =& $field['widget'];
     if (!@$widget['separator']) {
         $widget['separator'] = '<br />';
     }
     if (isset($field['vocabulary']) and $field['vocabulary']) {
         $radios = array();
         $dummyForm = new HTML_QuickForm();
         $options =& Dataface_FormTool::getVocabulary($record, $field);
         $options__classes = Dataface_FormTool::getVocabularyClasses($record, $field);
         // CSS classes
         foreach ($options as $opt_val => $opt_text) {
             if ($opt_val === '') {
                 continue;
             }
             $radios[] =& $dummyForm->createElement('radio', null, null, $opt_text, $opt_val, array('class' => 'radio-of-' . $field['name'] . ' ' . @$options__classes[$opt_val]));
         }
         $factory =& Dataface_FormTool::factory();
         $el =& $factory->addGroup($radios, $field['name'], $widget['label']);
     } else {
         error_log("Your field {$formFieldName} is missing the vocabulary directive.");
         throw new Exception("Your field {$formFieldName} is missing the vocabulary directive.");
     }
     return $el;
 }
Example #5
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('time', $formFieldName, $widget['label'], array(), $widget);
     return $el;
 }
Example #6
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     /*
      *
      * This field uses a table widget.
      *
      */
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $factory =& Dataface_FormTool::factory();
     $widget =& $field['widget'];
     $el =& $factory->addElement('table', $formFieldName, $widget['label']);
     if (isset($widget['fields'])) {
         $widget_fields =& $widget['fields'];
         foreach ($widget_fields as $widget_field) {
             $widget_field =& Dataface_Table::getTableField($widget_field, $this->db);
             if (PEAR::isError($widget_field)) {
                 return $widget_field;
             }
             $widget_widget = $formTool->buildWidget($record, $widget_field, $factory, $widget_field['name']);
             $el->addField($widget_widget);
         }
     } else {
         if (isset($field['fields'])) {
             foreach (array_keys($field['fields']) as $field_key) {
                 $widget_widget = $formTool->buildWidget($record, $field['fields'][$field_key], $factory, $field['fields'][$field_key]['name']);
                 $el->addField($widget_widget);
                 unset($widget_widget);
             }
         }
     }
     return $el;
 }
 /**
  * Defines how a geopicker widget should be built.
  *
  * @param Dataface_Record $record The Dataface_Record that is being edited.
  * @param array &$field The field configuration data structure that the widget is being generated for.
  * @param HTML_QuickForm The form to which the field is to be added.
  * @param string $formFieldName The name of the field in the form.
  * @param boolean $new Whether this widget is being built for a new record form.
  * @return HTML_QuickForm_element The element that can be added to a form.
  *
  */
 function &buildWidget($record, &$field, $form, $formFieldName, $new = false)
 {
     $factory = Dataface_FormTool::factory();
     $mt = Dataface_ModuleTool::getInstance();
     $mod = $mt->loadModule('modules_geopicker');
     $widget =& $field['widget'];
     $atts = array();
     if (!@$atts['class']) {
         $atts['class'] = '';
     }
     $atts['class'] .= ' xf-geopicker';
     $atts['df:cloneable'] = 1;
     $perms = $record->getPermissions(array('field' => $field['name']));
     $noEdit = ($new and !@$perms['new']) or !$new and !@$perms['edit'];
     if ($noEdit) {
         $atts['data-geopicker-read-only'] = "1";
     }
     $mod->registerPaths();
     // Add our javascript
     Dataface_JavascriptTool::getInstance()->import('xataface/modules/geopicker/widgets/geopicker.js');
     $el = $factory->addElement('text', $formFieldName, $widget['label'], $atts);
     if (PEAR::isError($el)) {
         throw new Exception($el->getMessage(), $el->getCode());
     }
     return $el;
 }
Example #8
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $widget =& $field['widget'];
     $options =& Dataface_FormTool::getVocabulary($record, $field);
     $el =& $form->addElement('autocomplete', $formFieldName, $widget['label'], array('class' => $widget['class'], 'id' => $field['name']));
     $el->setOptions($options);
     return $el;
 }
Example #9
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $widget['record'] =& $record;
     $el =& $factory->addElement('portal', $formFieldName, $widget['label']);
     $el->init_portal($widget);
     return $el;
 }
Example #10
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('hidden', $field['name']);
     if (PEAR::isError($el)) {
         throw new Exception("Failed to get element for field {$field['name']} of table " . $record->_table->tablename . "\n" . "The error returned was " . $el->getMessage(), E_USER_ERROR);
     }
     $el->setFieldDef($field);
     return $el;
 }
 /**
  * Defines how a depselect widget should be built.
  *
  * @param Dataface_Record $record The Dataface_Record that is being edited.
  * @param array &$field The field configuration data structure that the widget is being generated for.
  * @param HTML_QuickForm The form to which the field is to be added.
  * @param string $formFieldName The name of the field in the form.
  * @param boolean $new Whether this widget is being built for a new record form.
  * @return HTML_QuickForm_element The element that can be added to a form.
  *
  */
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $factory = Dataface_FormTool::factory();
     $mt = Dataface_ModuleTool::getInstance();
     $mod = $mt->loadModule('modules_depselect');
     //$atts = $el->getAttributes();
     $widget =& $field['widget'];
     $atts = array();
     if (!@$atts['class']) {
         $atts['class'] = '';
     }
     $atts['class'] .= ' xf-depselect';
     if (!@$atts['data-xf-table']) {
         $atts['data-xf-table'] = $field['tablename'];
     }
     $targetTable = Dataface_Table::loadTable($field['widget']['table']);
     if (PEAR::isError($targetTable)) {
         error_log("Your field {$formFieldName} is missing the widget:table directive or the table does not exist.");
         throw new Exception("Your field {$formFieldName} is missing the widget:table directive or the table does not exist.");
     }
     $targetPerms = $targetTable->getPermissions();
     $atts['data-xf-depselect-options-table'] = $field['widget']['table'];
     if (@$targetPerms['new']) {
         $atts['data-xf-depselect-perms-new'] = 1;
     }
     $atts['df:cloneable'] = 1;
     $jt = Dataface_JavascriptTool::getInstance();
     $jt->addPath(dirname(__FILE__) . '/js', $mod->getBaseURL() . '/js');
     $ct = Dataface_CSSTool::getInstance();
     $ct->addPath(dirname(__FILE__) . '/css', $mod->getBaseURL() . '/css');
     // Add our javascript
     $jt->import('xataface/widgets/depselect.js');
     $filters = array();
     if (@$field['widget']['filters'] and is_array($field['widget']['filters'])) {
         foreach ($field['widget']['filters'] as $key => $val) {
             $filters[] = urlencode($key) . '=' . urlencode($val);
         }
     }
     $atts['data-xf-depselect-filters'] = implode('&', $filters);
     if (@$field['widget']['nomatch']) {
         $atts['data-xf-depselect-nomatch'] = $field['widget']['nomatch'];
     }
     if (@$field['widget']['dialogSize']) {
         $atts['data-xf-depselect-dialogSize'] = $field['widget']['dialogSize'];
     }
     if (@$field['widget']['dialogMargin']) {
         $atts['data-xf-depselect-dialogMargin'] = $field['widget']['dialogMargin'];
     }
     //$el->setAttributes($atts);
     $el = $factory->addElement('depselect', $formFieldName, $widget['label'], $atts);
     if (PEAR::isError($el)) {
         throw new Exception($el->getMessage(), $el->getCode());
     }
     return $el;
 }
Example #12
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('hidden', $field['name']);
     if (PEAR::isError($el)) {
         echo "Failed to get element for field {$field['name']} of table " . $record->_table->tablename;
         echo "The error returned was " . $el->getMessage();
         echo Dataface_Error::printStackTrace();
     }
     $el->setFieldDef($field);
     return $el;
 }
Example #13
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     /*
      * This field uses a calendar widget
      */
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('lookup', $formFieldName, $widget['label']);
     if (PEAR::isError($el)) {
         return $el;
     }
     $el->setProperties($widget);
     return $el;
 }
Example #14
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     /*
      * This field uses a calendar widget
      */
     $widget =& $field['widget'];
     if (!@$widget['lang']) {
         $widget['lang'] = Dataface_Application::getInstance()->_conf['lang'];
     }
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('calendar', $formFieldName, $widget['label'], null, $widget);
     //$el->setProperties($widget);
     return $el;
 }
 /**
  * @brief Initializes the depselect module and registers all of the event listener.
  *
  */
 function __construct()
 {
     $app = Dataface_Application::getInstance();
     // Now work on our dependencies
     $mt = Dataface_ModuleTool::getInstance();
     // We require the XataJax module
     // The XataJax module activates and embeds the Javascript and CSS tools
     $mt->loadModule('modules_XataJax', 'modules/XataJax/XataJax.php');
     // Register the tagger widget with the form tool so that it responds
     // to widget:type=tagger
     import('Dataface/FormTool.php');
     $ft = Dataface_FormTool::getInstance();
     $ft->registerWidgetHandler('depselect', dirname(__FILE__) . '/widget.php', 'Dataface_FormTool_depselect');
 }
Example #16
0
 function pushValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName = $element->getName();
     if ($table->isDate($field['name'])) {
         return Dataface_converters_date::qf2Table($element->getValue());
     } else {
         if ($table->isInt($field['name'])) {
             return Dataface_converters_date::qf2UnixTimestamp($element->getValue());
         } else {
             return Dataface_converters_date::datetime_to_string(Dataface_converters_date::qf2Table($element->getValue()));
         }
     }
 }
Example #17
0
 /**
  * @brief Added support to transform date values in alternate formats
  * as provided by the widget:ifFormat directive.
  * http://xataface.com/forum/viewtopic.php?f=4&t=5345
  */
 function pullValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName = $field['name'];
     $val = $record->strval($formFieldName);
     if (!trim($val)) {
         return '';
     }
     if (@$field['widget']['ifFormat']) {
         return strftime($field['widget']['ifFormat'], strtotime($val));
     } else {
         return $val;
     }
 }
Example #18
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     /*
      * This field uses a calendar widget
      */
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('yui_autocomplete', $formFieldName, $widget['label']);
     $el->setProperties($widget);
     if (@$field['vocabulary']) {
         $el->options = $record->_table->getValuelist($field['vocabulary']);
         $el->vocabularyName = $field['vocabulary'];
         $el->updateAttributes(array('df:vocabulary' => $el->vocabularyName));
     } else {
         if (isset($widget['datasource'])) {
             $datasource =& $widget['datasource'];
             if (isset($datasource['url'])) {
                 $el->datasourceUrl = $datasource['url'];
                 $el->updateAttributes(array('df:datasource' => $el->datasourceUrl));
                 if (!isset($datasource['resultNode'])) {
                     $datasource['resultNode'] = 'Result';
                 }
                 $el->resultNode = $datasource['resultNode'];
                 $el->updateAttributes(array('df:resultNode' => $el->resultNode));
                 if (!isset($datasource['fieldname'])) {
                     $datasource['fieldname'] = 'df:title';
                 }
                 $el->queryKeyNode = $datasource['fieldname'];
                 $el->updateAttributes(array('df:queryKeyNode' => $el->queryKeyNode));
                 if (!@$datasource['other_fieldnames']) {
                     $el->additionalNodes = array();
                 } else {
                     $el->additionalNodes = array_map('trim', explode(',', $datasource['other_fieldnames']));
                 }
                 $el->updateAttributes(array('df:additionalNodes' => implode(',', $el->additionalNodes)));
                 if (!@$datasource['scriptQueryParam']) {
                     $datasource['scriptQueryParam'] = '-search';
                 }
                 $el->scriptQueryParam = $datasource['scriptQueryParam'];
                 $el->updateAttributes(array('df:scriptQueryParam' => $el->scriptQueryParam));
             }
         }
     }
     if (@$field['yui_autocomplete'] and is_array($field['yui_autocomplete'])) {
         $el->updateAttributes(array('data-xf-max-results-displayed' => $field['yui_autocomplete']['maxResultsDisplayed']));
     }
     return $el;
 }
Example #19
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     if (is_string($field)) {
         echo Dataface_Error::printStackTrace();
     }
     $table =& $record->_table;
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('htmlarea', $formFieldName, $widget['label'], array('class' => $widget['class'], 'id' => $field['name']));
     if (method_exists($el, 'setWysiwygOptions')) {
         $el->setWysiwygOptions($widget);
         if (isset($widget['editor'])) {
             $el->editorName = $widget['editor'];
         }
     }
     return $el;
 }
Example #20
0
 function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
 {
     if (is_string($field)) {
         throw new Exception("buildWidget expects field to be a structure but recieved a string: {$field}", E_USER_ERROR);
     }
     $table =& $record->_table;
     $widget =& $field['widget'];
     $factory =& Dataface_FormTool::factory();
     $el =& $factory->addElement('htmlarea', $formFieldName, $widget['label'], array('class' => $widget['class'], 'id' => $field['name']));
     if (method_exists($el, 'setWysiwygOptions')) {
         $el->setWysiwygOptions($widget);
         if (isset($widget['editor'])) {
             $el->editorName = $widget['editor'];
         }
     }
     return $el;
 }
Example #21
0
 function pushValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     // quickform stores select fields as arrays, and the table schema will only accept
     // array values if the 'repeat' flag is set.
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName =& $element->getName();
     if (!$field['repeat']) {
         $val = $element->getValue();
         if (count($val) > 0) {
             return $val[0];
         } else {
             return null;
         }
     } else {
         return $element->getValue();
     }
 }
Example #22
0
 function save()
 {
     $db =& Dataface_DB::getInstance();
     $db->startTransaction();
     $formTool =& Dataface_FormTool::getInstance();
     foreach ($this->getFieldDefs() as $uri => $fieldDef) {
         $record =& $this->getRecord($uri);
         $formTool->pushField($record, $fieldDef, $this, $uri);
         if ($record->valueChanged($fieldDef['name'])) {
             $this->changed_fields[] = $uri;
         }
     }
     foreach (array_keys($this->records) as $uri) {
         $res = $this->records[$uri]->save(null, true);
         if (PEAR::isError($res)) {
             $db->rollbackTransaction();
             return $res;
         }
     }
     $db->commitTransaction();
     return true;
 }
Example #23
0
 /**
  * @brief Gets the list of meta values that is associated with the valuelist
  * for a particular field.  The idea is that the options in a valuelist
  * can be categorized into classes.  This returns those classes.
  * @param Dataface_Record &$record The record that is being edited.
  * 
  * @param array &$field The config array for the field being edited.
  *
  * @returns array The associative array of classes [key => class]
  */
 public static function getVocabularyClasses($record, &$field)
 {
     $res = Dataface_FormTool::_getVocabAndClasses($record, $field);
     return $res['options__classes'];
 }
Example #24
0
 function &pushValue(&$record, &$field, &$form, &$element, &$metaValues)
 {
     $table =& $record->_table;
     $formTool =& Dataface_FormTool::getInstance();
     $formFieldName = $element->getName();
     $val = $element->getValue();
     if ($field['repeat']) {
         //print_r(array_keys($val));
         // eg value array('value1'=>1, 'value2'=>1, ..., 'valueN'=>1)
         if (is_array($val)) {
             $out = array_keys($val);
         } else {
             $out = array();
         }
         //$res =& $s->setValue($fieldname, array_keys($val));
     } else {
         if (preg_match('/int/', @$field['Type'])) {
             $out = intval($val);
         } else {
             $out = $val;
         }
         //$res =& $s->setValue($fieldname, $val);
     }
     if (PEAR::isError($val)) {
         $val->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushValue.ERROR_PUSHING_VALUE', "Error pushing value for field '{$field['name']}' in QuickForm::pushWidget() on line " . __LINE__ . " of file " . __FILE__, array('name' => $field['name'], 'file' => __FILE__, 'line' => __LINE__)));
         return $val;
     }
     return $out;
 }
Example #25
0
 function handle(&$params)
 {
     import('Dataface/FormTool.php');
     import('Dataface/QuickForm.php');
     $formTool =& Dataface_FormTool::getInstance();
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $resultSet =& $app->getResultSet();
     $currentRecord =& $app->getRecord();
     $currentTable =& Dataface_Table::loadTable($query['-table']);
     if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) {
         $tabs = $currentTable->tabs($currentRecord);
         uasort($tabs, array($formTool, '_sortTabs'));
         list($query['--tab']) = array_keys($tabs);
     } else {
         if (count($currentTable->tabs($currentRecord)) <= 1) {
             unset($query['--tab']);
         }
     }
     $includedFields = null;
     // Null for all fields
     if (@$query['-fields']) {
         $includedFields = explode(' ', $query['-fields']);
     }
     /*
      *
      * Create the quickform for the current record.
      *
      */
     //$form = new Dataface_QuickForm($query['-table'], $app->db(),  $query);
     if ($resultSet->found() > @$query['-cursor']) {
         $form = $formTool->createRecordForm($currentRecord, false, @$query['--tab'], $query, $includedFields);
         /*
          * There is either a result to edit, or we are creating a new record.
          *
          */
         $res = $form->_build();
         if (PEAR::isError($res)) {
             error_log($res->toString() . implode("\n", $res->getBacktrace()));
             throw new Exception("An error occurred while building the edit form.  See error log for details.", E_USER_ERROR);
         }
         $formTool->decorateRecordForm($currentRecord, $form, false, @$query['--tab']);
         /*
          *
          * We need to add the current GET parameter flags (the GET vars starting with '-') so
          * that the controller knows to pass control to this method again upon form submission.
          *
          */
         foreach ($query as $key => $value) {
             if (strpos($key, '-') === 0) {
                 $form->addElement('hidden', $key);
                 $form->setDefaults(array($key => $value));
             }
         }
         /*
          * Store the current query string (the portion after the '?') in the form, so we 
          * can retrieve it after and redirect back to our original location.
          */
         $form->addElement('hidden', '-query');
         $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING']));
         /*
          * 
          * We have to deal with 3 cases.
          * 	1) The form has not been submitted.
          *	2) The form was submitted but didn't validate (ie: it had some bad input)
          * 	3) The form was submitted and was validated.
          *
          * We deal with Case 3 first...
          *
          */
         if ($formTool->validateRecordForm($currentRecord, $form, false, @$query['--tab'])) {
             /*
              *
              * The form was submitted and it validated ok.  We now process it (ie: save its contents).
              *
              */
             $app->clearMessages();
             $formTool->handleTabSubmit($currentRecord, $form, @$query['--tab']);
             if (!isset($query['--tab'])) {
                 // If we aren't using tabs we just do it the old way.
                 // (If it ain't broke don't fix it
                 $result = $form->process(array(&$form, 'save'));
             } else {
                 // If we are using tabs, we will use the formtool's
                 // session aware saving function
                 $result = $formTool->saveSession($currentRecord);
             }
             $success = true;
             $response =& Dataface_Application::getResponse();
             if (!$result) {
                 error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace());
                 throw new Exception("An error occurred while attempting to save the record.  See error log for details.", E_USER_ERROR);
             } else {
                 if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) {
                     if (Dataface_Error::isDuplicateEntry($result)) {
                         $app->addError($result);
                         $success = false;
                     } else {
                         error_log($result->toString() . implode("\n", $result->getBacktrace()));
                         throw new Exception("An error occurred while attempting to save the record.  See error log for details.", E_USER_ERROR);
                     }
                 } else {
                     if (Dataface_Error::isNotice($result)) {
                         $app->addError($result);
                         //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage();
                         $success = false;
                     }
                 }
             }
             if ($success) {
                 if (@$query['-response'] == 'json') {
                     //header('Content-type: text/html; charset="'.$app->_conf['oe'].'"');
                     $rvals = $currentRecord->strvals();
                     $rvals['__title__'] = $currentRecord->getTitle();
                     $rvals['__id__'] = $currentRecord->getId();
                     echo df_escape(json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved'))));
                     return;
                 }
                 import('Dataface/Utilities.php');
                 Dataface_Utilities::fireEvent('after_action_edit', array('record' => $form->_record));
                 /*
                  *
                  * The original query string will have the -new flag set.  We need to remove this 
                  * flag so that we don't redirect the user to create another new record.
                  *
                  */
                 $vals = $form->exportValues();
                 $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']);
                 $_SESSION['--last_modified_record_url'] = $form->_record->getURL();
                 $_SESSION['--last_modified_record_title'] = $form->_record->getTitle();
                 $msg = implode("\n", $app->getMessages());
                 //$msg =@$response['--msg'];
                 $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg);
                 if (preg_match('/[&\\?]-action=edit&/', $vals['-query']) and !$form->_record->checkPermission('edit')) {
                     $vals['-query'] = preg_replace('/([&\\?])-action=edit&/', '$1-action=view&', $vals['-query']);
                 } else {
                     if (preg_match('/[&\\?]-action=edit$/', $vals['-query']) and !$form->_record->checkPermission('edit')) {
                         $vals['-query'] = preg_replace('/([&\\?])-action=edit$/', '$1-action=view', $vals['-query']);
                     }
                 }
                 $vals['-query'] = preg_replace('/&?--msg=[^&]*/', '', $vals['-query']);
                 if (@$query['--lang']) {
                     $vals['-query'] .= '&--lang=' . $query['--lang'];
                 }
                 $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--saved=1&--msg=' . $msg;
                 /*
                  *
                  * Redirect the user to the appropriate record.
                  *
                  */
                 $app->redirect("{$link}");
             }
         }
         ob_start();
         $form->display();
         $out = ob_get_contents();
         ob_end_clean();
         if (count($form->_errors) > 0) {
             $app->clearMessages();
             $app->addError(PEAR::raiseError("Some errors occurred while processing this form: <ul><li>" . implode('</li><li>', $form->_errors) . "</li></ul>"));
         }
         $context = array('form' => $out);
         // Now let's add the tabs to the context
         $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']);
     } else {
         // no records were found
         $context = array('form' => '');
         if (isset($_SESSION['--last_modified_record_url'])) {
             $lastModifiedURL = $_SESSION['--last_modified_record_url'];
             $lastModifiedTitle = $_SESSION['--last_modified_record_title'];
             unset($_SESSION['--last_modified_record_title']);
             unset($_SESSION['--last_modified_record_url']);
             $app->addMessage(df_translate('Return to last modified record', 'No records matched your request.  Click <a href="' . $lastModifiedURL . '">here</a> to return to <em>' . df_escape($lastModifiedTitle) . '</em>.', array('lastModifiedURL' => $lastModifiedURL, 'lastModifiedTitle' => $lastModifiedTitle)));
         } else {
             $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request'));
         }
         $query['-template'] = 'Dataface_Main_Template.html';
     }
     if (isset($query['-template'])) {
         $template = $query['-template'];
     } else {
         if (@$query['-headless']) {
             $template = 'Dataface_Edit_Record_headless.html';
         } else {
             if (isset($params['action']['template'])) {
                 $template = $params['action']['template'];
             } else {
                 $template = 'Dataface_Edit_Record.html';
             }
         }
     }
     df_display($context, $template, true);
 }
Example #26
0
    function handle(&$params)
    {
        $app = Dataface_Application::getInstance();
        header('Content-type: text/html; charset=' . $app->_conf['oe']);
        $record =& $app->getRecord();
        $query =& $app->getQuery();
        if (isset($_REQUEST['-form-id'])) {
            $formid = $_REQUEST['-form-id'];
        } else {
            $formid = 'ajax-form-' . rand();
        }
        // First let's figure out what kind of form this is
        $form_type = @$_REQUEST['-form-type'];
        $form = null;
        if (isset($_REQUEST['-fields'])) {
            $fields = explode(',', $_REQUEST['-fields']);
        } else {
            $fields = null;
        }
        switch ($form_type) {
            case 'new':
                $form = df_create_new_record_form($query['-table'], $fields);
                $form->_build();
                break;
            case 'edit':
                $form = df_create_edit_record_form($query['-table'], $fields);
                break;
            case 'new_related_record':
                $form = df_create_new_related_record_form($record, $query['-relationship'], $fields);
                break;
            case 'existing_related_record':
                $form = df_create_existing_related_record_form($record, $query['-relationship']);
                break;
            case 'composite':
                import('Dataface/CompositeForm.php');
                $form = new Dataface_CompositeForm($fields);
                $form->build();
                break;
            default:
                @(include_once 'forms/' . $form_type . '.php');
                if (!class_exists('forms_' . $form_type)) {
                    return PEAR::raiseError('Could not find form of type "' . $form_type . '".', DATAFACE_E_ERROR);
                }
                $classname = 'forms_' . $form_type;
                $form = new $classname($fields);
                break;
        }
        // We want the form to be submitted to the embedded iframe
        $form->updateAttributes(array('target' => $formid . '-target', 'accept-charset' => $app->_conf['ie']));
        $formparams = preg_grep('/^-[^\\-].*/', array_keys($query));
        foreach ($formparams as $param) {
            $form->addElement('hidden', $param);
            $form->setDefaults(array($param => $query[$param]));
        }
        $form->addElement('hidden', '-form-id');
        $form->setDefaults(array('-form-id' => $formid));
        // Now that we have our form, we can do our thing with it.
        if ($form->validate()) {
            /*
             *
             * The form was submitted and it validated ok.  We now process it (ie: save its contents).
             *
             */
            $app->clearMessages();
            $result = $form->process(array(&$form, 'save'));
            $success = true;
            $response =& Dataface_Application::getResponse();
            if (!$result) {
                trigger_error("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace(), E_USER_ERROR);
                exit;
            } else {
                if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) {
                    if (Dataface_Error::isDuplicateEntry($result)) {
                        return $result;
                    } else {
                        trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR);
                        exit;
                    }
                } else {
                    if (Dataface_Error::isNotice($result)) {
                        $app->addError($result);
                        $success = false;
                    }
                }
            }
            if ($success) {
                import('Dataface/Utilities.php');
                Dataface_Utilities::fireEvent('after_action_ajax_form');
                $msg = implode("\n", $app->getMessages());
                //$msg =@$response['--msg'];
                $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg);
                // We need to output the success content.
                // This could be in any of the following formats:
                //	1. HTML --- actually not yet.. let's just do JSON
                //	2. JSON
                //	3. XML --- not yet.. just JSON for now.
                $targetid = @$_REQUEST['-target-id'];
                // This should:
                // 1. Get the target element.
                // 2. Go through the element's subtree and replace
                // 		values that have been changed.  How do we know what
                // 		values have been changed.
                //
                if (method_exists($form, 'htmlValues')) {
                    if (method_exists($form, 'changedFields')) {
                        $changed_fields = $form->changedFields();
                    } else {
                        $changed_fields = null;
                    }
                    // Convert the values to JSON
                    $changed_values = $form->htmlValues($changed_fields);
                    import('Services/JSON.php');
                    $json = new Services_JSON();
                    $changed_values_json = $json->encode($changed_values);
                } else {
                    $changed_values_json = '{}';
                }
                echo <<<END
<html><body><script language="javascript"><!--
\t
\t//self.onload =  function(){
\t\t//parent.handleEditableResponse('{$targetid}', {$changed_values_json});
\t\tvar targetel = parent.document.getElementById('{$targetid}');
\t\ttargetel.handleResponse('{$targetid}', {$changed_values_json});
\t\ttargetel.onclick=parent.makeEditable;
\t\ttargetel.onmouseover=targetel.old_onmouseover;
\t\ttargetel.edit_form.parentNode.removeChild(targetel.edit_form);
\t
\t//}
\t
\t
//--></script></body></html>
END;
                exit;
            }
        }
        import('Dataface/FormTool.php');
        $formTool = new Dataface_FormTool();
        ob_start();
        if (is_array($fields) and count($fields) == 1 and strpos($fields[0], '#') !== false) {
            $singleField = $fields[0];
        } else {
            $singleField = false;
        }
        $formTool->display($form, null, $singleField);
        $out = ob_get_contents();
        ob_end_clean();
        echo <<<END
\t\t
\t\t<div id="{$formid}-wrapper">
\t\t\t<iframe id="{$formid}-target" name="{$formid}-target" style="width:0px; height:0px; border: 0px"></iframe>
\t\t\t{$out}
\t\t</div>
END;
        if ($form->isSubmitted()) {
            // The form has already been submitted so we must be displaying some
            // errors.  We need to remove this stuff from inside the iframe
            // that we are going to be inside of, and place them on the page
            // in the correct place
            echo <<<END
<script language="javascript"><!--
var targetel = parent.document.getElementById('{$formid}-wrapper');
var sourceel = document.getElementById('{$formid}-wrapper');
targetel.innerHTML = sourceel.innerHTML;
//--></script>
END;
        }
        exit;
    }
Example #27
0
 function display()
 {
     $this->_build();
     $tableLabel = htmlspecialchars($this->_table->getLabel());
     df_display(array('tableLabel' => $tableLabel), 'Dataface_Search_Instructions.html');
     //parent::display();
     import('Dataface/FormTool.php');
     $ft =& Dataface_FormTool::getInstance();
     $ft->display($this, 'Dataface_FindForm.html');
     //echo '</div>';
 }
Example #28
0
 function display()
 {
     if ($this->_resultSet->found() > 0 || $this->_new) {
         $res = $this->_build();
         if (PEAR::isError($res)) {
             return $res;
         } else {
             //$this->displayTabs();
             if (!$this->_new and !Dataface_PermissionsTool::edit($this->_record)) {
                 $this->freeze();
             }
             if ($this->_new and !Dataface_PermissionsTool::checkPermission('new', $this->_table)) {
                 $this->freeze();
             }
             $formTool =& Dataface_FormTool::getInstance();
             if ($this->_new || Dataface_PermissionsTool::view($this->_record)) {
                 //echo $this->_renderer->toHtml();
                 echo $formTool->display($this);
             } else {
                 echo "<p>" . df_translate('scripts.GLOBAL.INSUFFICIENT_PERMISSIONS_TO_VIEW_RECORD', 'Sorry you have insufficient permissions to view this record.') . "</p>";
             }
             //parent::display();
         }
     } else {
         echo "<p>" . df_translate('scripts.GLOBAL.NO_RECORDS_MATCHED_REQUEST', 'No records matched your request.') . "</p>";
     }
 }
 /**
  * Displays the form.
  */
 function display()
 {
     if (!$this->_built) {
         $this->_build();
     }
     import('Dataface/FormTool.php');
     $formTool =& Dataface_FormTool::getInstance();
     echo $formTool->display($this, null, false, $this->_relationship->showTabsForAddNew());
     //$this->accept($this->_renderer);
     //echo $this->_renderer->toHtml(); //parent::display();
 }
Example #30
0
 function pushValue($val)
 {
     $this->element->setValue($val);
     $delegate = $this->record->_table->getDelegate();
     $widgetHandler = Dataface_FormTool::getInstance()->getWidgetHandler($this->field['widget']['type']);
     $filterValue = true;
     if ($delegate !== null and method_exists($delegate, $this->field['name'] . "__pushValue")) {
         /*
          *
          * The delegate defines a conversion method that should be used.
          *
          */
         $method = $this->field['name'] . '__pushValue';
         $val = $delegate->{$method}($this->record, $this->element);
         $filterValue = false;
     } else {
         if (isset($widgetHandler) and method_exists($widgetHandler, 'pushValue')) {
             $val = $widgetHandler->pushValue($this->record, $this->field, $this->form, $this->element, $this->new);
         }
     }
     if ($filterValue) {
         $evt = new stdClass();
         $evt->record = $this->record;
         $evt->field =& $this->field;
         $evt->form = $this->form;
         $evt->{'new'} = $this->{'new'};
         $evt->element = $this->element;
         $evt->metaValues = array();
         $evt->value = $val;
         Dataface_Application::getInstance()->fireEvent('FormTool::pushValue', $evt);
         $val = $evt->value;
     }
     return $val;
 }