You are here

public function ApiSettingsForm::fbPageSubmit in Facebook Instant Articles 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/ApiSettingsForm.php \Drupal\fb_instant_articles\Form\ApiSettingsForm::fbPageSubmit()

Form submission handler.

Parameters

array $form: FAPI array.

\Drupal\Core\Form\FormStateInterface $form_state: Form state.

File

src/Form/ApiSettingsForm.php, line 339

Class

ApiSettingsForm
Facebook Instant Articles API form.

Namespace

Drupal\fb_instant_articles\Form

Code

public function fbPageSubmit(array &$form, FormStateInterface $form_state) {
  $config = $this
    ->config('fb_instant_articles.settings');
  $app_id = $config
    ->get('app_id');
  $app_secret = $config
    ->get('app_secret');
  $fb = new Facebook([
    'app_id' => $app_id,
    'app_secret' => $app_secret,
    'default_graph_version' => 'v2.5',
  ]);
  $access_token = $config
    ->get('access_token');
  $expires = time() + 60 * 60 * 2;
  $access_token = new AccessToken($access_token, $expires);
  $sdk_helper = new Helper($fb);
  $pages = $sdk_helper
    ->getPagesAndTokens($access_token);
  $page_id = $form_state
    ->getValue('page_id');
  foreach ($pages as $page) {
    if ($page
      ->getField('id') === $page_id) {
      $page_name = $page
        ->getField('name');
      $page_access_token = $page
        ->getField('access_token');
      break;
    }
  }
  if (isset($page_name) && isset($page_access_token)) {
    $config
      ->set('page_id', $page_id)
      ->set('page_name', $page_name)
      ->save();
    $config
      ->set('page_access_token', $page_access_token)
      ->save();
    $this
      ->messenger()
      ->addStatus('Success! This Instant Articles module has been activated.');
    $form_state
      ->setRedirect('fb_instant_articles.api_settings_form');
  }
  else {
    $this
      ->messenger()
      ->addError('There was an error connecting with your Facebook page. Try again.');
  }
}