3

I have a content entity type, and I would like to have an 'Upload file' field. I have declared the field in my Entity class

$fields['file'] = BaseFieldDefinition::create('file')
    ->setLabel(t('Upload a file'))
    ->setDescription(t('Choose file from your computer'));

And in EntityForm I am trying to set some settings, because I need to make this dependable later with the '#states'

$form['file'] = [
    '#title' => $this->t('File'),
    '#description' => $this->t('Upload a file from your computer'), 
    '#type' => 'file',
    '#default_value' => $entity->file->value,
];

But at the moment the field is displayed, but I have problems on saving the form. The file is attached, but not getting uploaded and the error says:

Fatal error: Call to a member function getValue() on a non-object in C:\A plus\drupalsite\core\modules\file\src\Plugin\Validation\Constraint\FileValidationConstraintValidator.php on line 18

2
  • In field definition add ->setDisplayConfigurable('form', TRUE) and then in hook update for exmaple load the default form display and configure it. This is for texfield but have a look at upload widget what settings it has: $form_display->setComponent('myfield', ['type' => 'text_textarea', 'weight' => -10, 'settings' => ['rows' => 3]]); or just do it manually.
    – user21641
    May 11 '16 at 12:25
  • Set image as permanent in custom block plugin, temporary URI. Check this link for uploading an image in Drupal 8 Jan 12 '17 at 6:48
3
 $form['File'] = array(
        '#type' => 'managed_file',
        '#title' => t('Choose  File'),
        '#upload_location' => 'public://MyFilesFolder/',
        '#default_value' => $entity->get('File')->value,
        '#description' => t('upload file'),
        '#states' => array(
          'visible' => array(
            ':input[name="File_type"]' => array('value' => t('Upload Your File')),
          ),
        ),
      );
3
  • The file is uploaded, but not saved, unfortunately :(
    – badm
    May 17 '16 at 13:54
  • follow this link on how to save @badm[link]drupal.stackexchange.com/questions/198135/… do inform me if u need me to add that part here (save permanent part) May 17 '16 at 14:01
  • the problem is in this line '#default_value' => $entity->get('File')->value, if i set '#default_value' => array(10) for exmple it uploads some file with this fid, but how can i get this file__target_id $entity->file__target_id->value doesn't work
    – badm
    May 17 '16 at 14:33

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.