I have a content type "event" with a field called "field_pricelist". It's a dropdown with no values, I add the values when I alter the form. The values come from a custom table (install / schema) in my database. I want to save this custom value on insert/update. My code works but I don't think it's the best way to save/update a custom field.. Any suggestions?
function TableManager_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'event_node_form') {
global $user;
$query = db_select('pricelist', 'p');
$query->fields('p');
$query->condition('user_id', $user->uid,'=');
$results = $query->execute()->fetchAll();
$query2 = db_select('field_data_field_pricelist', 'd');
$query2->fields('d');
$query2->condition('entity_id', $form['nid']['#value'],'=');
$results2 = $query2->execute()->fetchAll();
$dropdown_array = array();
foreach ($results as $r) {
$form['field_pricelist']['und']['#options'][$r->pricelist_id] = $r->pricelist_name;
}
$form['field_pricelist']['und']['#default_value']['0'] = $results2['0']->field_pricelist_value;
$form['#submit'][] = "TableManager_form_submit";
}
}
function TableManager_form_submit($form, &$form_state) {
global $user;
$nid = $form_state['values']['nid'];
$pricelist_id = $form_state['values']['field_pricelist']['und']['0']['value'];
$query = db_update('field_data_field_pricelist');// Table name no longer needs {}
$query->fields(array('field_pricelist_value' => $pricelist_id));
$query->condition('entity_id', $nid, '=');
$query->execute();
}