You are here

function context_ui_item in Context 5

Provides simple operations (load/save) on any context-item associations. context_ui_item() will automatically sync the database with the context object provided when saving. Any associations that exist on the object that are absent from the database will be inserted, and any associations that are missing will be removed from the database.

Parameters

$op: Operation to perform on a context. May be either load or save.

$context: A context object with item associations.

Return value

Load returns a context object with item associations. Save returns true on success and false on failure.

1 call to context_ui_item()
context_ui_context in context_ui/context_ui.module
Provides simple operations (load/insert/update/etc.) on a core context space/key/value definition.

File

context_ui/context_ui.module, line 815

Code

function context_ui_item($op = 'load', $context) {
  if ($context->cid) {
    switch ($op) {
      case 'load':
        $result = db_query("SELECT * FROM {context_ui_item} WHERE cid = %d", $context->cid);
        while ($row = db_fetch_object($result)) {
          $context->{$row->type}[$row->id] = $row->id;
        }
        return $context;
      case 'save':
        $current = new stdClass();
        $current->cid = $context->cid;
        $current = context_ui_item('load', $current);
        foreach (context_ui_types() as $type) {

          // Delete any stale associations
          if (isset($current->{$type}) && is_array($current->{$type})) {
            foreach ($current->{$type} as $id) {
              $delete = false;
              if (!is_array($context->{$type})) {
                $delete = true;
              }
              else {
                if (array_search($id, $context->{$type}) === false) {
                  $delete = true;
                }
              }
              if ($delete) {
                $result = db_query("DELETE FROM {context_ui_item} WHERE cid = %d AND type = '%s' AND id = '%s'", $context->cid, $type, $id);
              }
            }
          }

          // Add/update any missing associations
          if (isset($context->{$type}) && is_array($context->{$type})) {
            foreach ($context->{$type} as $id) {
              $update = false;
              if (!(isset($current->{$type}) && is_array($current->{$type}))) {
                $update = true;
              }
              else {
                if (array_search($id, $current->{$type}) === false) {
                  $update = true;
                }
              }
              if ($update) {
                $result = db_query("REPLACE INTO {context_ui_item} (cid, type, id) VALUES(%d, '%s', '%s')", $context->cid, $type, $id);
              }
            }
          }
        }
        return true;
        break;
    }
  }
  return false;
}