/** * Change a field's type * */ protected function ___changeFieldtype(Field $field1) { if (!$field1->prevFieldtype) { throw new WireException("changeFieldType requires that the given field has had a type change"); } if ($field1->type instanceof FieldtypeMulti && !$field1->prevFieldtype instanceof FieldtypeMulti || $field1->prevFieldtype instanceof FieldtypeMulti && !$field1->type instanceof FieldtypeMulti) { throw new WireException("Cannot convert between single and multiple value field types"); } $field2 = clone $field1; $field2->name = $field2->name . "_PWTMP"; $field2->type->createField($field2); $field1->type = $field1->prevFieldtype; $schema1 = array(); $schema2 = array(); $result = $this->db->query("DESCRIBE `{$field1->table}`"); while ($row = $result->fetch_assoc()) { $schema1[] = $row['Field']; } $result->free(); $result = $this->db->query("DESCRIBE `{$field2->table}`"); while ($row = $result->fetch_assoc()) { $schema2[] = $row['Field']; } $result->free(); foreach ($schema1 as $key => $value) { if (!in_array($value, $schema2)) { if ($this->config->debug) { $this->message("changeFieldType loses table field '{$value}'"); } unset($schema1[$key]); } } $sql = "INSERT INTO `{$field2->table}` (`" . implode('`,`', $schema1) . "`) " . "SELECT `" . implode('`,`', $schema1) . "` FROM `{$field1->table}` "; try { $result = $this->db->query($sql); } catch (WireDatabaseException $e) { $result = false; } if (!$result) { $this->error("Field type change failed. Database reports: {$this->db->error}"); $this->db->query("DROP TABLE `{$field2->table}`"); return false; } $this->db->query("DROP TABLE `{$field1->table}`"); $this->db->query("RENAME TABLE `{$field2->table}` TO `{$field1->table}`"); $field1->type = $field2->type; // clear out the custom data, which contains settings specific to the Inputfield and Fieldtype foreach ($field1->getArray() as $key => $value) { // skip fields that may be shared among any fieldtype if (in_array($key, array('description', 'required', 'collapsed', 'notes'))) { continue; } // remove the custom field $field1->remove($key); } return true; }