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; }
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; }
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; }
/** * @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')); }
/** * @brief Initializes the radio module and registers all of the event listener. * */ function __construct() { $app = Dataface_Application::getInstance(); if (!class_exists('Dataface_FormTool')) { // If the formtool is not loaded then we don't want to load it here... we'll just register // the _registerWidget() method to run as soon as the FormTool is loaded. $app->registerEventListener('Dataface_FormTool::init', array($this, '_registerWidget')); } else { // Register the radio widget with the form tool so that it responds to widget:type=radio $this->_registerWidget(Dataface_FormTool::getInstance()); } }
/** * @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'); }
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())); } } }
/** * @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; } }
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(); } }
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); }
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; }
function pushValue($val) { $this->element->setValue($val); $delegate = $this->record->_table->getDelegate(); $widgetHandler = Dataface_FormTool::getInstance()->getWidgetHandler($this->field['widget']['type']); 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); } else { if (isset($widgetHandler) and method_exists($widgetHandler, 'pushValue')) { $val = $widgetHandler->pushValue($this->record, $this->field, $this->form, $this->element, $this->new); } } return $val; }
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>"; } }
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; }
function handle() { import('Dataface/FormTool.php'); import('Dataface/QuickForm.php'); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $new = true; $currentRecord = new Dataface_Record($query['-table'], array()); $currentTable =& Dataface_Table::loadTable($query['-table']); if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) { list($query['--tab']) = array_keys($currentTable->tabs($currentRecord)); } else { if (count($currentTable->tabs($currentRecord)) <= 1) { unset($query['--tab']); } } $formTool =& Dataface_FormTool::getInstance(); $form = $formTool->createRecordForm($currentRecord, true, @$query['--tab'], $query); //$form = new Dataface_QuickForm($query['-table'], $app->db(), $query, '',$new); $res = $form->_build(); if (PEAR::isError($res)) { trigger_error($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); } $formTool->decorateRecordForm($currentRecord, $form, true, @$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, true, @$query['--tab'])) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $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, true); } $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { trigger_error("Error occurred in save: " . mysql_error($app->db()) . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { $success = false; $form->_errors[] = $result->getMessage(); } else { //echo "not dup entry"; exit; trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); $success = false; } } } if ($success) { if (@$query['-response'] == 'json') { //header('Content-type: text/json; charset="'.$app->_conf['oe'].'"'); $rvals = $currentRecord->strvals(); $rvals['__title__'] = $currentRecord->getTitle(); echo json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved'))); exit; } import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_new', array('record' => $currentRecord)); /* * * Since the form created a new record, then it makes more sense to redirect to this newly * created record than to the old record. We used the 'keys' of the new record to generate * a redirect link. * */ //$query = $form->_record->getValues(array_keys($form->_record->_table->keys())); $currentRecord->secureDisplay = false; if ($currentRecord->checkPermission('edit')) { $nextAction = 'edit'; } else { $nextAction = 'view'; } $url = $currentRecord->getURL(array('-action' => $nextAction)); $msg = implode("\n", $app->getMessages()); //@$response['--msg']; $msg = urlencode(trim(Dataface_LanguageTool::translate("Record successfully saved", "Record successfully saved.") . "\n" . $msg)); if (strpos($url, '?') === false) { $url .= '?'; } $link = $url . '&--msg=' . $msg; header("Location: {$link}"); exit; } } ob_start(); $form->setDefaults($_GET); $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); $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']); df_display($context, 'Dataface_New_Record.html', true); }
/** * 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(); }
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>'; }
/** * This test is to verify a fix to the following bug report: * http://bugs.weblite.ca/view.php?id=841 * * When editing a join record but the join record doesn't exist yet, it would * report an error. This was traced back to the behavior of Dataface_Record::getJoinRecord() * so that it returns a record even if that record hasn't been created yet. * Dataface_FormTool::createRecordForm() depended on this null value to signal when * it should create a new record form rather than an edit record form for the tab. */ function test841() { $rec = df_get_record('test841', array('test841_id' => '=1')); $this->assertTrue($rec instanceof Dataface_Record, 'Could not find record in test841 table but it should exist'); $join = $rec->getJoinRecord('test841_join'); $this->assertTrue($join instanceof Dataface_Record, 'Failed to load join record but it should be there.'); $this->assertEquals(1, $join->val('test841_id'), 'Join record primary key does not match parent record.'); $this->assertEquals('join value', $join->val('join_varchar_field'), 'Join record did not load its field values correctly.'); import('Dataface/QuickForm.php'); import('Dataface/FormTool.php'); $ft = Dataface_FormTool::getInstance(); $form = $ft->createRecordForm($rec, false, 'test841_join'); $this->assertTrue($form instanceof Dataface_QuickForm, 'Join form should be an instance of Dataface_QuickForm.'); $formRec = $form->_record; $this->assertTrue($formRec instanceof Dataface_Record, 'Join form should be based on a Dataface_Record object.'); $this->assertEquals('test841_join', $formRec->table()->tablename, 'Join form record has wrong table name'); $this->assertEquals(false, $form->_new, 'Join form for id 1 exists so the form should be an edit record form.'); // Now for the one where no join yet exists. $rec = df_get_record('test841', array('test841_id' => '=2')); $this->assertTrue($rec instanceof Dataface_Record, 'Could not find record but it should exist.'); $join = $rec->getJoinRecord('test841_join'); $this->assertTrue($join instanceof Dataface_Record, 'Failed to load join record.'); $this->assertEquals(2, $join->val('test841_id'), 'Join record value primary key does not match.'); $this->assertEquals(null, $join->val('join_varchar_field'), 'Join record shouldnt have a value yet because it doesnt exist in the database.'); // Now to request a null value if the record doesn't exist yet $join2 = $rec->getJoinRecord('test841_join', true); $this->assertEquals(null, $join2, 'getJoinRecord() should have returned null when record doesnt exist - and the 2nd parameter was set.'); $form = $ft->createRecordForm($rec, false, 'test841_join'); $this->assertTrue($form instanceof Dataface_QuickForm, 'Join form should be a Dataface_QuickForm record.'); $this->assertEquals('test841_join', $form->_record->table()->tablename, 'Join table edit form is working on the wrong record.'); $this->assertEquals(true, $form->_new, 'Join form for id 2 should be a new record form because the record doesnt exist yet.'); }
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; }
function pushValue(&$record, &$field, &$form, &$element, &$metaValues) { // The widget is a file upload widget $formTool =& Dataface_FormTool::getInstance(); $formFieldName = $element->getName(); $table =& $record->_table; $app =& Dataface_Application::getInstance(); if ($element->isUploadedFile()) { // a file has been uploaded $val =& $element->getValue(); // eg: array('tmp_name'=>'/path/to/uploaded/file', 'name'=>'filename.txt', 'type'=>'image/gif'). if (PEAR::isError($val)) { $val->addUserInfo(df_translate('scripts.Dataface.QuickForm.pushValue.ERROR_GETTING_ELEMENT_VALUE', "Error getting element value for element {$field['name']} in QuickForm::pushField on line " . __LINE__ . " of file " . __FILE__, array('fieldname' => $field['name'], 'line' => __LINE__, 'file' => __FILE__))); trigger_error($val->toString(), E_USER_ERROR); return $val; } if ($table->isContainer($field['name'])) { $src = $record->getContainerSource($field['name']); if (strlen($record->strval($field['name'])) > 0 and file_exists($src) and is_file($src) and !is_dir($src)) { // delete the old file. if (!is_writable($src)) { trigger_error("Could not save field '" . $field['name'] . "' because there are insufficient permissions to delete the old file '" . $src . "'. Please check the permissions on the directory '" . dirname($src) . "' to make sure that it is writable by the web server." . Dataface_Error::printStackTrace(), E_USER_ERROR); } @unlink($src); } // Make sure that the file does not already exist by that name in the destination directory. $savepath = $field['savepath']; $filename = basename($val['name']); // we use basename to guard against maliciously named files. $filename = str_replace(chr(32), "_", $filename); $matches = array(); if (preg_match('/^(.*)\\.([^\\.]+)$/', $filename, $matches)) { $extension = $matches[2]; $filebase = $matches[1]; } else { $extension = ''; $filebase = $filename; } while (file_exists($savepath . '/' . $filename)) { $matches = array(); if (preg_match('/(.*)-{0,1}(\\d+)$/', $filebase, $matches)) { $filebase = $matches[1]; $fileindex = intval($matches[2]); } else { $fileindex = 0; // We should just leave the filebase the same. //$filebase = $filename; } if ($filebase[strlen($filebase) - 1] == '-') { $filebase = substr($filebase, 0, strlen($filebase) - 1); } $fileindex++; $filebase = $filebase . '-' . $fileindex; $filename = $filebase . '.' . $extension; } if (!is_writable($field['savepath'])) { trigger_error(df_translate('scripts.Dataface.QuickForm.pushValue.ERROR_INSUFFICIENT_DIRECTORY_PERMISSIONS', "Could not save field '" . $field['name'] . "' because there are insufficient permissions to save the file to the save directory '" . $field['savepath'] . "'. Please Check the permissions on the directory '" . $field['savepath'] . "' to make sure that it is writable by the web server.", array('fieldname' => $field['name'], 'savepath' => $field['savepath'])) . Dataface_Error::printStackTrace(), E_USER_ERROR); } move_uploaded_file($val['tmp_name'], $field['savepath'] . '/' . $filename); chmod($field['savepath'] . '/' . $filename, 0744); $out = $filename; } else { if (file_exists($val['tmp_name'])) { if (!@$app->_conf['multilingual_content']) { // THis is a bit of a hack. If we are using multilingual // content, then Dataface_DB will parse every query // before sending it to the database. It is better if // that query is short - so we only pass the whole value // if we are not parsing the query. $out = file_get_contents($val['tmp_name']); } else { // If we are parsing the query, then we will just store // the path to the blob. $out = $val['tmp_name']; } } else { $out = null; } } if (is_array($metaValues)) { if (isset($field['filename'])) { // store the file name in another field if one is specified $metaValues[$field['filename']] = $val['name']; } if (isset($field['mimetype'])) { // store the file mimetype in another field if one is specified $metaValues[$field['mimetype']] = $val['type']; } } return $out; } if ($table->isContainer($field['name'])) { return $record->val($field['name']); } return null; }
function handle() { import('Dataface/FormTool.php'); import('Dataface/QuickForm.php'); $formTool =& Dataface_FormTool::getInstance(); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $new = true; $includedFields = null; // Null for all fields if (@$query['-fields']) { $includedFields = explode(' ', $query['-fields']); } $currentRecord = new Dataface_Record($query['-table'], array()); $currentTable =& Dataface_Table::loadTable($query['-table']); $app->setPageTitle(df_translate('actions.new.label', 'New ' . $currentTable->getSingularLabel(), array('tableObj' => $currentTable))); 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']); } } $form = $formTool->createRecordForm($currentRecord, true, @$query['--tab'], $query, $includedFields); //$form = new Dataface_QuickForm($query['-table'], $app->db(), $query, '',$new); $res = $form->_build(); if (PEAR::isError($res)) { error_log($res->toString() . Dataface_Error::printStackTrace()); throw new Exception("Error occurred while building the new record form. See error log for details.", E_USER_ERROR); } $formTool->decorateRecordForm($currentRecord, $form, true, @$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, true, @$query['--tab'])) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $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, true); } $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { throw new Exception("Error occurred in save: " . xf_db_error($app->db()), E_USER_ERROR); } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { $success = false; $form->_errors[] = $result->getMessage(); } else { //echo "not dup entry"; exit; error_log($result->toString() . "\n" . implode("\n", $result->getBacktrace())); throw new Exception("An error occurred while attempting to save the record. See server error log for details.", E_USER_ERROR); } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); $success = false; } } } if ($success) { if (@$query['-response'] == 'json') { //header('Content-type: application/json; charset="'.$app->_conf['oe'].'"'); $rvals = $currentRecord->strvals(); $rvals['__title__'] = $currentRecord->getTitle(); $rvals['__id__'] = $currentRecord->getId(); echo 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_new', array('record' => $currentRecord)); /* * * Since the form created a new record, then it makes more sense to redirect to this newly * created record than to the old record. We used the 'keys' of the new record to generate * a redirect link. * */ //$query = $form->_record->getValues(array_keys($form->_record->_table->keys())); $currentRecord->secureDisplay = false; if ($currentRecord->checkPermission('edit')) { $nextAction = 'edit'; } else { $nextAction = 'view'; } $urlParams = array('-action' => $nextAction); // Some parameters we'll want to pass to our edit action // so that the edit form is consistent with the display // of the new form. E.g. if the form was headless or // has only particular fields, then the edit form should // include the same fields and also be headless. $passedParams = array('-fields', '-headless', '-xf-hide-fields'); foreach ($passedParams as $passedParam) { if (@$query[$passedParam]) { $urlParams[$passedParam] = $query[$passedParam]; } } $url = $currentRecord->getURL($urlParams); if (@$query['--lang']) { $url .= '&--lang=' . $query['--lang']; } //echo $url;exit; $msg = implode("\n", $app->getMessages()); //@$response['--msg']; $msg = urlencode(trim(Dataface_LanguageTool::translate("Record successfully saved", "Record successfully saved.") . "\n" . $msg)); if (strpos($url, '?') === false) { $url .= '?'; } $link = $url . '&--saved=1&--msg=' . $msg; //echo "$link";exit; $app->redirect("{$link}"); } else { $app->addHeadContent('<meta id="quickform-error" name="quickform-error" value="Save failed"/>'); } } ob_start(); $form->setDefaults($_GET); $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); $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']); if (isset($query['-template'])) { $template = $query['-template']; } else { if (@$query['-headless']) { $template = 'Dataface_New_Record_headless.html'; } else { $template = 'Dataface_New_Record.html'; } } df_display($context, $template, true); }