アップロードしたファイルをfile_mangedテーブルに永続的に保存するにはどうすればよいですか?


11

Drupal 8のfile_managedテーブルにステータスが1のアップロードファイルを保存するにはどうすればよいですか?

ファイルをアップロードするたびに、ステータス値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)
{

}
}

回答:


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ファイルで実行できますか?
Guillaume Bois

7
素敵な@Jasodeep !! しかし、これは私が取り組むには十分ではありませんでした。設定後setPermanent()save()。私は追加の手順を実行する必要がありました $file_usage = \Drupal::service('file.usage'); $file_usage->add($file, 'mymodule', 'mymodule', \Drupal::currentUser()->id()); :)これが役立つことを願っています!!
JayKandari 2017年


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();
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.