Question

I have a custom form module with a field of type 'managed_file', and an entry in the database pointing to an image's filepath.

I would like to pre-load this image into the 'managed_file' field when the form is first displayed.

I've tried assigning #default_value to the image's filepath, but this does nothing.

What is the best way to go about doing this?

$result = db_query('SELECT n.companyName, n.billingEmail, n.leadEmail, n.contactEmail, n.contactEmail,
                        n.url, n.description, n.companyLogo, n.promoVideoUrl
        FROM {leads_client} n WHERE n.clientId = :uid', array(':uid' => $GLOBALS['user']->uid));    

    $row = $result->fetchAssoc();


$form['company_logo'] = array(
  '#type' => 'managed_file',
  '#title' => t('Company Logo'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#upload_location' => 'public://uploads/',
  '#default_value' => $row['companyLogo'],
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(1024*1024*1024),
  ),
);
Was it helpful?

Solution

The default value needs to be a file ID (the 'managed' part of 'managed_file' means Drupal's taking care of the file for you in the file_managed table, and any reference to it needs to be via the ID).

If you're currently saving the URL in companyLogo you might want to consider changing that column to an int and saving the file ID instead. That way your existing code will work.

If you need to get the URI at any point you can load the file up:

$uri = file_load($row['companyLogo'])->uri;

And if you need the full URL from that:

$url = file_create_url($uri);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top