سؤال

I've got this form:

 $form['import_json'] = [
      '#type' => 'file',
      '#description' => $this->t('Allowed extensions: json'),
      '#title' => $this->t('Import your JSON\'s file.'),
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Import'),
    ];

I have to use '#type' => 'file' because AFAIK managed_file doesn't allow json file and file is the only type left.

I need to be able to get the uploaded file when the user submit the form to be able to convert the JSON's data to create nodes of a certain type.

My function is already created and it looks like this:

protected function createActualite(string $json)
  {

    $jsonstring = json_decode($json, TRUE);

    foreach ($jsonstring as $field) {
      $node = Node::create([
        'type' => 'import_content', // Machine name de notre content type 'actualité'
        'title' => $field['titre'],
        'body' => $field['body'],
      ]);
      $node->save();
    }
  }

The problem is that I can't find a way to properly get the uploaded file, I tried the same way that we do with managed_file

$file = File::load($field['import_json']);
        $file->setPermanent();
        $file->save();

but it doesn't work, also this (which is 10yo) doesn't do the trick either gist

If someone can lead me to arrive to save this file or to any doc, I would greatly appreciate.

هل كانت مفيدة؟

المحلول

Ok I made it works, first I get the file's path using the solution given here

and then once I got the path, I'm reading the file using

$file = file_get_contents($file_path);

then calling my function createActualite($file); and it creates all the nodes up to the content of the JSON as expected.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى drupal.stackexchange
scroll top