Descripción
Para los que han tenido incovenientes con la nueva manera de utilizar services de Drupal 8 y tengan que conectarse utilizando Post para enviar datos a un servidor externo de Drupal usando Guzzle, les dejo el código que utilicé en un módulo custom para un proyecto.
Código
<?php
namespace Drupal\suggestions_module\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Serialization\Json;
/**
* Class SuggestionsIbmController.
*
* @package Drupal\suggestions_ibm\Controller
*/
class SuggestionsIbmController extends ControllerBase {
/**
* {@inheritdoc}
* @return array
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function showSuggestions() {
/**
* Descarga de Sugerencias y filtrado para enviarlas
*/
// Load entities by their property values.
$contenidos_for_suggestions = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'review']);
foreach ($contenidos_for_suggestions as $contenido_for_suggestions) {
$check_is_replied = $contenido_for_suggestions->get('field_replied')->value;
if($check_is_replied == "No"){
$check_id_contenido = $contenido_for_suggestions->get('nid')->value;
//print "No tiene contenido: ".$check_id_contenido;
/**
* Configuring Json to server send
*/
$json_array = [
'data' => []
];
$node_pre = \Drupal\node\Entity\Node::load($check_id_contenido);
$json_array['data'][] = array(
'type' => $node_pre->get('type')->target_id,
'id' => $node_pre->get('nid')->value,
'attributes' => array(
'Campo_1_Name' => $node_pre->get('campo_1_name')->target_id,
'Campo_2_Name' => $node_pre->get('campo_2_name')->value,
'Titulo' => $node_pre->get('title')->value,
'Campo_4_Name' => $node_pre->get('campo_4_name')->value,
),
);
$current_user = \Drupal::currentUser();
$account = $current_user->getAccount();
$username = $account->name;
// pass would be hard to get as stored hashed
//... so you would need to get a bit tricky to "catch" the users password when they log in...
$pass = 'mi_PASS';
$auth = 'Basic ' . base64_encode($username . ':' . $pass);
$token = 'EL TOKEN OBTENIDO USANDO /session/token AL FINAL DE LA URL';
// Logs a notice
\Drupal::logger('mi_modulo_custom')->notice('ID Contenido enviado:'.$check_id_contenido);
$client = \Drupal::httpClient();
$response = $client->request(
'POST',
//'https://URL_SERVIDOR_EXTERNO',
[
'timeout' => 600,
'json' => $json_array,
'headers' => [
'Authorization' => $auth,
'Content-Type' => 'application/hal+json',
'X-CSRF-Token' => $token,
],
]);
$suggestions_options = Json::decode($response->getBody());
$suggestions_options = $suggestions_options['VALOR_EXTERNO_RECIBIDO'];
$items = [];
foreach ($suggestions_options as $suggestion_option) {
$items[] = $suggestion_option['proposal'];
}
$check_is_replied = $contenido_for_suggestions->get('nid')->value;
//ksm($check_id_contenido);
$node = \Drupal\node\Entity\Node::load($check_is_replied);
$node->field_new_proposal = $items;
$node->save();
}else{
$check_id_contenido = $contenido_for_suggestions->get('nid')->value;
// print "Sí que tienen respuestas" .$check_id_contenido;
}
}
return [
'#type' => 'markup',
'#markup' => $this->t('Carga realizada correctamente: '),
];
}