1

I have a module which behaves much like question and answers. Each question needs to have a help image. So far, I have written the schema as this:

function mymodule_schema() {
  $schema(mymodule_questions) = array(
      'description' => 'Stores questions for my module',
      'fields' => array(
          'qid' => array(
            'type' => 'serial',
              'not null' => TRUE,
              'description' => 'Primary Key: Question ID.'
          ),
          'prompt' => array(
             'type' => 'text',
              'not null' => TRUE,
              'size' => 'normal',
              'description' => 'Question prompt',
              'length' => '1000'
          ),
          'option_type' => array(
              'type' => 'varchar',
              'not null' => TRUE,
              'description' => 'Option Type',
              'length' => '255'
          ),
          /* Image field schema goes here */
      ),
  );
}
?>

Now, I want to add an image field, i.e. a field where admins can upload images to be shown with each question. What should be the schema for this field? Should I use the Field API in the schema (is that possible?)? If yes, how?

Thanks.

Kaustav Das Modak

1

To be able to integrate with field API, you would need to declare your custom data thing as a fieldable entity. This is possibly, but it is quite a bit of work and then you'll have to add the field in a install hook.

What you can do as well is simply add a single 'fid' integer column to your table, add a form element of #type 'managed_file' to your form, which will automatically save the file for you and create an entry in the file_managed table. You can then simply reference the fid (file id) of that object. Also note that you need to call file_usage_add() so that the managed file knows that it is in use. When your object is deleted, use file_usage_delete() then the file will automatically be removed.

This is exactly what is done in Drupal 7 for profile pictures, have a look at user_save() for an example.

  • Got it. I was trying to use Field API but still wanted to retain some referencing control. Adding the 'fid' column helped. Thanks @Berdir – kaustavdm Oct 15 '11 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.