/** * Populates the form and field ids for all the fields for this form. * * If the form or fields don't exist yet they will be created. * @param I2CE_Form $form */ protected function setupForm($form) { if ($form->hasStaticAttribute("DBEntry_form_id") && $form->getStaticAttribute("DBEntry_form_id") > 0) { return; } $form_id = $this->getFormId($form->getName()); $form->setStaticAttribute("DBEntry_form_id", $form_id); $form_fields = array(); if (!$this->prepareSetupFormStatement("select")) { I2CE::raiseError("Unable to setup form select query!"); } $result = self::$prepared['setupForm']['select']->execute($form_id); I2CE::pearError($result, "Error setting up form in the database:"); while ($row = $result->fetchRow()) { $form_fields[$row->field] = $row->id; } foreach ($form as $key => $field) { if (!$field instanceof I2CE_FormField) { I2CE::raiseError("Bad field {$key} in form " . $form->getName()); continue; } if (!$field->isInDB()) { continue; } $field_id = $this->getFieldId($field->getName(), $field->getTypeString()); if ($field_id == null) { I2CE::raiseError("Bad field id for {$field}"); continue; } if (array_key_exists($field_id, $form_fields)) { $form_field_id = $form_fields[$field_id]; } else { /* * There can only be one field name assigned to a given form. If through an upgrade the * field type changes this can cause issues with the form_field table. * So, we delete any other rows in form_field that have the same field name as the one * we're adding before adding the new one. */ if (!$this->prepareSetupFormStatement("delete")) { I2CE::raiseError("Unable to setup form delete query!"); } if (!$this->prepareFormIDInsertStatement()) { I2CE::raiseError("Unable to setup form id insert query!"); } $deleted = self::$prepared['setupForm']['delete']->execute(array($form_id, $field->getName())); if (is_numeric($deleted) && $deleted > 0) { I2CE::raiseError("Deleted extra {$deleted} row(s) from form_field to block field name collisions. Form: {$form_id} Field: " . $field->getName() . " Field Type: " . $field->getTypeString() . " Field Class: " . get_class($field)); } else { I2CE::pearError($deleted, "Tried to delete invalid rows from form_field:"); } $form_field_id = $this->db->getBeforeID('form_field', 'id', true, true); $field_values = array($form_field_id, $form_id, $field_id); $res = self::$prepared['formIDInsert']->execute($field_values); $form_field_id = $this->db->getAfterID($form_field_id, 'form_field', 'id'); I2CE::pearError($res, "Error setting up form field in the database:"); } $field->setStaticAttribute("DBEntry_field_id", $field_id); $field->setStaticAttribute("DBEntry_form_field_id", $form_field_id); } }