업로드 된 파일을 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 파일에서이 작업을 수행 할 수 있습니까?
기 illa 보이스

7
좋은 @Jasodeep !! 그러나 이것은 내가 일하기에 충분하지 않았습니다. 설정 한 후 setPermanent()& save(). 나는 추가 단계를 수행해야했다 $file_usage = \Drupal::service('file.usage'); $file_usage->add($file, 'mymodule', 'mymodule', \Drupal::currentUser()->id()); :) 이것이 도움이되기를 바랍니다!
JayKandari

1
이 링크가 도움이되기를 바랍니다. api.drupal.org/api/drupal/core%21modules%21file%21file.module/…
dresh

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();
}

0

buildForm 함수에서 캐시를 비활성화해야 할 수도 있습니다.

$form_state->disableCache(); 
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.