0

Drupal 7 newb here.

I am creating a simple module. Basically, this has an admin config form with a message text area. On the front end, that message appears or not depending on the state of a cookie.

My question is: where (in what function) should you set the cookie?

My code is:

/**
 * Implements hook_block_info().
 */
function message_block_info() {
  return [
    'message_block' => [
      'info' => t('Message'),
      'cache' => DRUPAL_CACHE_GLOBAL,
    ],
  ];
}

/**
 * Implements hook_theme().
 */
function message_theme() {
  return [
    'message_block' => [
      'template' => 'templates/message-block',
      'variables' => [
        'config' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_block_view().
 */
function message_block_view($delta = '') {
  if ($delta !== 'message_block') {
    return;
  }

  $config = message_default_settings();
  if (empty($config['alert_message']) || $config['alert_show'] === 0) {
    return;
  }


  $block['content'] = array(
    '#theme' => 'message_block',
    '#config' => array(
      'alert_show' => $config['alert_show'],
      'alert_message' => filter_xss($config['alert_message']),
      'alert_link' => filter_xss($config['alert_link']),
    ),
  );

  return $block;
}
7
  • Depends on when do you want to set the cookie? – No Sssweat Mar 22 '18 at 7:08
  • @NoSssweat as a newb, I honestly don't know. How do you ascertain that? – MeltingDog Mar 22 '18 at 7:09
  • What is the cookie keeping track of? when (or what action) do you want that causes the cookie to be set? – No Sssweat Mar 22 '18 at 7:10
  • I want the message to appear only once per user - so, if the user visits the site a 2nd time the message is no longer visible to them. I've also updated the above with my code. – MeltingDog Mar 22 '18 at 7:13
  • 1
    You can set the cookie in hook_form_FORM_ID_alter. See How can I find the form ID of a form? to get the FORM_ID – No Sssweat Mar 22 '18 at 7:41
0

Here i set the cookie as user login and logged out.

/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-logged-in', '2', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-logged-in']);
}

You can try it will able to create new cookie anywhere i.e Create cookie into hook_init() https://www.drupal.org/forum/support/theme-development/2009-05-26/setting-custom-cookies#comment-2901778

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.