I am trying to create a module which defines an entity (called "didyouknow") with two fields: ID and content.
I have set it up to create new items of this custom entity, but I can't get it to work for editing existing items.
I'm trying to reuse the same form (didyouknow_item_form()
) for creating and editing, which works fine for creating, but for editing. The "%didyouknow" part in the URL is supposed to mean that the argument of didyouknow_item_edit()
is a loaded entity object, but it isn't; if I output it within that function using print_r()
, it outputs as "structure." This results in PHP outputting:
Notice: Trying to get property of non-object in didyouknow_item_form()
The code for the functions is below:
function didyouknow_menu() {
$items['admin/structure/didyouknow/manage/add'] = array(
'title' => 'Add Did You Know item',
'page callback' => 'didyouknow_add',
'access arguments' => array('create didyouknow'),
);
$items['admin/structure/didyouknow/manage/%didyouknow/edit'] = array(
'page callback' => 'didyouknow_item_edit',
'access arguments' => array('create didyouknow'),
'page arguments' => array(1),
);
return $items;
}
function didyouknow_item_edit($didyouknow){
return drupal_get_form('didyouknow_item_form', $didyouknow);
}
function didyouknow_add() {
$didyouknow = (object) array (
'pid' => '',
'type' => 'didyouknow',
'content' => '',
);
return drupal_get_form('didyouknow_item_form', $didyouknow);
}
function didyouknow_item_form($form, &$form_state, $didyouknow) {
$form['content'] = array(
'#type' => 'textarea',
'#title' => t('Content'),
'#default_value' => $didyouknow->content,
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
field_attach_form('didyouknow', $didyouknow, $form, $form_state);
return $form;
}
function didyouknow_item_form_validate($form, &$form_state) {
$didyouknow_submission = (object) $form_state['values'];
field_attach_form_validate('diyouknow', $didyouknow_submission, $form, $form_state);
}
function didyouknow_item_form_submit($form, &$form_state) {
$didyouknow_submission = (object) $form_state['values'];
field_attach_submit('didyouknow', $didyouknow_submission, $form, $form_state);
$didyouknow = didyouknow_item_save($didyouknow_submission);
$form_state['redirect'] = "admin/structure/didyouknow/manage/$didyouknow->pid/edit";
}
function didyouknow_item_save(&$didyouknow) {
return entity_get_controller('didyouknow')->save($didyouknow);
}