We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 11793
    • 49 Posts
    Any ideas on best practice for using the methods buildSelect, buildInput, buildSelectOptions, buildTextArea and createOptions from the Class MakeForm?

    Specifically, I’m looking at building select lists from linked tables.
    • Quote from: hardboiled at Jul 08, 2009, 01:24 AM

      Any ideas on best practice for using the methods buildSelect, buildInput, buildSelectOptions, buildTextArea and createOptions from the Class MakeForm?

      Specifically, I’m looking at building select lists from linked tables.
      Actually, the build*() methods, except buildForm(), are all internal methods of the class. Let me provide an example of how you might use this class; this is a snippet I wrote for a custom event calendar management application (targeted at MODx 0.9.x) that generates (and processes) a form for adding/editing events using MakeForm [note the $calendarOptions variable that is created from a set of custom data records]:
      <?php
      /* if the user is not logged into the manager, send them to the unauthorized page */
      if (!isset ($_SESSION['mgrValidated']) || !$_SESSION['mgrValidated']) {
          $modx->sendUnauthorizedPage();
      }
      
      /* include xPDO and add the modx and modx.calendar model packages */
      include_once ($modx->config['base_path'] . 'xpdo/xpdo.class.php');
      $dsn= $GLOBALS['database_type'] . ':host=' . $modx->db->config['host'] . ';dbname=' . str_replace('`', '', $modx->db->config['dbase']);
      $xpdo= new xPDO($dsn, $modx->db->config['user'], $modx->db->config['pass'], $modx->db->config['table_prefix']);
      $xpdo->setPackage('modx', MODX_BASE_PATH . 'model/');
      $xpdo->setPackage('modx.calendar', MODX_BASE_PATH . 'model/');
      //$xpdo->setDebug(true);
      $xpdo->setLogLevel(XPDO_LOG_LEVEL_ERROR);
      $xpdo->setLogTarget('HTML');
      
      $eventId= isset ($_REQUEST['event']) ? $_REQUEST['event'] : 0;
      $eventInstanceId= isset ($_REQUEST['instance']) ? $_REQUEST['instance'] : 0;
      
      $pageManageEvents= isset ($pageManageEvents) ? $pageManageEvents : $modx->documentObject['parent'];
      
      /* load the MakeForm class and get an instance of it */
      $xpdo->loadClass('form.MakeForm', XPDO_CORE_PATH, true, true);
      $oForm= new MakeForm($xpdo);
      
      $event= null;
      $eventCalendarId= 0;
      $eventCalendarXref= null;
      if (!intval($eventId)) {
          /* present a new event form */
          $event= $xpdo->newObject('modCalendarEvent');
      } else {
          /* present an existing event form for editing */
          if (!$event= $xpdo->getObject('modCalendarEvent', $eventId)) {
              $modx->setPlaceholder('message', '<p class="error">Could not load requested event: ' . print_r($eventId, true) . '</p>');
          }
      }
      
      $formOutput= '';
      if ($event) {
          $includeFields= array (
              'summary',
              'description',
              'website',
              'cost',
              'allday',
              'status',
              'dtstart',
              'dtend',
              'recurs',
              'rrule',
          );
          $oForm->setFormObject($event, array_diff(array_keys($event->_fields), $includeFields));
          $eventCalendarId= 1;
          if ($eventCalendars= $event->getMany('Calendars')) {
              $eventCalendar= reset($eventCalendars);
              $eventCalendarId= $eventCalendar->get('calendar');
              while ($nextCalendar= next($eventCalendars)) $nextCalendar->remove();
          }
          $eventCalendarId= isset ($_POST['calendar']) && intval($_POST['calendar'])
              ? $intval($_POST['calendar'])
              : $eventCalendarId;
          if (isset ($_POST['save']) || isset ($_POST['save_x'])) {
              $dtStartElement= 'modCalendarEvent--' . (intval($eventId) ? $eventId : '') . '-dtstart';
              $dtEndElement= 'modCalendarEvent--' . (intval($eventId) ? $eventId : '') . '-dtend';
              if (isset ($_POST[$dtStartElement])) {
                  $_POST[$dtStartElement]= preg_replace('/(\d{2})\/(\d{2})\/(\d{4})(.*)/', '$3-$1-$2$4', $_POST[$dtStartElement]);
              }
              if (isset ($_POST[$dtEndElement])) {
                  $_POST[$dtEndElement]= preg_replace('/(\d{2})\/(\d{2})\/(\d{4})(.*)/', '$3-$1-$2$4', $_POST[$dtEndElement]);
              }
              if (!$oForm->processForm($event, $_POST)) {
                  $modx->setPlaceholder('message', '<p class="error">Could not save event: ' . print_r($eventId, true) . '</p>');
              }
              $eventId= $event->get('id');
              if ($eventCalendarId) {
                  $exists= false;
                  if ($eventCalendarXrefs= $xpdo->getCollection('modCalendarEventLink', array ('event' => $eventId))) {
                      foreach ($eventCalendarXrefs as $xrefKey => $xref) {
                          if ($xref->get('calendar') == $eventCalendarId) {
                              $exists= true;
                              continue;
                          }
                          $xref->remove();
                      }
                  }
                  if (!$exists) {
                      $eventCalendarXref= $xpdo->newObject('modCalendarEventLink');
                      $eventCalendarXref->set('calendar', $eventCalendarId);
                      $eventCalendarXref->set('event', $eventId);
                      $eventCalendarXref->save();
                  }
              }
              if (intval($pageManageEvents)) {
                  header('HTTP/1.1 302 Found');
                  $modx->sendRedirect($modx->makeUrl($pageManageEvents));
              } else {
                  $modx->setPlaceholder('message', '<p class="info">Event saved successfully.</p>');
              }
          }
          elseif (isset ($_POST['confirm_remove']) || isset ($_POST['confirm_remove_x'])) {
              header('HTTP/1.1 302 Found');
              $modx->sendRedirect($modx->makeUrl($modx->documentIdentifier, '', 'event='.$eventId.'&remove=1'));
          }
          elseif (isset ($_REQUEST['remove']) || isset ($_REQUEST['remove_x'])) {
              $event->remove();
              header('HTTP/1.1 302 Found');
              $modx->sendRedirect($modx->makeUrl($pageManageEvents));
          }
      
      
          /* get a collection of calendar objects to build the select options list */
          $calendarOptions= '';
          if ($calendars= $xpdo->getCollection('modCalendar')) {
              $calendarArray= array ();
              foreach ($calendars as $calendarId => $calendar) {
                  $calendarArray[$calendarId]= $calendar->get('name');
              }
              $calendarOptions= $oForm->createOptions($calendarArray, $eventCalendarId);
          }
      
          /* register the datetimepicker js */
          $modx->regClientStartupScript('assets/js/datetimepicker/datetimepicker.js');
      
          /* prepare additional form elements to supplement those automatically populated from the object */
          $formOverlay= array (
              'event' => array (
                  'type' => 'hidden',
                  'name' => 'event',
                  'value' => $eventId,
              ),
              'calendar' => array (
                  'type' => 'select',
                  'label' => 'Calendar',
                  'name' => 'calendar',
                  'options' => $calendarOptions,
              ),
              'save' => array (
                  'type' => 'submit',
                  'label' => 'Save',
                  'name' => 'save',
                  'value' => 'Save'
              ),
              'confirm_remove' => array (
                  'type' => 'submit',
                  'label' => 'Delete',
                  'name' => 'confirm_remove',
                  'value' => 'Delete'
              ),
          );
          $oForm->setFormElements($formOverlay, true);
          $descriptionElement= 'modCalendarEvent--' . (intval($eventId) ? $eventId : '') . '-description';
          $statusElement= 'modCalendarEvent--' . (intval($eventId) ? $eventId : '') . '-status';
          $dtStartElement= 'modCalendarEvent--' . (intval($eventId) ? $eventId : '') . '-dtstart';
          $dtEndElement= 'modCalendarEvent--' . (intval($eventId) ? $eventId : '') . '-dtend';
          $oForm->formElements[$descriptionElement]['type']= 'textarea';
          $oForm->formElements[$descriptionElement]['style']= 'width: 100%; height: 150px;';
          $oForm->formElements[$statusElement]['name']= $statusElement;
          $oForm->formElements[$statusElement]['type']= 'select';
          $oForm->formElements[$statusElement]['label']= 'Status';
          $oForm->formElements[$statusElement]['size']= 1;
          $oForm->formElements[$statusElement]['style']= 'width:180px;';
          $oForm->formElements[$statusElement]['options']= $oForm->createOptions(array ('CONFIRMED' => 'Confirmed', 'TENTATIVE' => 'Tentative', 'CANCELLED' => 'Cancelled'), $event->get('status'), true);
          $oForm->formElements[$dtStartElement]['label']= 'Event Start Date';
          $oForm->formElements[$dtStartElement]['extra']= '<span><a href="javascript:NewCal(\'' . $dtStartElement .'\',\'mmddyyyy\',true,12,\'dropdown\',true)" title="Choose date with calendar"><img src="assets/images/calendar.gif" alt="[ calendar ]" /></a></span>';
          $oForm->formElements[$dtStartElement]['size']= 25;
          $oForm->formElements[$dtEndElement]['label']= 'Event End Date';
          $oForm->formElements[$dtEndElement]['extra']= '<span><a href="javascript:NewCal(\'' . $dtEndElement .'\',\'mmddyyyy\',true,12,\'dropdown\',true)" title="Choose date with calendar"><img src="assets/images/calendar.gif" alt="[ calendar ]" /></a></span>';
          $oForm->formElements[$dtEndElement]['size']= 25;
      
          /* build the form output */
          $formOutput.= $oForm->buildForm();
      
          /* if any errors occurred, add them to the message placeholder
          if (!empty($oForm->errorMsg)) $modx->setPlaceholder('message', $modx->getPlaceholder('message') . $oForm->errorMsg);
      }
      return $formOutput;
      ?>


      It’s probably better that I let the example speak for itself, rather than try to explain everything, but feel free to ask additional questions.