function RestExampleClientEdit::buildForm

Same name in other branches
  1. 3.x modules/rest_example/src/Form/RestExampleClientEdit.php \Drupal\rest_example\Form\RestExampleClientEdit::buildForm()

Throws

\GuzzleHttp\Exception\GuzzleException

Overrides FormInterface::buildForm

File

modules/rest_example/src/Form/RestExampleClientEdit.php, line 63

Class

RestExampleClientEdit
Edit or create a new node on a remote Drupal site.

Namespace

Drupal\rest_example\Form

Code

public function buildForm(array $form, FormStateInterface $form_state, $id = NULL) {
    $config_factory = \Drupal::configFactory();
    if (empty($config_factory->get('rest_example.settings')
        ->get('server_url'))) {
        $this->messenger()
            ->addError($this->t('The remote endpoint service address have not been set. Please go and provide the credentials and the endpoint address on the <a href="@url">config page</a>.', [
            '@url' => base_path() . 'examples/rest-client-settings',
        ]));
        return [
            'error' => [
                '#markup' => 'Unable to establish to the remote site.',
            ],
        ];
    }
    if (!is_null($id) && !is_numeric($id)) {
        return new Response('The ID passed in the URL is not an integer', 500);
    }
    $title = '';
    $form_state->set('node_id', NULL);
    $form_state->set('node_type', 'rest_example_test');
    // If this an existing node, we pull the data from the remote and set the
    // variables that we use as default values later on.
    if (is_numeric($id)) {
        $node = $this->client
            ->index($id);
        if (isset($node[0])) {
            $title = $node[0]['title'];
            $form_state->set('node_id', $id);
        }
    }
    $form['title'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Node title'),
        '#default_value' => $title,
    ];
    $form['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
    ];
    return $form;
}