如何将上传的文件永久保存在file_manged表中?


11

如何在Drupal 8中将状态为1的上载文件保存在file_managed表中?

每当我上传文件时,该文件就会以状态值0存储在file_managed表中。
我曾经File::load( $form_state->getValue('image'))加载过该文件。接下来我需要做什么?

在Drupal 7中,我将使用$file->status = FILE_STATUS_PERMANENT。Drupal 8的等效代码是什么?

class AddBannerForm extends FormBase {


public function getFormId()
{
  return 'add_banner_form';
}

public function buildForm(array $form, FormStateInterface $form_state)
{


  $form['image'] = array(
    '#type'          => 'managed_file',
    '#title'         => t('Choose Image File'),
    '#upload_location' => 'public://images/',
    '#default_value' => '',
    '#description'   => t('Specify an image(s) to display.'),
    '#states'        => array(
      'visible'      => array(
        ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
      ),
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save image'),
  );

  return $form;
}


public function validateForm(array &$form, FormStateInterface $form_state)
{
    File::load( $form_state->getValue('image') );
}


public function submitForm(array &$form, FormStateInterface $form_state)
{

}
}

Answers:


17

谢谢@Clive@kiamlaluno

/* Fetch the array of the file stored temporarily in database */ 
   $image = $form_state->getValue('image');

/* Load the object of the file by it's fid */ 
   $file = File::load( $image[0] );

/* Set the status flag permanent of the file object */
   $file->setPermanent();

/* Save the file in database */
   $file->save();

1
现在,您可以在schema.yml文件中执行此操作吗?
纪尧姆·博伊斯

7
很好@Jasodeep !! 但是,这还不足以让我继续工作。设置setPermanent()&之后save()。我不得不做一个额外的步骤$file_usage = \Drupal::service('file.usage'); $file_usage->add($file, 'mymodule', 'mymodule', \Drupal::currentUser()->id()); :)希望这会有所 帮助!
JayKandari


4

如果您使用的是Drupal 8,请使用此代码将图像永久保存在配置表单中。

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  $image = $form_state->getValue('welcome_image');
  // Load the object of the file by its fid. 
  $file = File::load($image[0]);
  // Set the status flag permanent of the file object.
  if (!empty($file)) {
    $file->setPermanent();
    // Save the file in the database.
    $file->save();
    $file_usage = \Drupal::service('file.usage'); 
    $file_usage->add($file, 'welcome', 'welcome', \Drupal::currentUser()->id());
  }
  $config = $this->config('welcome.settings');
  $config->set('welcome_text', $form_state->getValue('welcome_text'))
    ->set('welcome_image', $form_state->getValue('welcome_image'))
    ->save();
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.