I'm currently working on a custom module that communicates with a REST API. It is implemented as a new field type with a custom widget. The entire communication with the API works fine. The thing is that I'd like to save one part of the response in the database and I can't get it to work.
My code is here: https://github.com/stopopol/b2share/blob/master/b2share.module
Basically, I only need the information of one textfield ( $form['b2share_fieldset']['pid_button']) to be saved in the database, but the save function doesn't seem to be called.
I tried following this tutorial: http://getlevelten.com/blog/ian-whitcomb/defining-custom-field-types-drupal but I had no success yet. Maybe it's also important to mention that this field will be embedded in a content type together with plenty of other fields, therefore the communication with the rest api is done via ajax, but the values I get from the API should be stored together with the regular fields in the node form.
I only need someone to tell me what's missing from being able to save it. I've been stuck for days and can't figure it out.
Thanks.
EDIT: Ok. I narrowed it down and it seems like the problem is that
foreach ($items as $delta => $item)
never runs because the size of $items is always 0. I haven't found the reason yet. But will post my insights here.
EDIT2: Thanks for the helpful comments. I used hook_submit and was able to save values in the database, but drupal is complaining about the entity_Id and delta.
Example code I found suggests a function like this:
function b2share_form_alter(&$form, &$form_state, $form_id) {
$form['actions']['submit']['#submit'] = array('b2share_form_submit');
return $form;
}
function b2share_form_submit($form, &$form_state) {
drupal_set_message( 'submit handler is called' );
$values = array(
'url' => $form_state['values']['b2share_fieldset']['url'],
'pid' => $form_state['values']['b2share_fieldset']['pid']
);
$insert = db_insert('field_data_field_b2share')
-> fields(array(
'field_b2share_url' => $values['url'],
'field_b2share_pid' => $values['pid'],
//'entity_id' => 1,
//'delta' => 0,
//'language' => 'und',
))
->execute();
}
But apparently the functions needs to give more info or I am missing something somewhere else.
EDIT 3: Calling b2share_form_submit breaks the node form. The error message says: "The requested page "/.../node//current-revision" could not be found."
Logs say :
"Warning: Missing argument 3 for b2share_form_submit(),"
"Warning: Missing argument 4 for b2share_form_submit()"
EDIT 4: As described here in a comment (Do something after submit the form at hook_form_alter) this is the correct way to write the form_alter function:
function b2share_form_alter(&$form, &$form_state, $form_id) {
$form['#submit'][]='b2share_form_submit';
return $form;
}