[Решено] не создается таблица в бд

Главные вкладки

Аватар пользователя Bobby Bobby 11 августа 2010 в 18:09

Нужно что бы создавалась табличка в бд, где будет храниться пары айди: юзер - его начальник.

<?php
/**
 * Implementation of hook_schema().
 */
 
function dependencies_schema() {
  
    
$schema['dependencies'] = array(
                                        
'description' => t('The table for storing the employee hierarchy.'),
                                        
'fields' => array(
                                                 
'uid' => array(  
                                                       
'description' => t('Person'), 
                                                       
'type' => 'integer',
                                                       
'unsigned' => TRUE,
                                                       
'not null' => FALSE
                                                  
),
                                                  
'mid' => array(  
                                                       
'description' => t('Boss of a person'), 
                                                       
'type' => 'integer',
                                                       
'unsigned' => TRUE,
                                                       
'not null' => FALSE
                                                  
),
                                                  
'primary key' => array('uid''mid'),
                                         ),
                                           
    );
  
  return 
$schema;
}
?>

сильно не пеняйте, первый модуль, да и с пхп знаком с месяц...

Комментарии

Аватар пользователя Bobby Bobby 13 августа 2010 в 10:55

.install


<?php

/**
 * Implementation of hook_schema().
 */
 
function dependencies_schema() {
  
    
$schema['dependencies'] = array(
                                        
'description' => t('The table for storing the employee hierarchy.'),
                                        
'fields' => array(
                                                 
'uid' => array(  
                                                       
'description' => t('Person'), 
                                                       
'type' => 'integer',
                                                       
'unsigned' => TRUE,
                                                       
'not null' => FALSE,
                                                  ),
                                                  
'mid' => array(  
                                                       
'description' => t('Boss of a person'), 
                                                       
'type' => 'integer',
                                                       
'unsigned' => TRUE,
                                                       
'not null' => FALSE,
                                                  ),
                                                  
'primary key' => array('uid''mid'),
                                         ),
                                           
    );
  
  return 
$schema;
}

/**
 * Implementation of hook_install().
 */

function dependencies_install() {
  
    
drupal_install_schema('dependencies');
  
}

/**
 * Implementation of hook_uninstall().
 */

function dependencies_uninstall() {
  
//    variable_del('nodeaccess_workflow_');
  
    // Удаление таблиц
    
drupal_uninstall_schema('dependencies'); 
  
}

?>

.module //не дописан еще


<?php

define

('DEPENDENCIES_MAX_MANAGERS'5);

/**
 * Implementation of hook_perm().
 * 
 * 
 */
function dependencies_perm() {
    
    return array(
'manage dependencies');
    
}

/**
 * Implementation of hook_profile_alter().
 */
function dependencies_profile_alter(&$account) {
    
    
$values = array ('Test manager1''Test manager2''Test manager3');
    if (!isset(
$account->content['dependencies'])) {
        
$account->content['dependencies'] = array(
          
'#type' => 'user_profile_category',
          
'#title' => 'Dependencies',
        );
      }

      

$account->content['dependencies']['managers'] = array(
        
'#type' => 'user_profile_item',
        
'#title' => 'Managers',
        
'#value' => theme('item_list'$values),
        
'#weight' => '-5',
       
// '#attributes' => array('class' => 'profile-manager1'),
      
);
}

function 

dependencies_form_alter(&$form$form_state) {
    if (
$form['type']['#value'] != 'hierarchy') {
        return;
    }
  
    
$hierarchy dependencies_get_hierarchy();
    
$hierarchy dependencies_prepare_hierarchy($hierarchy);
     
    
//TODO probably replace with eployee uid, if provided
    
$counterFieldEmployee 0;
    
$descrFieldManager 'Dependencies sample field for manager';
                
    if (!
is_array($hierarchy)) {
        return;
    }
    foreach (
$hierarchy as $employee => $managers) {
        
        
$fieldsetEmployee 'fs_employee_'.$counterFieldEmployee;
        
$fieldsetManager 'fs_manager_'.$counterFieldEmployee;
        
$nameE 'field_employee_depend_'.$counterFieldEmployee;
        
        
$form[$fieldsetEmployee] = array('#type' => 'fieldset',
                  
'#title' => t($employee),
                  
'#weight' => '0',
        );
    
        
        
//$form[$fieldsetEmployee][$nameE] = make_userreference_field($empUid, $nameE, $titleFieldEmployee, $descrFieldEmployee);
        
        
        
$form[$fieldsetEmployee][$fieldsetManager] = array('#type' => 'fieldset',
                  
'#title' => t('Managers'),
                  
'#weight' => '0',
            );
        
        if (
is_array($managers)) {
            
            
$counterFieldManager 0;
            
//foreach ($managers as $manUid) {
            
for ($i 0$i DEPENDENCIES_MAX_MANAGERS$i++) {
                
                
$manUid = isset($managers[$i]) ? $managers[$i] : '';
                
$nameM 'field_manager_depend_'.$counterFieldEmployee.'_'.$i;
                
$titleFieldManager 'Manager ' $i;
                
$form[$fieldsetEmployee][$fieldsetManager][$nameM] = dependencies_make_userreference_field($manUid$nameM$titleFieldManager$descrFieldManager);
                
$counterFieldManager++;
                
            }
        }
        
$counterFieldEmployee++;
        
    }    
}

function 

dependencies_make_userreference_field($uid$name$title$descr) {
    
    
$default $uid ? array('uid' => $uid) : '';
    
$field = array(
          
'#theme' => 'content_multiple_values',
          
'#title' => t($title),
          
'#required' => '0',
          
'#description' => t($descr),
          
          
=> array(
                     
'#default_value' => $default,
                     
'#type' => 'userreference_autocomplete',
                     
'#value_callback' => 'userreference_autocomplete_value',
                     
'#title' => t($title),
                     
'#required' => '0',
                     
'#description' => t($descr),
                     
'#weight' => '0',
                     
'#delta' => '5',
                     
'#columns' => array('uid'),
                     
'#field_name' => $name,    
                     
'#type_name' => 'hierarchy',
                    ), 
          
        );
    
    return 
$field;
    
}

function 

dependencies_get_hierarchy() {
    
    
$hierarchy = array();
    
    
$sql 'select u.uid, u.mail, d.mid from {users} u left join {dependencies} d on u.uid = d.uid where u.status = 1';
    
$result db_query($sql);
    while (
$user db_fetch_array($result)) {
      
$hierarchy[] = $user;
    }
    
    return 
$hierarchy;
    
}

function 

dependencies_prepare_hierarchy($hierarchy) {
    
    
$result = array();
    foreach (
$hierarchy as $user) {
        
        if(
$user['mid']) {
            
$result[$user['uid']][] = $user['mid'];
        } else {
            
$result[$user['uid']][] = '';
        }
        
        
    }
    
    return 
$result;
    
}

/**
 * Implementation of hook_user().
 */ 
/*
function dependencies_user($type, &$edit, &$account, $category = NULL) {
    
  //user_user
    //$form_state = array();
    $uid = isset($account->uid) ? $account->uid : FALSE;
   // return user_edit_form($form_state, (isset($account->uid) ? $account->uid : FALSE), $edit);
  //user_user  
    
    _user_password_dynamic_validation();
  $admin = user_access('administer users');
    
// Managers section:
  $form['managers'] = array('#type' => 'fieldset',
    '#title' => t('Managers information'),
    '#weight' => -10,
  );
  // Only show name field when:  an admin user.
  if ($admin) {
    $form['managers']['name'] = array(
      '#type' => 'textfield',
    //'#type' => 'userreference',
      '#title' => t('manager'),
      '#default_value' => '8',
      '#description' => t('Choose a manager.'),
    );
  }
  return $form;
    
}
*/

/**
 * 
 * Implementation of hook_nodeapi().
 * 
 */
//function nodeaccess_workflow_nodeapi(&$node, $op, $arg = 0) {
//  switch ($op) {
//    case 'load':
//      $result = db_fetch_object(db_query('SELECT * FROM {workflow_node} WHERE nid = %d', $node->nid));
//      $node->wf_state = $result->sid;
//      break;
    /*case 'delete':
      db_query('DELETE FROM {node_access_example} WHERE nid = %d', $node->nid);
      break;
    case 'insert':
      db_query('INSERT INTO {node_access_example} (nid, private) VALUES (%d, %d)', $node->nid, $node->private);
      break;
    case 'update':
      db_query('UPDATE {node_access_example} SET private = %d WHERE nid = %d', $node->private, $node->nid);
      break;*/
//  }
//}

/**
 * System settings form for nodeaccess_workflow.
 */ /*
function nodeaccess_workflow_admin_settings() {
  
  
  $query = 'SELECT sid, state FROM {workflow_states} WHERE status = 1';
  $result = db_query($query);
  $stateList = array();
    
  while ($temp = db_fetch_array($result)) {

    $stateList[$temp['sid']] = $temp['state'];
    
  }
    
  $form['nodeaccess_workflow_priority'] = array(
    '#type' => 'weight',
    '#title' => t('Set node grants priority for Node Access Workflow'),
    '#default_value' => variable_get('nodeaccess_workflow_priority', 0),
    '#description' => t('If you are only using this access control module, you can safely ignore this. 
    If you are using multiple access control modules you can adjust the priority of this module.'),
  );
  
  $form['nodeaccess_workflow_datex'] = array(
    '#type' => 'date',
    '#title' => t('Set expiry date'),
    '#default_value' => '2010-05-11 23:00:00 +0400',
    '#description' => t('After this date users with the workflow state below cannot change their forms.'),
  );
  
  $form['nodeaccess_workflow_state'] = array(
    '#type' => 'select',
    '#options' => $stateList,
    '#title' => t('Set workflow state'),
    '#default_value' => array('12' => t('complete')),
    '#description' => t('Users with this workflow state cannot change their forms after the date above.'),
  );
  
  // Add additional submit processing
  //$form['#submit'][] = 'nodeaccess_workflow_admin_settings_submit';

  return system_settings_form($form);
}*/

/**
 * Implementation of hook_menu().
 */ /*
function dependencies_menu() {
  $items = array();

  $items['admin/settings/nodeaccess_workflow'] = array(
    'title' => 'Node access workflow settings',
    'description' => 'Configure Node Access Workflow.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodeaccess_workflow_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );
    
  return $items;
}
*/

?>
Аватар пользователя vitg vitg 16 августа 2010 в 5:33

Чтож. Тогда так. После выключения модуля есть дополнительно кнопка "удалить". Попробуйте её нажать для Вашего модуля. Затем снова установить. Возможно, MySQL выдаст ошибку, если так - пишем какую или решаем сами.

Аватар пользователя Bobby Bobby 16 августа 2010 в 10:52

"vitg" wrote:
После выключения модуля есть дополнительно кнопка "удалить". Попробуйте её нажать для Вашего модуля. Затем снова установить.

Уже раза 3 устанавливал и удалял...
"vitg" wrote:
Возможно, MySQL выдаст ошибку

в том от и дело что он ничего не выдает...
пользуюсь воркбенчем 5.2

Аватар пользователя vitg vitg 17 августа 2010 в 11:47

Я попробовал установить, сразу ошибка. Значит, ошибка в схеме.

user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unsigned DEFAULT NULL, `mid` unsigned DEFAULT NULL, `primary key` DEFAULT NU' at line 2 query: CREATE TABLE dependencies ( `uid` unsigned DEFAULT NULL, `mid` unsigned DEFAULT NULL, `primary key` DEFAULT NULL ) /*!40100 DEFAULT CHARACTER SET UTF8 */ in C:\homeserver\docs\drupal\includes\database.inc on line 550.

1) У тебя точно ошибка в схеме. ('primary_key' должен быть не на том уровне).
2) Подумай еще раз о структуре таблицы и назначении полей. Напиши, для чего используется каждое поле
3) Попробуй создать таблицу с другим именем.

Аватар пользователя Bobby Bobby 17 августа 2010 в 12:55

"vitg" wrote:
1) У тебя точно ошибка в схеме. ('primary_key' должен быть не на том уровне).
2) Подумай еще раз о структуре таблицы и назначении полей. Напиши, для чего используется каждое поле
3) Попробуй создать таблицу с другим именем.

хорошо..
"vitg" wrote:
Я попробовал установить, сразу ошибка

ооо...почему у меня тогда не выводит???