Пользовательский модуль Drupal 8 - от данных Dynami c (API) для хранения в полях (тип содержимого) Drupal DB - PullRequest
0 голосов
/ 10 июля 2020

Я создал специальный модуль в Drupal 8, который берет некоторые данные из API и помещает их в базу данных Drupal, создавая новую таблицу. Я хочу добавить эти данные в качестве содержимого определенного типа содержимого c.

Как я могу это сделать?

вот мой код:

<?php

/**
 * Implements hook_cron().
 */
function ods_cron() {
  $message = 'Cron run: ' . date('Y-m-d H:i:s');

  $ods  = \Drupal::service('ods.ods');
  $conf = \Drupal::service('ods.ods_configuration_request');

  if ($conf->isDevelopment()) {
    // Development
    $response_bond = beforeSendRequest($conf->devUrlExternalBond(), 'GET');
    $response_mf = beforeSendRequest($conf->devUrlExternalMutualFund(), 'GET');
  } else {
    // Production
    $parameters_bond = [
      'headers' => $conf->headers(),
      'authorization' => $conf->basicAuthorization(),
      'data_post' => $conf->bodyBond(),
    ];
    $parameters_mf = [
      'headers' => $conf->headers(),
      'authorization' => $conf->basicAuthorization(),
      'data_post' => $conf->bodyMutualFund(),
    ];
    $response_bond = beforeSendRequest($conf->urlExternalBond(), 'POST', $parameters_bond);
    $response_mf = beforeSendRequest($conf->urlExternalMutualFund(), 'POST', $parameters_mf);
  }

  $raw_result_bond = json_decode($response_bond);
  $raw_result_mf = json_decode($response_mf);

  // Development
  if ($conf->isDevelopment()) {
    $raw_result_bond = json_decode($raw_result_bond[0]->field_bonds);
    $raw_result_mf = json_decode($raw_result_mf[0]->field_api);
  }

  $BondsProductList = $raw_result_bond->BondsProductInqRs->BondsProductList;
  $MFProductInqList = $raw_result_mf->MFProductInqRs->MFProductInqList;

  // Bond data store to internal
  if ($BondsProductList !==  null) {
    $bond_datas = [];
    foreach ($BondsProductList as $row => $content) {
      $bond_datas[] = [
        'AskPrice' => number_format($content->AskPrice, 1, '.', ','),
        'BidPrice' => number_format($content->BidPrice, 1, '.', ','),
        'BuySettle' => number_format($content->BuySettle, 1, '.', ','),
        'CouponFreqCode' => $content->CouponFreqCode,
        'CouponFreqID' => number_format($content->CouponFreqID),
        'CouponRate' => number_format($content->CouponRate, 2, '.', ','),
        'IDCurrency' => $content->IDCurrency,
        'LastCoupon' => $content->LastCoupon,
        'MaturityDate' => $content->MaturityDate,
        'MinimumBuyUnit' => number_format($content->MinimumBuyUnit),
        'MultipleOfUnit' => number_format($content->MultipleOfUnit),
        'NextCoupon' => $content->NextCoupon,
        'Penerbit' => $content->Penerbit,
        'ProductCode' => $content->ProductCode,
        'ProductName' => $content->ProductName,
        'ProductAlias' => $content->ProductAlias,
        'RiskProfile' => $content->RiskProfile,
        'SellSettle' => $content->SellSettle
      ];
    }

    $insert_data = $ods->setData(
      'bond',
      [
        'AskPrice', 'BidPrice', 'BuySettle', 'CouponFreqCode', 'CouponFreqID', 'CouponRate', 'IDCurrency',
        'LastCoupon', 'MaturityDate', 'MinimumBuyUnit', 'MultipleOfUnit', 'NextCoupon', 'Penerbit',
        'ProductCode', 'ProductName', 'ProductAlias', 'RiskProfile', 'SellSettle'
      ],
      $bond_datas
    );

    if ($insert_data) {
      // make response as JSON File and store the file
      $ods->makeJsonFile($bond_datas, 'feeds/bonds', 'bond.json');
    }

  }

  // Mutual Fund data store to internal
  if ($MFProductInqList !==  null) {
    $mf_datas = [];
    foreach ($MFProductInqList as $row => $content) {
      $mf_datas[] = [
        'ProductCode' => $content->ProductCode,
        'ProductName' => $content->ProductName,
        'ProductCategory' => $content->ProductCategory,
        'ProductType' => $content->ProductType,
        'Currency' => $content->Currency,
        'Performance1' => $content->field_1_tahun_mf,
        'Performance2' => $content->Performance2,
        'Performance3' => $content->Performance3,
        'Performance4' => $content->Performance4,
        'Performance5' => $content->Performance5,
        'UrlProspektus' => $content->UrlProspektus,
        'UrlFactSheet' => $content->UrlFactSheet,
        'UrlProductFeatureDocument' => $content->UrlProductFeatureDocument,
        'RiskProfile' => $content->RiskProfile,
        'FundHouseName' => $content->FundHouseName,
        'NAVDate' => $content->NAVDate,
        'NAVValue' => $content->NAVValue
      ];
    }

    $insert_data_mf = $ods->setData(
      'mutual_fund',
      [
        'ProductCode', 'ProductName', 'ProductCategory', 'ProductType', 'Currency', 'Performance1', 'Performance2', 'Performance3',
        'Performance4', 'Performance5', 'UrlProspektus', 'UrlFactSheet', 'UrlProductFeatureDocument', 'RiskProfile', 'FundHouseName',
        'NAVDate', 'NAVValue'
      ],
      $mf_datas
    );

    if ($insert_data_mf) {
      // make response as JSON File and store the file
      $ods->makeJsonFile($mf_datas, 'feeds/mf', 'mutual_fund.json');
    }

  }

  // console log
  \Drupal::logger('ods')->notice($message);
}

Могу ли я сохранить данные в безупречной таблице drupal 8?

1 Ответ

0 голосов
/ 13 июля 2020

Во-первых, вам нужно создать тип контента в бэкэнде Drupal 8, выбрав Структура> Тип контента.

Во-вторых, вы можете добавить узел программно, как это

use Drupal\node\Entity\Node;

$node = Node::create(array(
    'type' => 'your_content_type',
    'title' => 'your title',
    'langcode' => 'en',
    'uid' => '1',
    'status' => 1,
    'body'=> 'your body',
));

$node->save();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...