How to embed Facebook videos? -Drupal 7.37 & Omega4-Subtheme

-Windows7 HP & Toshiba Laptop

-Acquia-DevDesktop WAMP-Stack

-Latest Wysiwyg, CKEditor & Media_Module & Media_Oembed

Now I have tried everything and nothing allows a Facebook Video to Embed.

I have tried using the Facebook-URI/Embed-Code in the Media_Module-Media-Browser as well as dropping the Facebook-Embed-Code (using cut-and-paste) in the text-area.  The Facebook-Embed-Code that Facebook gives you, BTW seems strange to me.

Oembed (not the Media_Oembed Module) did not work at all.
Tried using another Wysiwyg-Rich-Text-Editor, besides CKEditor, because CKEditor strips out code and that switch did not help make the Videos embed.
Tried editing the CKEditor Advanced-Content-Filter to stop it from rewiring any code and that did not help.
The Video-Lightbox Software application seems to refuse the Facebook URI's also.
Media_Oembed also fails to help Media_Module to recognize Facebook-Embeds or URI's.
When I just cut-and-paste the Facebook-Embed-Code directly into a basic HTML-Document outside of Drupal (and even outside of a WAMP-Stack), this also does not work.  Viewing the source-code in FireFox, again I see some of the Facebook-Embed-Code is missing, having been stripped out by something.  What? FireFox?  HTML5?  This is the most puzzling.  Maybe the WAMP-Stack is necessary for embeds, but the link works.
Something seems to be removing part of the Code or else Facebook is using bad code inadvertently, being unaware of some configuration in the outside world.
Basically the URI's just deliver a red-reject-box from the Media_Module-Browser or else they deliver an iFrame or Flash that is dead in the water. Direct cut-and-pastes deliver just direct unprocessed raw code on output or else just, oddly, a link to the Facebook-Page that shows the name of the Video's owner and nothing more.
Any thought from anyone?  I am just really interested if anyone out there is embedding Facebook-Videos in ANY kind of way and if so, how?

Copy and paste it in the textarea, make sure you have full HTML filter selected, if y do not have that option, go to Text format and create a filter


Change a variable dynamically without it persisting in the DB I am wanting to change a variable (google analytics ID) programmatically based on the environment, BUT I do not want to change the saved value, so variable_set() is not an option.

Ideally I would also like the value that I set to be cached so as to not undermine performance.

So this is what I came up with, an implementation of hook_init(). Perhaps there is a better solution?

function MYMODULE_init() {
  global $conf;

  // If we have the environmental variable ENV && we are not on a config page
  if ($env = getenv('ENV') && current_path() != 'admin/config/system/googleanalytics') {

    // Alter the googleanalytics_account ID
    if ($env == 'dev') {
      $conf['googleanalytics_account'] = 'UA-xxxxxxxx-x';
    }
  }
}


attach an programmatically generated pdf file to a node Im using PDF Using MPDF module to generate 4 files when a node is saved using its API function pdf_using_mpdf_api:

function MYMODULE_node_insert($node){
        // PDF generation :
        // Generate standard version
        $view = node_view($node, 'PDF');
        $html = drupal_render($view);
        pdf_using_mpdf_api($html, 'reference_'.$node->nid);

        // Generate short version
        $view = node_view($node, 'pdf_short');
        $html = drupal_render($view);
        pdf_using_mpdf_api($html, 'reference_'.$node->nid.'_short');

        // Generate Standard EN version
        $view = node_view($node, 'pdf_en');
        $html = drupal_render($view);
        pdf_using_mpdf_api($html, 'reference_'.$node->nid.'_en');

        // Generate short EN version
        $view = node_view($node, 'pdf_short_en');
        $html = drupal_render($view);
        pdf_using_mpdf_api($html, 'reference_'.$node->nid.'_short_en');
}

this code above generates 4 pdf files correctly and save them under default/files/pdf_using_mpdf directory.
users should be able to download these PDFs, so I added 4 fields in my content type for each PDF version (field_pdf1, field_pdf2, field_pdf3, field_pdf4).

I want to attach these stored files into their corresponding fields inside private directory (after success, i'll remove them from default/files/pdf_using_mpdf directory).

Before Im used to use field_attach_update to attach fields to a node, but for file fields how can I do this ?

What should be the value of the field : $node->field_pdf1['und'][0]['value'] ? and how can I store them into private directory ?

Thanks in advance.

I didn't use PDF Using MPDF, so not sure what will be the file path for the PDFs got generated.

Anyway, these are general steps you need to perform for attaching files to a node.

Create a file object representing our physical file
Make it a managed file by calling file_save()
Fill file field with file's properties and fill field's other properties like display and description
Save the node to make attachment effective

You can utilize sample code below to get idea how to work on it.

<?php
// We have complete file path.
$file_path = '/whatever/path/to/file/sample.pdf';

$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.
file_save($file);

// We will save file under this location.
$destination = 'private://PDFs/';

// Make sure destination directory exists
//before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_pdf[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_pdf[$node->language][0]['display'] = 1;
$node->field_pdf[$node->language][0]['description'] = 'Our special PDF';

// Save node to make the attachment effective.
node_save($node);

Apply correct file path and destination directory. Here is the post explaining it in detail: Programmatically Attach Files to Node in Drupal 7


Are there any alternate module for qq_import module (Quiz Questions Import Module)? Are there any alternate module for qq_import module (Quiz Questions Import Module) ? It seems it has no Drupal 7 version for it.

It turns our that there are some similar existing modules on D7 but not as close as qq_import module. Instead, I just created my own custom D7 quiz question importer. It only imports multiple choice type of questions though


How to let users choose to hide fields in their profile? Is there a way to allow users to choose to hide certain fields in their profile?

For example if building a job site, a user might choose to hide their name from others. Is there a way to do this?

Create a checkbox field just below the field you want to hide on user profile page.
Now override the settings in template file.

Please follow the link allow users to choose whether certain profile fields are visible or hidden for detailed steps.

Also you can try out Profile2 Privacy module.

  This module extends Profile 2 by allowing administrators to create
  privacy levels as predefined groups or sets of profile fields on a per
  role basis. Users can then select from among the privacy levels to
  apply access control to their profile.


Autocomplete results showing behind the form How can I make the autocomplete search results appear above all elements on the page?

I have 2 forms on one page, the top form has the autocomplete text field. Immediately below that is another form. When the autocomplete results show, they are behind the second form.

I can only speculate as to how you've styled up the second form, but it might be its z-index is higher than that of the autocomplete dropdown.

Trying setting a higher z-index for the autocomplete div in your stylesheet:

#autocomplete {
  z-index: 1000;
}


How do I format a date value for a 3-column date drop-down widget? I would like to pass a date in the format 2013-04-23 00:00:00 as a #default_value into a form builder function:

$form['date'] = array(
    '#title' => t('Date'),
    '#type' => 'date',
    '#default_value' => $my-array['date'],
);

...but the form renders dates in a three column drop-down widget (which I want to keep). How do I reformat my date and/or form builder function so that my three drop-downs display 23 Apr 2013? At present, they display 02 Feb 1900.

Thanks

Solution

See @tostinni's answer for half of the soluion. This is the second half:

$timestamp = strtotime($my-array['date']);
$day = date('d', $timestamp);
$month = date('n', $timestamp);
$year =  date('Y', $timestamp);

The Form API documentation will help you figure this out, you'll have to pass an array with the year, month and day keys like this:

$form['date'] = array(
    '#title' => t('Date'),
    '#type' => 'date',
    '#default_value' => array('year' => 2013, 'month' => 4, 'day' => 23),
);


Change markup shown before the search result How do I change this markup from my .theme file?

Line 119 and following in core/modules/search/src/Controller/SearchController.php contain this code.

if (count($results)) {
  $build['search_results_title'] = array(
    '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
  );
}

I want to remove the <h2> tags from my search page.

I am able to change the search form above, and the result list after that tag using
hook_preprocess_form()on the search form and hook_preprocess_search_result() on the search results.

Is there a preprocess function I am missing, or can I use a custom template?

This answer has already been answered on stackoverflow. Here's a copy paste of what Cornel Andreev wrote.

You have to alter the route defined by the search module.
In order to do so:

Define in your mymodule.services.yml file following:

    services:
      mymodule.route_subscriber:
      class: Drupal\mymodule\Routing\RouteSubscriber
      tags:
        - { name: event_subscriber }

Create a class that extends the RouteSubscriberBase class on /mymodule/src/Routing/RouteSubscriber.php as following:

    /**
     * @file
     * Contains \Drupal\mymodule\Routing\RouteSubscriber.
     */

    namespace Drupal\mymodule\Routing;

    use Drupal\Core\Routing\RouteSubscriberBase;
    use Symfony\Component\Routing\RouteCollection;

    /**
     * Listens to the dynamic route events.
     */
    class RouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public function alterRoutes(RouteCollection $collection) {
        // Replace dynamically created "search.view_node_search" route's Controller
        // with our own.
        if ($route = $collection->get('search.view_node_search')) {
          $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleSearchController::view');
        }
      }
    }

Finally, the controller itself located on /mymodule/src/Controller/MyModuleSearchController.php

    namespace Drupal\mymodule\Controller;

    use Drupal\search\SearchPageInterface;
    use Symfony\Component\HttpFoundation\Request;
    use Drupal\search\Controller\SearchController;

    /**
     * Override the Route controller for search.
     */
    class MyModuleSearchController extends SearchController {

      /**
       * {@inheritdoc}
       */
      public function view(Request $request, SearchPageInterface $entity) {
        $build = parent::view($request, $entity);
        // Unset the Result title.
        if (isset($build['search_results_title'])) {
          unset($build['search_results_title']);
        }

        return $build;
      }

    }


How can I allow users to opt out of receiving e-mails with one-time login links? So I have been working on an update to my site to allow users to log in via one-time login links when they receive a Private Message.  Unfortunately, this kind of feature recently has been in the news as a security issue, so I want to make sure that I give users a way to opt out.

The one-time login links are provided by the Login One Time module.  The e-mail notifications are provided by the Privatemsg module's PM E-mail Notify submodule, but ideally the solution would also work for e-mails sent by Rules, system e-mails, etc.

How I add the login link

In the PM E-mail Notify UI, in the body of the "You have received a new message" e-mail, I insert the following token:

[privatemsg_message:recipient:login-one-time]

and the whole link is:

[privatemsg_message:recipient:login-one-time]?edit[name]=[privatemsg_message:recipient:mail]

This provides the user with a one-time login link that looks like this:

  http://localhost:8888/en/login_one_time/1173/1377182743/RZCfB7uwKRB_bFVCeKPNwtOnDn2jFfGMO2FdaE_cpxI?destination=?edit[name]=useremail@example.com

(Note: the ?edit[name]=useremail@example.com part is a query string for the Prepopulate module which pre-fills the e-mail address on the login form in the event that the one-time login link has already been used.)

What I want to do

Add a boolean field to the user profile, "Do not send me one-time login links in my e-mail."
Somehow check the value of that field when sending e-mail notifications.

Is there a robust way to do this?  Here is what I have thought of so far:

Instead of using Privatemsg to send the e-mail notifications, attempt to create the notifications in Rules.  But if I do this, then I cannot use any of the nice Privatemsg configuration settings (such as allowing users to choose when they would like to receive e-mails, e.g. every time they receive a message, only once per sender, etc.)
I could somehow create a token that gives the one-time link if the user has not opted out or the regular link if the user has opted out. (I'm not really sure how to do this.)
I could hack the PM E-mail Notify submodule to do what I want.

Ideally, I want to do the following: if a user has opted out, I want to replace the one-time login link in any e-mail sent by the site with a link to the login form.

Note: My site is multilingual, and I am translating the e-mails sent with the site using the Variable and i18n modules.  So, any solution needs to be robust enough to handle multilingual e-mails.

What I would do is define your own token.

Start off with copying login_one_time_token_info() and login_one_time_tokens() into a custom module, change the hook names and rename the token to something like login-one-time-optional or whatever you prefer :)

Then, change the implementation of the hook_tokens() implementation so that you check the field on the $account and use either the existing function or url('user/login', array('absolute' => TRUE)). Keep in mind that existing users users might not have any data saved in that field, so add a default value, you might want to put something like this in a helper function:

if ($items = field_get_items('user', $account, 'your_settings_field')) {
  return (bool) $items[0]['value'];
}
else {
  // Default to use the one time login link.
  return TRUE;
}


How is a field's value (rather than its key) obtained? In Drupal 7, I have a page content type that has a field called group (so the machine name is field_group).  The field is a List (integer) field type.

This field might have allowed values as follows:

0|Description 1
1|Description 2
2|Description 3

If I want to return the key of this field for the current page, the following code correctly works:

field_get_items('node', $node, 'field_group')[0]['value']

If the key were set to 1 for this page, the above code would return 1.

However, is there a way to instead return the associated value (e.g., "Description 1," "Description 2," etc.)?

I thought I had a way to return the value already, but I was told yesterday that my previous method was not a good way to get the value (or key) because my previous method may return extraneous data (such as unwanted HTML), when I really just want the raw key/value itself: How is a field's key (rather than value) obtained?

As you can see, you pass to field_get_items() the $node parameter. This should tell you that this function will return you a value stored in this Entity. The values of your field are stored in the field itself. You can get your options array as following.

$fieldData = field_info_field('field_group');
$options = $fieldData['settings']['allowed_values'];


How to stop webform from sending an email I'm using Drupal 7.12 / Webform 3

How do I stop email from being sent upon a webform submission? I want to do this conditionally so I need to use a hook. I still want everything else to go through correctly (i.e. confirmation page, db entry for submission).

I see that there are these lines in function webform_client_form_submit($form, &$form_state)

if (!$is_draft && !$form_state['values']['details']['finished']) {
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);
    webform_submission_send_mail($node, $submission);
  }

How do I hook into that and stop it?

If you go the end of the function webform_submission_send_mail() inside the file webform.submissions.inc (inside weform module's include directory), you'll notice that the webform module using the function drupal_mail() to send the mail.

So a better place to change the behavior of the mail from being sent (alter in Drupal terms) is hook_mail_alter(), which is used to alter an email message created by using drupal_mail() function.

Implementation of the hook to stop the e-mails:

function MODULE_mail_alter(&$message) {
  //You can do your conditional check here and depending on that
  //you can set the value of $message['send'] to false to stop the mail from being sent.
  //place the line below inside conditional loop, or else it'll stop every mail from being sent ;-)
  $message['send'] = FALSE;
}

Note: This hook will only work if the mail is generated by drupal_mail(). If you're sending mail by some other menthod, it'll not be invoked. But, by default Webform module uses drupal_mail() as mentioned earlier, so there's nothing to worry :-)
You'll also need to clear the caches to make the change effective.


Can I rename a module? I foolishly created a features module and named it events. This is bad because, of course, there is a registered module with that same name. So the update status report is always in error and drush has to lock the module so it doesn't attempt to "update" it.

I would rather not uninstall, recreate, reinstall because I will have to recreate content (yes, I have backup/restore installed).

Is it possible (advisable) to rename the directory and files, edit the .info, and edit the record in system?

     ericx ** drupal_addicted ** Wed Sep  3 15:26:29 2014
     sql> select * from system where name='events'\G
    *************************** 1. row ***************************
          filename: sites/dev.addictedtoagility.com/modules/custom/events/events.module
              name: events
              type: module
             owner:
            status: 1
         bootstrap: 0
    schema_version: 0
            weight: 0
              info: a:11:{s:4:"name";s:6:"Events";s:11:"description";s:49:"Adds the Events content type and supporting stuff";s:4:"core";s:3:"7.x";s:7:"package";s:8:"addicted";s:7:"version";s:7:"7.x-0.1";s:7:"project";s:6:"events";s:12:"dependencies";a:8:{i:0;s:4:"date";i:1;s:11:"event_sites";i:2;s:8:"fe_block";i:3;s:4:"file";i:4;s:4:"list";i:5;s:14:"node_reference";i:6;s:9:"strongarm";i:7;s:5:"views";}s:8:"features";a:7:{s:6:"ctools";a:2:{i:0;s:21:"strongarm:strongarm:1";i:1;s:23:"views:views_default:3.0";}s:17:"fe_block_settings";a:1:{i:0;s:20:"views-events-block_1";}s:12:"features_api";a:1:{i:0;s:5:"api:1";}s:5:"field";a:5:{i:0;s:22:"node-event-field_dates";i:1;s:33:"node-event-field_event_event_site";i:2;s:22:"node-event-field_judge";i:3;s:24:"node-event-field_premium";i:4;s:27:"node-event-field_start_time";}s:4:"node";a:1:{i:0;s:5:"event";}s:8:"variable";a:14:{i:0;s:23:"comment_anonymous_event";i:1;s:26:"comment_default_mode_event";i:2;s:30:"comment_default_per_page_event";i:3;s:13:"comment_event";i:4;s:27:"comment_form_location_event";i:5;s:21:"comment_preview_event";i:6;s:27:"comment_subject_field_event";i:7;s:25:"date_format_month_and_day";i:8;s:33:"field_bundle_settings_node__event";i:9;s:18:"menu_options_event";i:10;s:17:"menu_parent_event";i:11;s:18:"node_options_event";i:12;s:18:"node_preview_event";i:13;s:20:"node_submitted_event";}s:10:"views_view";a:1:{i:0;s:6:"events";}}s:3:"php";s:5:"5.2.4";s:5:"files";a:0:{}s:9:"bootstrap";i:0;}

1 row in set (0.00 sec)

Renaming a Drupal feature requires additional steps than rename a custom module.

Solution 1 (without un/install)

Backup the DB.
Put the site on maintenance mode.
Rename the feature with an IDE or bash script (don't access/edit any content of the site while you are doing this).
Run:

drush php-eval 'registry_rebuild();'
drush updb -n. (forces drupal to reload caches related to module/features)
drush cc all

Solution 2 (more proved but requires un/install)

Backup the DB.
Follow the steps to rename the feature on this thread.

To replace the new name (the human and the machine name) on each file, I suggest you to use an IDE like NetBeans (or similar).

You can also use cool unix commands like sed and find to do it.

Try to make a code review after the changes to make sure that the rename was done on the right places.

Note: to make sure that the name I choose for a module/feature is not already used, I use the following command:

drush pm-list --type=Module --no-core --status=enabled --pipe | sort


Most user friendly way to organise this content? We're trying to work out how best to organise this content: https://international.permaculture.org.uk/for-organisations

It should be one column layout but with text and image aligned next to each other which will then be responsive (i.e. image moves to below paragraph associated with it)

It was suggested that the responsiveness could be detailed in within the text editor source for each pane, by giving the text and image separate div tags and assigning them some css, but I think the administrators who are going to use these sites would not feel happy with that approach.

I am wondering if using Nodequeue module is a good idea? Or if there is another way? Content order needs to be felxible so I don't think using a view is best way.

I'd recommend using the Bootstrap 3 theme/module it is very easy to install and use, and has built-in responsiveness to mobile vs laptop screens, which automatically moves your images below text, changes your menu to the mobile menu button, and other nifty features. You can copy its subtheme and make it into your own custom theme and there change many of the vanilla styles as well, so its very customizable.


Adding Roles with Rules upon Webform submission not working — Why? Here's what I have done so far (in Drupal 7):

Created a webform quiz that only validates if all answers are correct
Created a role called "Mid-program quiz: Passed" that has permissions to view a particular page
Created a rule that says upon submission of the quiz, the submitting user should be granted the "Mid-program quiz: Passed" role.

But it's not working. The quiz is being submitted correctly but the role is not being assigned.
Here are the details of the rule that's failing to execute:

Event
Event: After a webform submission has been added
Conditions: Webform has name
Parameter: The form id of the submitted form: [form_id], Webforms: Mid-program quiz
Elements
(Here I wasn't sure whether to use [user], i.e. the user submitting the webform,  or [site:current-user], i.e. the currently logged-in user. So I did both.)
Add user role
Parameter: User: [user], Roles: Mid-program quiz: Passed
Add user role
Parameter: User: [site:current-user], Roles: Mid-program quiz: Passed

Can someone see where the problem is in this rule?
Thanks!

Adding Roles with Rules upon Webform submission not working — Why?

Okay, it looks like I figured it out:

 Event: After a webform has been submitted
 Condition: Webform has name

   Parameters:

      The form id of the submitted form: [form_id]
      Webforms: Mid-program quiz

 Action: Add user role

   Parameters:

     User: [user]
     Roles: Mid-program quiz: Passed

So the confusing things to watch out for are:

 "After a webform has been submitted" is the one to choose, over "After a webform submission has been added."
 Webform Has Name has first parameter as ID and second as the webform (as selected from a list of webforms). It makes it seem like you're saying nid has to be equal to a title, which doesn't seem like it would work, but that's apparently not what's happening.
 Add user role takes simply Parameter:user, rather than site:user or any other attribute of user


Change content "Author" to the last "Editor" On the admin/content page. The field "AUTHOR" shows who created the content, but this is not very helpful for seeing who last edited it.

How would you change this to show who last edited it?

If you have a custom module to use, or aren't afraid to make one, then a hook_node_presave is the first method I would try.

function yourmodule_node_presave($node) {
  // php5 passes objects by reference
  // so this should not need a & or return
  global $user;
  $node->uid = $user->uid;
}

If you do not want to go with code, then try the Rules module.  Rules has a trigger for node about to be saved.  Set the condition that the current user is not anonymous (because rules likes you to confirm in a condition any data you want to use in the actions) and then set the author field in the action to the current user.  All done in the ui, no new code needed.


Is there a way to pass multiple arguments to menu_name while creating menu links programmatically? Am using Drupal 7.
Below is my code where am trying to create menu links programmatically:

$links[] = array(
'menu_name' => 'management',
'link_path' => 'myheader/config',
'link_title' => 'Header Settings',
'options' => array(),
'weight' => 2,
'parent' => 'custom/header-settings',
);
$links[] = array(
'menu_name' => 'mycustommenu',
'link_path' => 'myheader/config',
'link_title' => 'Header Settings',
'options' => array(),
'weight' => 2,
'parent' => 'custom/header-settings',
);

In the above code, only menu_name is different. Rest of them are same. Is there a way to pass multiple arguments to menu_name?

No. When you're building links for D7's menu system, you'll need to specify the entire link array because you're creating link metadata here. If you're trying to keep your code DRY you could try to create a template array (or function) then copy/update as you needed new links, but you're probably doing just as much work for little/no performance gain or clarity.


Import always show changes I have problem with import/export. After import it always says that there is changes after sync.

Anyone faced this issues? How to fix it (showing no changes after import all)?

I found myself problem. Export full create different .yml file than export single. That why it make some fields lost.
Besides, the export function might ignore hidden fields in .yml files. In this case it should add fields manually to avoid conflict.


Countdown timer for schedule unpublish date I am using Scheduler module in order to enable unpublish date for a content type.

Now I want to create countdown timer for the nodes that unpublish date is set for them.

I checked jQuery Countdown and Countdown Timer Field modules but it seems they can't help in this issue.

What is your suggestion? Is there any way to create a relation between node unpublish date and countdown_timer modules or I must edit source of themes?

Thanks a lot for your help

You could add the snippet below as a new module scheduler_unpublish_countdown. It defines a block which you can shown on the node page of any content type you choose and allow it to countdown to the scheduled unpublish time for that node. As the block that comes with the jquery_countdown module counts down to a global event; this might be better for your use case.

<?php

/**
 * Implements hook_block_info().
 */
function scheduler_unpublish_countdown_block_info() {
  return array(
    'unpublish_countdown' => array(
      'info' => t('Scheduler Unpublish Countdown'),
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

/**
 * Implements hook_block_view().
 */
function scheduler_unpublish_countdown_block_view($delta) {
  if ($delta == 'unpublish_countdown') {
    $node = menu_get_object();
    // Ignore non-node pages, already unpublished nodes, nodes that don't have a
    // date/time set for unpublishing and nodes whose unpublishing date-time is in the past.
    if (!$node ||
      empty($node->status) ||
      empty($node->scheduler['unpublish_on']) ||
      ($node->scheduler['unpublish_on'] <= REQUEST_TIME)) {
      return;
    }
    $variables = array(
      'id' => drupal_html_id('jquery_countdown-' . $delta),
      'options' => array(
        'until' => date("F d, Y g:i a", $node->scheduler['unpublish_on']),
        'description' => ' ', // So that the CSS doesn't get screwed
        // Reload the page when the countdown is done
        'onExpiry' => '(function() { location.reload(); })',
      )
    );
    return array(
      'subject' => t('Scheduled unpublish in..'),
      'content' => theme('jquery_countdown', $variables)
    );
  }
}

Once the countdown is complete, the page will simply reload (see onExpiry option above). As unpublishing happens only either during the normal Drupal cron run or through the Scheduler's own light-weight variant, it may not happen exactly at the time of unpublishing meaning the page would reload and nothing would happen (except for the timer not showing up anymore) which might be slightly awkward.

I'd recommend, therefore, to redirect to a custom page once the countdown expires where you explicitly call _scheduler_unpublish() and then redirect back to the node page. You might want to send a one-time-only token along for security.

Remember to add scheduler and jquery_countdown as dependencies for your new module.


Inline Validation Messages with Webform Sorry if this has been asked before (although I've been looking and haven't found quite what I'm looking for).

It's not currently possible to present the server-side validated messages (specifically required fields) inline on forms built with webform, is it? If not, is is something that I could realistically code myself? Looking at this ticket:

https://www.drupal.org/project/webform/issues/2889272

The line: "Form validation messages will not be moved because contrib modules and theme expect this information to be displayed in specific region." Makes me wonder if it would even be possible.

Be nice, this is my first question on here.

Thanks.

Drupal core includes the Inline Form Errors module which will move required validation messages below each element. Issue #2889272 was specifically about where the main message container, with the "X errors have been found" text, should be placed on a page.

I also recommend checking out the Clientside Validation module. Here is a short video showing how to improve webform client-side validation.


HTML E-Mails are being sent out as plaintext I am  using the Swift mailer module to send HTML emails. My actual body in hook_mail_alter() is the following.

New Enquiry Appear

            お名前
            @name

            &nbsp;メールアドレス
            @email

            &nbsp;電話番号
            @mobile

            題名
            @title

            メッセージ本文
            @message

&nbsp;

The actual output is something like the following.

    /*New Enquiry Appear */

お名前
                        amol

                         メールアドレス
                        testl@gmail.com

                         電話番号
                        99888776655

                        題名
                        challawar
               Html tag are not converted in Bold and Italic.

                        メッセージ本文
                        sssssssssssssssss

I want my output to be well formatted as per my HTML markup. (Few HTML tags like
, , and
 are not working in the above example.)

Did you check the message setting of swiftmailer module? You can change the message format to HTML.


Hide parent term and show only second level I'm getting frustrated figuring this out for a couple of hours. I was not able to make work what I've wanted to achieve.

I have taxonomy which has sub-child. Here is my taxonomy structure:

Parent 1

Child 1
Child 2

Parent 2

Child 1
Child 2

When the parent term is visited, then it will list its sub-child. Like below:-

Parent 1 title

Child 1
Child 2

I've created a views taxonomy terms, I don't want to use content  because the term will not show if that term is empty.

In contextual filters, the taxonomy id with depth and modifier is not available.

Assuming that when you say "When the parent term is visited" you mean at the taxonomy term page at taxonomy/term/[..], the view settings below will work.

View type : Term
Display : block
Pager : Display all items

Relationships : Taxonomy term: Parent term
> Identifier: Parent

Contextual filter : (Parent) Taxonomy term: Term ID
> Relationship : Parent
  > When the filter value is not available : Provide default value
    > Type: Taxonomy Term ID from URL
    > Load default filter from term page : checked

If you want the parent term to appear instead of the vocabulary name, also do:

  > When the filter value is available or a default is provided : Override title
    > (argument) %1

You can also enter a space instead of "%1" to clear it since the parent term already appears by default as page title (otherwise it will appear twice).

Finally, if you want to sort by term weight, also do:

Sort criteria : Taxonomy term: Weight (asc)

Enable the block to only display on taxonomy term pages, appearing above the main page content block.

You can also do some interesting things when you combine the Taxonomy Menu and Menu Block modules.

Hope that helps!


Form API: Persistent values across submits? Getting started with the form API. None of the examples seem to keep and redisplay the values the user entered. E.g.,  you have a "name" field. User enters "John" and hits Submit.

If the form data is invalidated for some reason, the name field should still show "John" so he doesn't have to enter it again. Is there a setting to set for persistent values? values vs. default_values?

Drupal 7 stock install

In the Form API, there are two separate value setters #default_value and #value where these two make different things happen when you using it
- #default_value set the value of your element when the form is created the first time, and if your form has an error for some reason, does not affect your element
- #value set element value every time the form is rendered, even when the form is created again because of some error

It is not correct to use #value for textfields and other input elements, use #default_value instead. #value is meant only for buttons, submits and other non input elements.
if you use $form['#value'] = 'Name' for input elements like textfield the value of that field always would be Name even if the user entered some other value for this field.

see Form API Reference


Convert Media tags to markup failing again Once again I am plagued by this. Embedding an image from the media library shows in the editor, but when you view the node on the front end you get this:

[[{"fid":"851","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"Reality Check","field_file_image_title_text[und][0][value]":""},"type":"media","attributes":{"height":"333","width":"1502","style":"font-size: 13.008px;","class":"media-element file-default"}}]]

Normally you would confirm a couple things in drupal 7.5 -

Check the text format configuration to make sure convert media tags
to markup is set. In my case its on every filter and it is in the top
position. no matter which position it is in, still nothing works.
Check to see if a custom template is used and make sure it's using
render() and not just a plain echo. In my case, it is a custom
template and it is using render($node->body['und'][0]['value'])
Check to see if any wrapping tags may be causing a conflict. In my
case there is no wrapping tag. It's just an inline image from the
media library.

I'm using a custom tinyMCE install with the wysiwyg module because for reasons unknown the media library module broke everything much worse. Somehow I don't think this has anything to do with tinyMCE though.

Anyone have any further ideas?

For those of us just constantly plagued by this failure in programming, here's a link with the solution that worked for me. Upvote if you find it helpful:
Media with WYSIWYG not converting media tags to markup

Essentially, don't trust print render() - I had to use this in my custom template file:

<?php print render(field_view_field('node', $node, 'body', array('label'=>'hidden'))) ;?>


List "edit Menu" links on a custom page I am attempting to create a simple user dashboard that will let a user do things throughout the site like edit menus and content.

I would like to have a dropdown that lists all the custom menus on the site and after they select one it would take them to the edit page.

How would I go about doing this within my module?

This feature is already done in core in D8, however not in one menu but in multiple one (in the wrapper divs of the elements).

First of all I would make a list exactly what I want to include in the custom menu (menu items edit, content edit, etc..).

And then trying to look inside the core for the existing solution for that and unite them into one menu.


Alter views style using regenerate feature? I created a views using feature and export the views in my second site. After some time I need to change in views style. After change in style I regenerate the feature and export again.

I disabled the previous version and enable this version. The changes in fields are altered but changes of styles plugin are not altered. I cleared the cache and also uninstalled and installed again, but it didn't work at all.

Anyone used feature module like this? Am I missing something?

You do not need to enable / disable features on prod server after uploading the new files

First, on your prod site clear all the caches

Then go on the view's page admin/structure/views click on the dropdown list beside your view, you should have an operation 'revert' : that's it

If you dont have 'revert' operation, (and disable is present) it means the views is up to date with your feature's file

Of course, the start point is to re-export your feature's files from your local site and upload them to your server (do not export/import your view, the code must be in the feature's files)


How I can unit-test APIs? How I can unit-test APIs? Is there any method for asserting API response in drupal 7?

You can find an example in the Examples for Developers module. Here are two excellent guides:

Simpletest Testing tutorial
Unit Testing with SimpleTest


Dependency injection to load node data When I checked the code I wrote with phpcs --standard=DrupalPractice /path/to/myController, I got the following warning.

  WARNING | Node::load calls should be avoided in classes, use dependency injection instead.

The code I use to load the node is the following.

use Drupal\node\Entity\Node;

public function content_load($node = NULL) {
 $noad_data = Node::load($node, NULL, TRUE);
}

How should I use dependancy injection to load a node?

The controller base class provides the method entityTypeManager() which gets the service with the same name from the container the first time you use it. You can use this service to get the node storage:

  $node_storage = $this->entityTypeManager()->getStorage('node');

and then load the node:

  $node = $node_storage->load($nid);


Messed-up div IDs for ajax-modified form field I want to change, using Ajax, some attributes to field2 (a select widget) when field1 changes:

In mymodule.module:

function mymodule_form_NODETYPE_FORM_alter(&$form, &$form_state, $form_id) {
    $form['filed1']["widget"]['#ajax'] = array(
        'callback' => 'on_filed1_change',
        'wrapper' => 'edit-field-filed2-wrapper',
        'event' => 'change',
        'method' => 'replace',
    );
}

function on_filed1_change(array $form, FormStateInterface $form_state)  {
    $form['field2'] = $modified_field2;
    return $form['field2'];
}

This works only the first time.

I found out the following id's have been changed with additional trailing random numbers:

edit-field-field2-wrapper--GCPg2vSCav0 for field2 wrapper <div>
edit-field-field2--EXhOuuWQld8 for field2 <select> element

Since the original Ajax wrapper edit-field-field2-wrapper no longer exists, no further modifications to field2 are possible.

Why does this happen? And how can I prevent this from happening, or use the new IDs as wrapper in the Ajax call?

I'm using 8.6.0-dev.

function mymodule_form_NODETYPE_FORM_alter(&$form, &$form_state, $form_id) {
    $form['field2']['#attributes']['id'] = 'my_dom_id_for_elem2';
    // or if it doesn't work properly you can wrap the element
    // $form['field2']['#prefix'] = '
';
    // $form['field2']['#suffix'] = '
';

    $form['filed1']["widget"]['#ajax'] = array(
        'callback' => 'on_filed1_change',
        'wrapper' => 'my_dom_id_for_elem2',
        'event' => 'change',
        'method' => 'replace',
    ); }

function on_filed1_change(array $form, FormStateInterface $form_state) {
    // This line is not necessary, at this time $form['field2']
    // has already been modified and you can just return the form element itself, it will be used as response.data by javascript.
    //$form['field2'] = $modified_field2;
    return $form['field2'];

}


Superfish module seems to "Ignore" it's very own library I have a problem connecting the Superfish library to the module... I've tried to Google this issue and the error I got, but found no direct solution. Here are more details:

I've installed the module alright but when I go to admin/config/user-interface/superfish, it asks me for the library path. I've tried many variations such as:

/public_html/sitesname.com/sites/all/libraries/Superfish
/public_html/sitesname.com/sites/all/libraries/
sitesname.com/sites/all/libraries/Superfish/
sitesname.com/sites/all/libraries/
public_html/sitesname.com/sites/all/libraries/Superfish
public_html/sitesname.com/sites/all/libraries
/public_html/sitesname.com/sites/all/libraries/Superfish/superfish.js

Nothing seems to work and I keep getting the (kinda wired) error "File not found". Any ideas?

Download the Superfish library and extract it to sites/all/libraries/superfish (so that the superfish.js will be located at http://example.com/sites/all/libraries/superfish/superfish.js)

Also check if the permissions on the .js files are correct. Status report pages (admin/reports/status) may also be of help.


How to call a function in a Twig file Let's say I create a function in a module file:

function _get_test() {
  return 'test';
}

How can I call this in any Twig file? For example *.html.twig, page.html.twig, node.html.twig etc.

OR

How can I pass a variable from PHP to Twig and display in any Twig file.
For example *.html.twig, page.html.twig, node.html.twig etc.

You can define your own custom Twig functions in a custom module (but not in a theme). To find an example for how to do this, see this example in core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php.

Also see this blog post: Create Twig extensions for Drupal 8.

  In this example, we will build an extension to display a Drupal block
  directly in a Twig template:

{{ display_block('my_block_id') }}

  src/MyTwigExtension.php

<?php

namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'block_display';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('display_block',
        array($this, 'display_block'),
        array('is_safe' => array('html')
      )),
  }

  /**
   * The php function to load a given block
   */
  public function display_block($block_id) {
    $block = \Drupal\block\Entity\Block::load($block_id);
    return \Drupal::entityManager()->getViewBuilder('block')->view($block);
  }

}

  src/MyTwigModule.services.yml

services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }


How to trigger a rules action only for a specific value of a user profile field? I have created a Rules component which contains an action to send an mail.
And I have a rule created with the scheduler option. In this rule, I have set one condition like so:

if site:current-user field has value equals to something
then mail should be triggered,
otherwise it should not.

But it is sending an eMail in both cases. Any idea why?

Make sure to add a Rules condition Entity has field (related to your additional site:current-user-field in your Rules condition). And make sure to add that Entity has field condition BEFORE the condition you already have.

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


This import is empty and if applied would delete all of your configurations Customer bought a theme that has Commerce plugin installed with sample data.
Anxious to get running and try out the new configuration system, I did what I do prior to Drupal 8.6. Commit everything but sensitive info into git and cloned to my local, dumped the MySql db. After getting the index page, every page returns a 500 error. One is Attempt to create a field commerce_remote_id that does not exist on entity type user despite the commerce_remote_id table in existence. The entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() in another.
Drag copying all files from modules/commerce, modules/profile should get me past these errors.
drush updb returns no updates needed.
drush cr offers no relief.
OK, I wanted to start using the new configuration system. On customer site drush cex and committed to git.
On my local after git pull, drush cim returns:

This import is empty and if applied would delete all of your configuration, so has been rejected.

As I research this, it appears that drush will not import, but prefer to use drush site:install with an existing configuration.
OK, the strong imperative within the community is to use composer to do a new site install.
Can drush 9.5.2 install a new site onto itself using the existing settings.php file? I would like to get the sync configuration files working so that I can remove that as a factor to resolve my local site being hosed.

I read in another tutorial that the UUID must be copied over because if the customer and my local are to have the configuration work together that the UUID in system.site.yml must match. I can confirm that they do match.
drush config.get system.site returns the UUID that the source Drupal install is using.

Do double check the directory where the config files are located. The directory is set in settings.php like:

$config_directories['sync'] = 'sites/default/files/[...]/sync';

I had the same issue but moving the config directory to the correct place solved it.


Patching together a Drupal project I'm trying to basicly glue/patch/fix a Drupal project so that I can edit it simpler. There's too much duplicated code which I want to make into the same function.

To do this I have to, from my own knowledge, handle modules. What I'm curious about is: What is the ideal way to structure these new functions?

Should I create a module called global_fixes, or should I add new functions to the existing modules? Feel free to share your solutions if you have been given a similiar situation.

Assuming that you inherited the custom modules along with the site, and there is no external maintainer of those, you should refactor the modules.

For contributed modules (i.e. modules maintained - or in some cases not - at drupal.org/projects), the options are more complicated.  I don't recommend creating yet another module (global_fixes) to deal with this.  You'll have problems keeping this in sync with new releases of the contributed modules you feel the urge to "fix".

Instead:

If you're community oriented person, raise an issue in the module's project issue queue for what you consider duplicated code (or other defects). If you fix the problem yourself, make your fix a patch, and add the patch to the issue queue.
If you don't want the hassle of dealing with module maintainers and the community, make a local fork where you essentially turn a contributed module into a custom one, and do whatever you like with it.  This also means that you will no longer be able to download improved versions of this module drupal.org/projects. You'll have to maintain it yourself (just like any other custom module).

If you want to follow the community route, you'll probably notice that not all Drupal project maintainers are prepared to resolve your issues or commit your patches in a timely manner.  So if you decide to create and submit patches, I strongly recommend that you install git and maintain a local repository that let you work with the code locally (independent of the repository at Drupal.org).  Just do a merge whenever there is a new commit available at the central repository.

If you're really community minded, and discover that all the fine patches you create and submit to a project's issue queue appearently fall into a black hole, you may want to read up on this: Dealing with unsupported (abandoned) projects.


A view that displays content with taxonomy term of current user? The Setup:

A Taxonomy Vocabulary called "School" - During registration, users can choose multiple "Schools" from the taxonomy list to associate themselves with.

A content type called "Lesson" - Each lesson can choose a school from the taxonomy list to associate itself with.

The Challenge:

I would like to construct a view where the logged in user sees a list of lessons from schools they have associated themselves with.

I'm struggling to understand the relationships and (presumably) the contextual filters that I'll need to have in place to make this happen. Help!

You have the right idea!

You'll start with a View of "Lesson" content.

You'll then add a Relationship from the "Lesson" to the "School" taxonomy term, using the taxonomy term reference field configured on the "Lesson" content type.

Next, you'll add another Relationship from the "School" taxonomy term to the User entity type, using the taxonomy term reference field on the User entity. This is a reverse relationship; in the Views interface, it will be labeled something like "Taxonomy term: User using [name of reference field]". (My suspicion is that this is the part you're missing.)

Finally, you'll add a Contextual Filter "User: Uid", configured to provide a default value of type "User ID from logged in user". There will be a configuration option here to select the Relationship to use for this contextual filter, but at this point it should already be selecting the only User Relationship that is currently configured.


Show system message to user when node is published I'm looking for a way to show a system message to the author of a node, when the node gets published (by an administrator)

I think this must be achievable with Rules, but browsing the web and searching on stackoverflow did not help me out (yet).

This is what I did in Rules so far:

EVENT:After updating existing content of type Event

CONDITIONS: Content is published

ACTIONS: Show a message on the site

System messages are displayed only once and for the current user. In your case it would be more appropriate to send an email when the node has been published.

To do so, create a following Rule:

Event: After updating existing content; restrict it by content type if necessary.
Condition: User has role(s), select administrator role and check Negate to make sure this rule does not get triggered for administrators.
Condition: Data comparison, for Data to compare select that node-unchanged:status equals to Unpublished. This is to make sure old node was unpublished.
Condition: Data comparison, for Data to compare select that node:status equals to Published. This is to make sure new node is published.
Action: Send mail and configure it the way you want.

Hope this helps.


Redirect to referrer, confirm_form I have few confirm_forms which could be invoked from different places. I would like to redirect user to proper place after cancelation. Referrer Header is not good way to do it so I'm looking for good idea to do it in drupal. Maybe something with current_path?

Menu for deletion is defined like so:

$menu['module/entity/%/delete'] = array(
    'title' => 'Delete directory',
    'description' => 'Remove directory from ITC Backup',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_entity_delete_form', 2),
    'access arguments' => array('Entity administer'),
    'type' => MENU_LOCAL_TASK
);

Form creation function is (at the moment) defined this way:

function module_entity_delete_form($form, &$form_state, $did) {
    $form['Id'] = array(
        '#type' => 'hidden',
        '#value' => $did
    );

    return confirm_form($form, t('Are you sure you want to delete selected entity?'), 'module/entity/list');
}

I think you answered yourself :).  If you want to redirect back to the page the user invoked it from, set $path to current_path() when calling confirm_form.  Otherwise set $path to wherever you want them to go on cancel.


Drupal for Bloggers: How can I achive getting such a little FB, Twitter, etc. Box on the left of my homepage? How can I achive getting such a little, sticky FB, Twitter, etc. Box on the left of my homepage, like one can find on this site:
http://www.marieforleo.com/2010/04/real-online-paid/

Any ideas - or is there a module for that?
Sorry I don't know what this little box is called ...

Many thanks!
Soezkan

You want to try something like the ShareBar in Drupal 7.

  The Drupal Sharebar module lets you easily add a "floating" social
  media submission bar on your website (like that found on Mashable)
  that includes share buttons for the most popular social media websites
  online such as Facebook, Twitter, and Google +1 Buttons.


Where to add CSS and Javascript directives so they are inserted into the header? I am attempting to make use of a jQuery script that will enable a "slider" or "slideshow" on my Drupal 7 front page. The instructions for the jQuery plugin (called FlexSlider) say to insert the following items into the header of the page where I want to use the plugin.

<!-- Place somewhere in the <head> of your document -->
<link rel="stylesheet" href="flexslider.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">`</script>
<script src="jquery.flexslider.js"></script>

The problem is I don't know where in my template file I place these directives. I am using a custom front page for Drupal so I have a template file named page--front.tpl.php. Do the directives go in there or some other location?

The best way to do this is to add the files inside your theme's info file. However you shouldn't need the jquery file, this is included in Drupal core.

scripts[] = scripts.js
stylesheets[all][] = style.css

Morea bout info files here: http://drupal.org/node/171205


Cache page based on cookie value and URL I am working on a site that is multi-lingual as well as multi-country. This means that pages will show content differently depending on a country cookie that is set when the user first visits the site. I used taxonomy tid's for the cookie's value, so there was no issue with case sensitivity, etc.

The problem is that Drupal's cache_page table indexes content by URL only, so users with different countries but the same URL all get the same content. I was able to get the effect I wanted just by modifying the mod_rewrite implementation:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} !(cid)
RewriteCond %{HTTP_COOKIE} (?:^|;\s*)country=([^;]*)
RewriteRule ^(.*)$ $1?cid=%1&%{QUERY_STRING} [L,R=302]

RewriteCond %{QUERY_STRING} ^$
RewriteCond %{HTTP_COOKIE} (?:^|;\s*)country=([^;]*)
RewriteRule ^$ /?cid=%1 [L,R=302]

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

I did have to disable the ExpiresDefault directive, as it was causing the browser to remember old content when the user switches countries.

The resulting cid's in the cache_page table look like this:

http://example.com/pagename?cid=98
http://example.com/pagename?cid=256

This post isn't so much of a "help me I'm stuck" but a "I had this problem, and here's how I solved it. Can you think of a better way to do this?"

You can do it without .htaccess rules.

Drupal core cache; modify in your settings.php file (apache only). From http://drupal.org/node/361832#comment-4204294

<?php
// Check if cookie is set.
if (!empty($_COOKIE['my_cookie'])) {
  // Add cookie value to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['my_cookie'];

}
// Disable page cache if cookie not set so your magic code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}
?>

Memcache
http://drupal.org/node/942914#comment-4477150


Domain Change from .com to .org My company wants to change the domain from domain.com to domain.org, how would we do that according to moving the theme, all files, modules, etc. and keeping the Drupal integration intact?

Unlike Wordpress, Drupal doesn't care on the hostname. Unless you statically mentioned the domain in any custom modules/themes, this will be a straight forward change.

Change the domain name using a local host file.
Change the trusted hosts configuration (for D8, in settings.php)
Try accessing the site after the drupal clear cache, using drush.

If you are experiencing any issues, try searching for domain.com using grep and replace. Better to refactor the code without the domain hardcoded.

Edit: The links hard coded in WYSIWYG editors like ckeditor can create issues. You may have to update programatically or manually.

Edit2: You can use pathlogic module (not tested, d8 version is usable). to reformat the URLs in the content.


Hooking into a contrib module I've installed a contrib module in Drupal 7 and would like to hook into it.  However, the documentation for the contrib module is sparse and doesn't list the available hooks, though it implies that there are some.

Is there a standard "Drupal way" of seeing what hooks a contrib module exposes?

(I've deliberately not mentioned which module this is as I'd like a generic answer if one exists.)

By convention a lot of modules include a modulename.api.php file in the root folder, which describes the hooks implemented.

They may also implement hook_hook_info() to programatically describe the hooks to Drupal.

If that file isn't there, have a look at the other documentation/non-code files included. Sometimes you'll find examples elsewhere in the folder structure.

There's nothing enforced, though, so there isn't a generic all-encompassing answer. For a low tech solution you could grep the module folders for patterns like

module_invoke('modulename
module_invoke_all('modulename
module_implements('modulename

If you use the grep method, remember to add a conditional for the quote before the module name, it could be single or double.

In case the above causes confusion:

By convention most hooks are prefixed with the module's name, so that method will work 99% of the time, and avoid false-positives when a module invokes hooks for anything other than itself.

There will be the odd instance when it doesn't, but since there's no formally enforced way for a module to define hooks, anything non-manual here is going to be a best effort however you look at it.


Rules: Copying field from user's account to field in content type D7.
Using the File Field Rules module, I am trying to copy the content of the image field of the user's account ("picture") to another image field ("field_node_image") in the same user's image gallery (each user has his own photo gallery.)

The purpose of this is for when a user uploads a picture to his account profile, a copy of it is also posted in his image gallery along with all the other pictures he may post there (displayed via Views.)

The module requires the selection of a source entity and a destination entity. Then a field is chosen from each entity.

I am making the event react upon updating the user's account, so that gives me access to the "account" selector for the source entity where the module finds the "picture" field.

But I need help in finding the destination selector. This, evidently, should be a node since the gallery is a content type. It also has to be a node that belongs to the user. But all base selectors I have begin by "site" or "account."

Can anyone help me find this second selector?

Thanks. :)

I think you need to add some more stuff in that Rule; namely, following from your explanation, you need to:

"Create a new entity": Create a new node in an action, before the image-copying action. This new entity is a Gallery-type node.
Use the "entity_created" variable as the destination entity.

That should be enough to accomplish your goal, hope this helped some!

Appendix A: An export of such a Rule that worked.

{ "rules_196457" : {
    "LABEL" : "196457",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "file_rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "NOT data_is_empty" : { "data" : [ "account:field-user-image:file" ] } },
      { "NOT data_is" : {
          "data" : [ "account:field-user-image:file" ],
          "value" : [ "account-unchanged:field-user-image:file" ]
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "article",
            "param_title" : "New pic for [account:name] | [site:current-date]",
            "param_author" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "new_article" : "Created entity" } }
        }
      },
      { "file_rules_copy_file" : {
          "source_entity" : [ "account" ],
          "source_field" : "field_user_image",
          "destination_entity" : [ "new-article" ],
          "destination_field" : "field_image",
          "remove_source" : "0"
        }
      },
      { "drupal_message" : { "message" : "A new Article has been created with the new user\u0027s image" } }
    ]
  }
}

Appendix B: An screenshot of the Rules UI


Set defaults for new content types I have to make a lot of different new content types. It will save me some time if the defaults (promote to frontpage etc) are set to my preferences. How can I do this?

I hope you get my question

It's quite simple, if you want to change a content type default setting, just change it in :

  Administration » Structure » Content types » Edit a content type

Everything you change in the "global" content type settings will be default when you add a new node of this content type.

In the case of a Basic page, it will be this page (admin/structure/types/manage/page) :


Views slideshow with pagination Basically i need to create slide show same like this one example.

In this slide show there should be pagination like (1,2,3,4) and i need text and picture should refer to another content type and this text must be taken from the content type(for example the first 100 characters.
How to achive this? what modules is best for this. any example will be nice.
I found some examples with views and slideshow module, but most problem is pagination and how to get the text from content type to show it on a slideshow.

add field row number
and uses this field in style:
and set field to control


Tag & vocabulary module or technique that mimics stack exchange tag behavior? I am looking to recreate the tagging functionality of stack exchange:
- enter tags on a single text input line, with comma separation.
- add new tags to the taxonomy
- increment count of existing tags
- inline suggestion based on initial character entry

Is there a Drupal module or set of tools that provides this functionality?

The Autocomplete Deluxe module is perfect for this. It adds an enhanced autocomplete element, that uses the JQuery UI autocomplete. Although it will not provide the term count, the behaviour is similar to stack exchange in every other way.


How do I change a field type from integer to decimal? I have some fields type integer that are already populated, is possible to change the fields from integer to decimal?

Ok, I found a good solution to solve my problem.

Modules required

Helper
Devel (this is not strictly necessary)

Steps

Enable Helper module;
Enable Devel module;
Enable the block Execute PHP;
Paste and execute this code in the block: FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
Edit display format for node where the field is being used;
Edit Views where the field is being used to fix the format settings (If necessary);

If you don't want use Devel and can use Drush:

Enable Helper module;
create a new file in root Drupal folder, i.e. name it: intToField.php

<?php
FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
?>
launch the drush command: drush src intToField.php
Delete the file;
Edit display format for node where the field is being used;
Edit Views where the field is being used to fix the format settings (If necessary);


How to set pragmatically Minimum order subtotal limit in Ubercart Drupal? I am using the Ubercart module for my site. And I need to set Minimum order subtotal pragmatically not for admin panel. I am going to create a custom module to apply this condition but not getting any hook.

Any suggestions?

If you would like to validate minimum subtotal directly in the cart, you could use hook_form_alter.

function mymodule_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'uc_cart_view_form':
      //add own validate function
      $form['#validate'] = array('mymodule_subtotal_validate');
    break;
  }
}

Then define the content of the validation function:

function mymodule_subtotal_validate($form, &$form_state){
  //validate only if we are going to submit the cart form
  //there are others possibilites, when the validate handler is called,
  //such as quantity change, etc..)
  if(isset($_POST['op']) && $_POST['op'] == t('Checkout')){
    //access cart items and their quantity
    $sum = 0;
    foreach($form_state['values']['items'] as $key => $item){
      $product = node_load($item['nid']);
      $qty = $item['qty'];
      $sum += $product->price * $qty;
    }

    if($sum < YOUR_SUM){
      form_set_error(null, 'Your items subtotal is less than minimal subtotal.');
    }
  }
}


how can I have Infinite pager in mini_page views? I need my minipager to go infinite. I mean when it get to the last record to jump to the the first one. If it goes to the last one jump to the first one? How can I achieve this. I am using views to display my information. But I just want it to use it in a particular view. I don't want it to be default for all my views.

I use this reference views mini pager. In order to do this in your template.php you need to call the function for that view mini pager. In order to find out which is the best for you, use the theme developer module.

The trick is to change what happens when empty($li_previous)) and (empty($li_next)). If there is a better way to accomplish this, please let me know.

function my_theme_name_views_mini_pager__yourview($variables){

  global $pager_page_array, $pager_total;

$tags = $vars['tags'];
  $element = $vars['element'];
  $parameters = $vars['parameters'];
  $quantity = $vars['quantity'];

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;

  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number

  $pager_max = $pager_total[$element];
  // End of marker calculations.

  if ($pager_total[$element] > 1) {
  $li_previous = theme('pager_previous',
  array(
  'text' => (isset($tags[1]) ? $tags[1] : t('')),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
)
);

if (empty($li_previous)) {
  $li_last = theme('pager_last',
   array('text' => (isset($tags[4]) ? $tags[4] : t('')),
  'element' => $element,
  'parameters' => $parameters));

  $li_previous =$li_last;

}

$li_next = theme('pager_next',
  array(
  'text' => (isset($tags[3]) ? $tags[3] : t('')),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
)
);

if (empty($li_next)) {
  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('')), 'element' => $element, 'parameters' => $parameters));
  $li_next = $li_first;

}

$items[] = array(
  'class' => array('pager-previous'),
  'data' => $li_previous,
);

$items[] = array(
  'class' => array('pager-current'),
  'data' => t('@current of @max', array('@current' => $pager_current, '@max' => $pager_max)),
);

$items[] = array(
  'class' => array('pager-next'),
  'data' => $li_next,
);

return theme('item_list',
  array(
  'items' => $items,
  'title' => NULL,
  'type' => 'ul',
  'attributes' => array('class' => array('pager')),
)
);

}

}


How to hide group header in grid style View? How can I hide the headers of the groups in views (Art, Society and Culture) ?

this is a grid style view of taxonomy grouped by parent term (Drupal 7)

Several options :

hide the relevant elements with CSS.
override the relevant template to prevent the output of the field.
depending on the view, tick the checkbox to not display the field in the field properties.


Why I'm not able to debug twig templates? sites/default/files/php directory is empty As in question. I'm following this tutorial: https://dev.acquia.com/blog/debugging-drupal-8/debugging-twig-templates-in-drupal-8-with-phpstorm-and-xdebug/25/08/2016/16586

but directory

  sites/default/files/php/twig

is always empty

I'v tried cr all, checked file system page, did drush cron, checked theme page - no errors.

I got some errors related to permissions at theme settings page, but:

  chmod 777 -R sites/default/files

seems to solved those.

Any advices?

Probably the directory sites/default/files/php/twig is empty because the container parameter twig.config.cache is set to false.

The approach used in the linked article is arguable.. put a breakpoint in every twig compiled template is not a viable solution. For debugging twig templates with xdebug there are better alternatives:

use the devel module + this patch (Committed)
use the twig_xdebug module


Programmatically Place View With Defined Fixed Contextual Filter I'm currently using the starter module which adds the Twig function place_view(). This works well in most cases, however I'd like to be able to pass another parameter to populate the fixed value given in a contextual filter.

This would be my contextual filter settings:

Here's the place_view() Twig function:

public function place_view($name, $display_id = 'default') {
  $drupal = \Drupal::service('renderer');
  $view = views_embed_view($name, $display_id);

  if(! is_null($view)) {
    return $drupal->render($view);
  }

  return null;
}

Preferably I'd like to be able to use place_view() with a parameter to adjust that fixed value. It'd be even better if I could somehow reference the contextual filter I wanted to adjust the fixed value of.

Hopefully that all made sense, thanks in advance.

Use views_embed_view:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  // Remove $name and $display_id from the arguments.
  unset($args[0], $args[1]);

  $view = Views::getView($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return [
    '#type' => 'view',
    '#name' => $name,
    '#display_id' => $display_id,
    '#arguments' => $args,
  ];
}

Btw. Twig Tweak maps this function one to one:

  {# This accepts views arguments as well. #}

View:

{{ drupal_view('view_name', 'page_1') }}

Example

So if you want to filter the node 123 in the contextual filter you've shown in the question, you use this as third argument:

PHP

views_embed_view('view_name', 'block_1', '123');

TWIG (using the module Twig Tweak)

{{ drupal_view('view_name', 'block_1', '123') }}


Requestee user cannot remove a one way User Relationship with requester user I have a one-way User Relationship which also can be reciprocated, and I have run into an issue where users cannot remove a one-way relationship with another user that they have previously approved.

For example, User B sends a one-way relationship request to User A. User A approves it. Then, User A decides they no longer want to have that relationship with User B, and they click the link to remove that relationship (for example, https://mywebsite.com/user/778/relationships/requested/3338/remove). The relationship is not removed, and User A is presented with this message: "No action has been taken". There is nothing in the Recent Log Messages that would point to any specific issue, and all of the Have/Maintain/Request/Delete permissions are enabled for Authenticated and other specific user roles that these users have.

How can I fix this, so that User A has total control over which approved relationships they have with User B?

I applied the patch listed here (https://www.drupal.org/node/1328170#comment-6980582) and that resolved the issue.


An error which appears in Autocomplete taxonomy fields Did someone ever note this annoying D7 taxonomy error? It jumps out when I seem to "pass" a certain amount of terms or characters. The error is as follows:

  An AJAX HTTP request terminated abnormally. Debugging information
  follows. Path:
  http://pancherim.co.il/taxonomy/autocomplete/field_engines StatusText:
  ResponseText:  ReadyState: 4

In my case I get this exact error when using Views. It happens when I try to save changes in a given view and I click too quickly to start another action, while the ajax loader of the previous action hasn't gone away. Basically it's moaning that I should wait for one action to finish before starting another.

In your case, maybe the ajax request isn't fast enough to go and grab an existing match for the taxonomy term(s) you're adding in order to autocomplete it. Do you have enough memory allocated to Drupal in your machine/server?

If you're using the admin overlay, another trail to follow is comment #10 in this issue


Adding a custom data-attribute to a field in Views In a view I need to add a custom data-attribute to the row output (just like classes are added). Simply rewriting the output doesn't work because XSS attribute filtering strips the attribute.
How can I accomplish this in a reasonable way?
These answers are for D7 and do not quite cover dynamic output:

Custom attribute in views fields

How to add data attributes to view list <li> tags?

To summarize for future reference:

You can add data attributes using Rewrite in Views Fields.

If you added a custom data-attribute but something isn't working, the problem might be in the value ;)

What gets stripped by the filter_xss_admin() on Rewrite is most notably the <object> tag and style="" attribute because users can submit malicious code through those.

It seems Views for D7 will have that check removed in the next release: Remove filter_xss_admin() from result rewriting because views editors are already trusted admins


Why is drupal_json_output only returning page HTML? I'm trying to get drupal to return some rendered views content that I request through ajax, but all it seems to want to output is what looks like a rendered page. What am I doing wrong here?

// This is logging a ton of page HTML

jQuery(function($) {
    $.ajax({
        url: 'fetch/explore/' . category,
        success: function(data) {
            console.log(data);
        }
    });
});

// This is from my custom module

function wdfm_menu() {
    $items['fetch/explore/%'] = array(
    'page callback' => 'fetch_explore_content',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
        'page arguments' => array(2)
  );
    return $items;
}

// Nothing is showing up in my log from this so I'm unsure it's even being called.

function fetch_explore_content($category) {
    watchdog('blargh', 'something');
    $data = array();
    $data['test'] = 'test';

  drupal_json_output($data);
    exit;
}

You have an error in your Javascript, you're trying to use PHP syntax to concatenate the URL (the . symbol). As it is you JS shouldn't be running at all which is why the callback isn't being called. Your module code looks fine. Just change your JS to this:

jQuery(function($) {
  $.ajax({
    url: 'fetch/explore/' + category, // + instead of .
    success: function(data) {
        console.log(data);
    }
  });
});

Just to clarify, if the ajax call is going through despite the syntax problem the HTML response you're getting might be a 404/403/500 error page caused by the wrong URL being called.


How to change the default search button value in awesome zymphonies free theme? please have a look at the site, http://35.187.238.51/jrdtml/. This is a prototype site of the library I'm working for. I'm using Drupal 8.4 with Awesome Zymphonies free theme. I would want to change the text in the default Search box from 'Search' to 'Site Search'. Also I would like the Search box to appear in different pages other than just the Home page.

Thanks for your attention.

Best, Francis

How to override the search text string

For how to change the text of the search box, you'll need to do a string override.  See the answer to this question on how to write your own custom module to do this.

Drupal also has a String Overrides module so that you don't have to write your own code, but it's not ready for Drupal 8 yet.  There is a test version here but it's not safe for production sites.

A third way to do this-- and perhaps the easiest approach if you will be changing lots of Drupal interface text-- is to add "English" as a translatable language on the language settings page (admin/config/regional/language) and then disable the original "English."  What this allows you to do is "translate" any text that appears in the Drupal UI.

How to show the search box on other pages

The search box is (most likely) a block that can be controlled on the block administration page: /admin/structure/block.

You can edit the block settings to choose which pages it appears on.  You can also place additional search blocks and then edit the settings to show them in different places on different pages.


If not hook_init(), what can be used for cached pages? I created a module to keep query_string laden links from a client site active (per client's request, background question here).

This code works wonderfully when I'm logged in (as user 1); however, I have later found that hook_init() does not run on cached pages.

Should I place this logic into another hook? Should I take a different approach to intercepting and mapping these legacy links?

<?php
/**
 * Extends hook_init()
 *
 * Intercepts vidID or PID and forwards to the page's proper Drupal node.
 *
 */

function module_init() {

    if (!menu_get_item($_GET['q'])) {

        $pid    = isset($_GET['PID']) ? $_GET['PID'] : FALSE;
        $vidID  = isset($_GET['vidID']) ? $_GET['vidID'] : FALSE;

        if ($pid) {
            // handler code
        }
        elseif ($vidID) {
            // handler code
        }
    }
}

I think you are asking the wrong question.

If a page is cached, it means that it got generated and cached at some point. At this point, your code in module_init() did run. If your code generated a redirect (via drupal_goto()), this redirect will get cached.

There should not be anything wrong with this scenario, so maybe you should just clear the cache once?


Why can't I edit Views in Drupal 6 since moving the site? I moved a Drup-al 6 site from one hosting server to another, exporting and re-importing the DB. Everything works well but for some reason I can't edit anything in the views. Each time it says page not found which is really odd. Has something happened with paths?

I've tried rebuilding menu structures and cleared all caches etc.

Thanks :)

I think something went wrong with SQL queries when importing the DB. Can you check if views_display and views_object_cache tables are consistent?

I would try to export each view using the Export function from the old site and then import those in the new site.


Change the confirm_form message of an entity made with eck I have an entity created with eck module, and when I want to delete an entity the message is :

Are you sure that you want to delete %id ?

I want to change this message to show me the title of the entity and not the id.
I find where this is implemented, is in the code below in eck.entity.inc file located under the eck module folder:
function eck__entity__delete_form($form, &$form_state, $entity_type, $bundle, $id){
  $path = eck__entity_type__path();

  $entities = entity_load($entity_type->name, array($id));

  $form['entity'] =
      array(
        '#type' => 'value',
        '#value' => $entities[$id],
  );

  $form['entity_type'] =
      array(
        '#type' => 'value',
        '#value' => $entity_type,
  );

  $form['bundle'] =
      array(
        '#type' => 'value',
        '#value' => $bundle,
  );

  $form['submit_redirect'] =
  array(
    '#type' => 'value',
    '#value' => "{$path}/{$entity_type->name}/{$bundle->name}",
  );

  $message = t("Are you sure that you want to delete %id",
          array("%id" => $id));

  $caption = t("This action cannot be undone.");

  return confirm_form($form, $message, "{$path}/{$entity_type->name}", $caption, t('Delete'));

}

Is there a way to change this confirm message without changing the code of this module ?
thanks in advance

You can use hook form alter to change a piece of the form, see this answer by Clive:

https://stackoverflow.com/questions/8111034/altering-title-on-drupal-node-delete-confirmation-form


Add field date to views tpl I had this issue before which I solved:
Add field date to node tpl

Now I need to add the date field in the views.tpl.php

Here's the code:

I want to replace "$date->node_created" with the field_date.

Here's what I know: I can't use $content['field_date'] because the $content array doesn't exist in this template file.

Thank you

To know what fields you have available to your View, you can use a custom module, and there you write the following:

function hook_views_pre_render(&$view) {
     if($view->name == "YOUR_VIEW_NAME"){
         foreach($view->result as $key => $r){
             echo "<pre>"; print_r($view->result[$key]); echo "</pre>";
     ....
         } // foreach
      } // if view->name
} // function


Overwriting database with backup from older Drupal version? I have a database from a live site I need to bring over to a development site.

live site = d7.7, outdated modules, but is obviously up to date with all the recent ubercart orders

dev site = d7.15, all modules updated, but is missing the latest ubercart orders

I had been migrating the live DB over to the dev site periodically, but now that the dev site is running newer modules and core, I'm wondering if its still safe to move migrate the database from the live 7.7 site.

can I migrate the database and simply run update.php afterward to catch up?

ubercart orders are really the only thing im concerned about. also, ubercart is one of the modules that has been updated on the dev site.

Complete list of modules that have been updated on the DEV site. Some of these required the running of update.php

Drush
CTools
Ubercart
Views
Entity
Token
Securepages
Rules
Admin Menu
Node Export
UUID
Pathauto
Gallery formatter
Twitter Pull

Yes - in most cases, this should be a fairly straightforward operation. You should be able to migrate your updated modules from dev over to the live site and just run update to get everything running again. If there are going to be issues with this (for ex. a module that requires a little more configuration to get working), you can isolate these issues before-hand on your dev server (and it sounds like you've already done this successfully).

Most of the top contrib modules (ex. the ones you cite above) will be very careful at upgrading their structure without impacting any new data (or orders).


Core request handler documentation maybe has conflicting information? I wanted to confirm with the community and maybe get some clarity about D8 Documentation:

On the Core request handling system ported to Symfony2 framework page it states:

  The PHP superglobals for $_GET, $_POST, and $_SERVER are deprecated
  and should not be used, ever.

However, I can't seem to locate this information on php.net. PHP setting register_globals is deprecated. Is this what they are refering to or did I miss something huge in recent news? No longer able to use $_GET in our custom modules for D8?

I'm pretty sure the advice stems from this issue: Replace almost all remaining superglobals ($_GET, $_POST, etc.) with Symfony Request object. The opening gambit from that post is:

  In order to depend on using the Request object to determine caching, we need to ensure that everything uses it, rather than raw PHP variables for $_SERVER, $_REQUEST, $_GET, $_POST.

I don't the quoted comment is suggesting they're deprecated in PHP as such, just that using them in Drupal isn't going to be reliable.


Why the core migrate modules won't be enough? I've seen that Drupal 8 comes with 2 core migration modules; These are "Migrate", and "Migrate Drupal".

My question: if we want to migrate SQL from a Drupal 7 site to our brand new Drupal 8 site, why aren't these two enough, and why do we also need to download the module Drupal Upgrade? Wasn't there a plan to make the process free of any contrib modules whatsoever?

This is asking two questions. 1) What do I need beside core for migrating to D8 from D7. 2) What is Drupal Upgrade.

If all your fields and data in D7 are core fields, then you do not need anything from contrib. If you have non-core fields i.e. userpoints, then you'll need source and destination migrate plugins for those non-core field types. Same applies to any non-core Drupal data.
Core does not currently have a UI. It is in the works, but until then if you want a UI, use Drupal Upgrade. Or you can use drush and migrate_tools. Mike Ryans's blog post provides a  break-down of the current module landscape for D8 migrations.

Lastly, if you are trying to suck in strait SQL data, the above mentioned blog post provides some suggestions.

  In migrate_plus, open up migrate_example/README.txt and it will guide
  you through the basics of implementing SQL-based migrations. It's
  simpler than you think!


Redirect from root and not page itself So I want to provide similar redirection logic as we have on drupal.org and redirection to dashboard to logged in users but also allow access to the /front page. I can't seem to get it to redirect ONLY on front page. Here is the current code I have:

function MYMODULE_init(){
  global $user;
  if(drupal_is_front_page() && user_access('view own dashboard')){
    drupal_goto('user/'.$user->uid.'/dashboard');
  }
}

It is also redirecting the page itself to the dashboard still and not simply the <root>

I think you should be using hook_user_login instead of hook_init.


How to make a required / not required one field depending on value of second field (Drupal in registration form) Below is an example of code that makes the first field not required in the form

<?php
    function мой_модуль_form_alter(&$form, &$form_state, $form_id){
    $form['field_website']['und'][0]['#required'] = FALSE;
    }
?>

$form['test']['und'][0]['value']=test;

But I need to check the content in the second field after sending the form, and if it coincides with the value of "test", then the first field became not required.

if($form['test']['und'][0]['value']=='test'){
    $form['field_website']['und'][0]['#required'] = FALSE;
}


xautoload classes in subfolders I have issues autoloading classes found in subfolders of my module with xautoload.

my module is called myentity

Here is my hook_entity_info

function myentity_entity_info() {
    $return['myentity'] = array(
        'label' => t('My entity'),
// The entity class and controller class extend the classes provided by the
// Entity API
        'entity class' => 'Drupal/myentity/class/MyEntity',
        'controller class' => 'Drupal/myentity/controller/MyEntityController',
        'base table' => 'myentity',
        'fieldable' => TRUE,
        'entity keys' => array(
            'id' => 'me_id',
            ),
        'bundles' => array(
        'myentity' => array(
            'label' => 'myentity',
        // Information below is used by the Field UI - they "attach" themselves here and lets us
        // do the standard field management that all the core entities enjoy.
            'admin' => array(
                'path' => 'admin/structure/myentity/manage',
                'access arguments' => array('administer myentity'),
                ),
            ),
        ),
    'label callback' => 'entity_class_label',
    'uri callback' => 'entity_class_uri',
    'module' => 'myentity',
    'view modes' => array(
        'full' => array(
            'label' => t('Default'),
            'custom settings' => FALSE,
        ),
        'teaser' => array(
            'label' => t('Teaser'),
            'custom settings' => FALSE,
        ),
    ),
    'metatags' => TRUE,
);

return $return;
}

My class and controller are found in

sites\all\modules\myentity\lib\Drupal\class\MyEntity.php

with the following content

<?php

namespace Drupal\myentity\class\MyEntity;

/**
 * The class used for model entities
 */
class MyEntity extends Entity {

    public function __construct($values = array()) {
        parent::__construct($values, 'myentity');
    }

    protected function defaultLabel() {
        return $this->name;
    }

    protected function defaultUri() {
        return array('path' => 'myentity/' . $this->identifier());
    }

}

and

sites\all\modules\myentity\lib\Drupal\controller\MyEntityController.php

Bugs bugs bugs.

    'entity class' => 'Drupal/myentity/class/MyEntity',
    'controller class' => 'Drupal/myentity/controller/MyEntityController',

This should be

    'entity class' => 'Drupal\myentity\class\MyEntity',
    'controller class' => 'Drupal\myentity\controller\MyEntityController',

And:

namespace Drupal\myentity\class\MyEntity;

This should be

namespace Drupal\myentity\class;

(and btw, is "class" really a valid namespace part? Won't PHP complain?)

And:

sites\all\modules\myentity\lib\Drupal\controller\MyEntityController.php

This should be:

sites\all\modules\myentity\lib\Drupal\myentity\controller\MyEntityController.php

EDIT: One more:

class MyEntity extends Entity {

should be

class MyEntity extends \Entity {

Because class Entity is in root namespace.


Problem with enabling the Optimizing js files I have installed the events and signup modules. The events appears in a calender. All were working fine. But when I enabled the optimizing JS files on the performance page Now the events does not display for the anonymous and authentication user. Now they are only available for the administrator.
I again the disabled the optimizing JS files on performance page but still events are not displaying.

Can someone tell me what is the problem?
I am using drupal 6.

Give AdvAgg a try. If JS Aggregation doesn't work, go to admin/reports/status and see what AdvAgg says; it has tests for just about every scenario that would cause JS optimizations to not work.


How to include cck field image in Forward module template (forward.tpl.php) I'm using the Forward module and need help adding a custom field into the forward.tpl.php template.  I've found a similar thread on d.o:
https://drupal.org/node/2078479

However, this is for using user profile fields, not node fields.  Here is the code that I came up with, but it's not fully working:

<?php
$path = drupal_get_normal_path($_GET["path"]);
$path = explode("/", $path);
$nid = $path[1];
$forwardthumb = node_load($nid);
$img_uri = $forwardthumb->field_thumb['und'][0]['uri'];
$fid = $forwardthumb->field_thumb['und'][0]['fid'];
$thumbfilename = file_load($fid)->filename;
$derivative_uri = image_style_path($style, $image_uri);
$success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
$new_image_url  = file_create_url($derivative_uri);
?>

In my testing, I've gotten the following text to output in my forwarded-email:
http://mysite.com/sites/default/files/styles/blog_thumb/public

(from the $new_image_url variable)

Which tells me that I've got it partially working, as it was able to indicate the correct folder / location... but I was never able to actually get it to spit out my image-file-name (e.g. thumbnail.png), just the path to the folder containing my image. Please let me know what I'm doing wrong?

Seems like part of this is a bit wonky, as it seems the $node variable in the template isn't the same $node variable used elsewhere in Drupal...?

[Edit] Wanted to also share the code that WORKS in a node.tpl file, but not in forward.tpl:

<img src="<?php print file_create_url($node->field_main_blog_image['und'][0]['uri']); ?>" />

But, when I set this code up in forward.tpl:

$path = drupal_get_normal_path($_GET["path"]);
$path = explode("/", $path);
$nid = $path[1];
$forwardthumb = node_load($nid);

And:

<img src="<?php print file_create_url($forwardthumb->field_main_blog_image['und'][0]['uri']); ?>" />

No luck...

Posted my solution on Drupal's site, the forward module issue queue:

https://drupal.org/node/2107769


How does the events dispatcher map to map_save to a callback function? MigrateEvents.php contains an event definition like this:

/**
 * Name of the event fired when saving to a migration's map.
 *
 * This event allows modules to perform an action whenever the disposition of
 * an item being migrated is saved to the map table. The event listener method
 * receives a \Drupal\migrate\Event\MigrateMapSaveEvent instance.
 *
 * @Event
 *
 * @see \Drupal\migrate\Event\MigrateMapSaveEvent
 *
 * @var string
 */
const MAP_SAVE = 'migrate.map_save';

If I grep the codebase for map_save, there is no other reference to it. What mechanism does Drupal/Symfony use to know the callback to call?

This event is fired by \Drupal\migrate\Plugin\migrate\id_map\Sql::saveIdMapping().

$this->eventDispatcher->dispatch(MigrateEvents::MAP_SAVE, new MigrateMapSaveEvent($this, $keys + $fields));

To listen and react to this event you need to add a new service that implements \Symfony\Component\EventDispatcher\EventSubscriberInterface and tag it with 'event_subscriber'.

This is what you find in content_translation.services.yml.

content_translation.updates_manager:
  class: Drupal\content_translation\ContentTranslationUpdatesManager
    arguments: ['@entity.manager', '@entity.definition_update_manager']
    tags:
      - { name: event_subscriber }

This tells the event dispatcher the ContentTranslationUpdatesManager class subscribes to events.

When you look at \Drupal\content_translation\ContentTranslationUpdatesManager::getSubscribedEvents() you can see that it subscribes to the \Drupal\Core\Config\ConfigEvents::IMPORT event and when this event fires, the \Drupal\content_translation\ContentTranslationUpdatesManager::onConfigImporterImport() method should fire, with a priority of 60. Note that priority works in reverse to the typical Drupal weight: This listener goes before those with a lower priority and after those with a higher priority.

You can read about the generic event dispatcher in the symfony documentation.

The Drupal relevant bit here is the event_subscriber tag, which is processed in a compiler pass by \Drupal\Core\DependencyInjection\Compiler\RegisterEventSubscribersPass::process(), taking care of the registering of listeners automatically, based on the presence of that tag.


Drupal HTML.tpl.php file won't effect site? My aim is to allow zooming in and out in mobile devices in my responsive Drupal 7 site. I have followed a Drupalize.me video and some more documentation that teach how to allow it via my theme's HTML.tpl.php and added the marked row there (Image attached), yet nothing happened. Maybe it should go to the system's HTML.tpl.php instead? maybe there is something to apply at the Drupal UI so that the site would be affected? P.S - I've cleared the Drupal cache.

There are several ways to achieve this.

You could hand code the meta viewport tag in your html template file as you did. The proper tag may need to be used as shown below:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

You could also use a page alter to add the html to your page as shown below (place in theme template.php):

function YOURTHEMENAME_page_alter($page) {
  // Viewport array, change values in content below.
  $viewport = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' =>  'viewport',
      'content' =>  'width=device-width, initial-scale=1.0, user-scalable=yes'
    )
  );
  // Drupal add HTML head.
  drupal_add_html_head($viewport, 'viewport');
}

Or you could use the viewport module

Note: Do not alter the system html template file, puppies will die!