If there is no nodes in current taxonomy term to display, load vocabulary and display other difficult to formulate a question

I have made a View, which display title, image, body(trimmed) on nodes pages with Content type - Home, its related nodes to this one(. Home has different categories - taxonomy, for example looks like this:

Homes one
homes two
homes three

So for example if my current node has taxonomy term - homes two i should display only nodes(title, image, body(trimmed) of this term. I did it like this - with contextual filters Content: Nid - i exclude current node to not display it in my view and

Content: Has taxonomy term ID

When filter is not available - i provide my own value, php code:

 $node = node_load(arg(1));
 if($node) {
 foreach($node->field_home_category[LANGUAGE_NONE] as $term) {
    $terms[] = $term['tid'];
 }
    return implode('+',$terms);
  }
  else {
    return
  }

$node->field_home_category[LANGUAGE_NONE] -  is a field which contains taxonomy term id.

And its works fine, but if my node is only single in homes two taxonomy term, the view returns nothing(for obvious reasons) and if this happens i need to display any other Home nodes.

I think i should load my taxonomy vocabulary and get all the terms and pass them to my view in this situation. Like this:

$tree = taxonomy_get_tree(2); // vocabulary id - is 2
    foreach ($tree as $term) {
        $options[] = $term->tid;
      }
      return implode('+', $options);

but i dont know how to add this to my view.

Something like this ->

PSEUDO CODE:

IF THERE IS NO NODES IN CURRENT TERM
   DO
      LOAD VOCABULARY OF HOMES
    AND
      DISPLAY ANY AVALIABLE NODES OF THIS VOCABULARY

//////////////////////////////////////////////////////

I will post full solution, maybe helps someone:

//////////////////////////////////////////////////////

No results behavior is great, but there is few situations:

For example:

homes two contains 2 homes, one is excluded, so view will display only 1 home, but we need 3 homes to be displayed all the time.

What i did is created new view, which displays 3 homes randomly(global Random sort criteria)
and excluded nid in contextual filter, i allow to pass multiple values to nid.
and in THEME_views_pre_render(&$view) i did next thing:

function THEME_views_pre_render(&$view) {
  if ($view->name == 'home') { // check is this my view
      $args = $view->args; //passed arguments
      $results = &$view->result; // this is important , you should pass it by reference
      if (!empty($args) && isset($args[0]) && isset($args[1])) {
        $node = node_load($args[1]);
        if ($node->type == 'home') { // check node type
            foreach($view->result as $row) {
                $restricted[] = $row->nid; //push current nodes to array, to pass them later to our new view, to not display them
            }
            $result_count = count($view->result);
            switch ($result_count) {
                case 1: // if one home
                    //gett the results of my view which display all nodes
                    // and do not display node which already displayed
                    // aka $restricted array
                    $result_array = views_get_view_result('related_homes_and_features', 'block_3', $restricted);
                    //add this results to current view
                    //
                    array_push($results, $result_array[0],$result_array[1]);
                    break;
                case 2:
                    $result_array = views_get_view_result('related_homes_and_features', 'block_3', $restricted);
                    array_push($results, $result_array[0]);
                    break;
                case 3:
                    $result_array = views_get_view_result('related_homes_and_features', 'block_3');
                    array_push($results, $result_array[0], $result_array[1], $result_array[2]);
                    return;
                    break;
            }
        }
    }
  }
}

home that helps someone.

Use "No results behavior" of the view ; specify a new view ("Global: View area"), showing all nodes, excluding the taxonomy term "homes two".


How do I translate a meta tag? I want to translate the title meta tag added to views on a Drupal 8 site, but I didn't see any option in the Translate View section.

How can I translate meta tags?

I've added a title metatag to the default Content view. Then went to translation page where I found the string to translate under Displays-> Page Display Settings-> Display Extenders-> Test Metatags


Show announcement on the site I want to be able to show an announcement on the site that requires a confirmation by the user before it disappears.

Something similar to Absolute Messages but I don't want to have all status messages shown that way.

You can use jQuery for the this purpose. Simply use mouseover event on the  announcement DIV. Write a jQuery function to hide this DIV using .hide method of jQuery. like this.

$(document).ready(function() {
$("#announcement_div_id").hover(function() {
$("#announcement_div_id").hide();
});
});

Here announcement_div_id is the id of the div which you want to hide.


Are there any custom block type template naming conventions? With our ability to create custom block types and manually add additional fields in Drupal 8, is there a simple naming convention to create block--custom_block_type.html.twig to handle the layout of additional fields?

Example: using theme hook suggestions for content types: node--content_type.html.twig

Are custom block types able to be handled this way without going the module route?

Here's one way to do it, in a module or theme:

function MYMODULEORTHEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof \Drupal\block_content\BlockContentInterface) {
    $suggestions[] = 'block__' . $content['#block_content']->bundle();
  }
}

Results in template suggestions like:

block--custom-block-type.html.twig

The instanceof might be overcautious, take it or leave it.


How to display multiple taxonomy fields in a view I have a view that display data from nodes (it's a listing of books).
Next to each rows, I need to display some icons that represent different category per book. Per example, a book could have the categories "For young adults, comic, black-white".

All the categories are in a taxonomy, and when the node is created, we select the ones we need.

Now displaying the field of the categories in the view doesn't work if I have more than one category selected.

I created a relation, allowing me to retrieve the images, but it only displays the first category selected.

How would I be able to display all of them ?

Thanks!

If you are willing to use Display Suite then you can get the kind of result you are asking for with configuration only (but with some limits on flexibility). The other alternative would be to do something with Views PHP.

The steps for configuring Display Suite to show taxonomy terms as images (from an image field you've added to the taxonomy) are:

Create a view mode for your taxonomy (or reuse, say, the tokens view mode). This view mode needs to show just your image image field. You can format it here, e.g. to a thumbnail or whatever works for you.
Create a view mode for your content type (or content types if more than one is involved). You could use the standard teaser view mode or add a custom one for this purpose. Add the fields you want from your node and also add the term reference field.
For the term reference field select the Rendered taxonomy term FORMAT option. This then gives you a choice of view mode for rendering the term. Select whatever you used in step 1.
In you View select Show: Content | Teaser under the FORMAT section. (If you've made a custom view mode, then replace 'Teaser' with the name of your custom view mode.)

By using the Content option you lose some of the flexibility of using the Fields option Views. If that's an issue you may need to go the Views PHP route. Although, if it's a case of doing the sort of thing that Views does with Rewrites, you may be able to do some or all of by using Display Suite code fields or block fields.

This approach, of course, also allows you to use the images for taxonomy terms (single or multiple) in your default view mode as well. If you're new to Display Suite, this might be a fairly tricky configuration task - but once you're used to DS it's a pretty quick job.


Acquia Drupal 6 Multisite I am hosting an Acquia Drupal site on AWS:

I currently have 2 sites both located in the sites folder:

I am fairly new to working with Drupal Multi-sites and would like to know what is the best way to point to each folder's settings.php with this format and ignore the sites/default folder?

And if it would be simpler in another format what would you recommend?

Let me know if you have any questions.

Thanks!

Assuming you have your web server (Apache, etc) pointing both sites correctly to your docroot, then Drupal will automatically route requests to the correct folder (and settings file) for each domain.

If you want to have it ignore the default folder and its settings.php file, you can delete the existing "default/" folder and create a symbolic link to one of your other two sites. For example:

ln -s alumni.something.edu default

and all requests to your docroot that don't match a domain in your multisites folder will be sent to alumni.something.edu (or whatever you prefer).


Subtheming -  what happens with parent theme's style.css Trying to pin down in better details the steps involved when sub-theming, I can manage to get a sub-theme up in D, but there is  a question I still have, concerning the style.css that is unfortunately not clear in my head. Is the sub-theme's style.css supposed to come from the parent theme or from subtheme?

The example I have show the subtheme as having no style.css. I tried the advice and flushed style.css, created an empty simpleblueMaster.css, added it to file[] in the .info file.

Author stated that css styles from parent theme will be loaded to be overridden if needed by sub-theme, and this totally makes sense.  Unfortunately this is not the case on my installation and I would of liked to confirm the expected behavior.

THe author erases all css and images in his sub-theme, except if I do that in mine, nothing works. Parent theme's style.css does not seem to load and I assumed it should be. Anyone know what happens to style.css in sub-themes?

Or what could be preventing parent theme's style.css from not loading, if it should be?

Any insight appreciated, Thanks all!

Update:

Basically, there are 2 main ways (ok, probabably more I don't know of!) for a sub-theme  to override the parent theme's css.

One involves copying the whole style.css in sub-theme and hacking on that. This works but a much cleaner approach as also mentionned in the answer is to not have a style.css in subtheme, and override with css in a sub-theme specific file.  If there is a better way, I'd be very happy to know!

Thanks all

You can choose which files you want to override in the parent theme... its as simple as including a copy of the files using the same name ex style.css just drop that anywhere inside your sub theme and tweak away.

Any file with the same exact names as files in the parent-theme will now default to the file that is in your sub_theme. So... if you still want the original style.css to load, do not add it to your sub-theme at all & instead create a custom.css and any similarly named style codes will default to the copy in your sub-themes css files first then if needed the original.

To add from your comment below, do not remove the style.css in the main theme unless you are going to bring in all of its code into your custom file.  What would be easiest for light edits would be to create a custom.css file in your sub-theme and only copy over the codes you need to tweak, if your going hog-wild just copy over the whole contents style.css

Hope that helps :)


Features installed with profile are overridden We are using workbench with the subpermissions module.  We have created two features which set custom permissions for workbench and for subpermissions.  If we install the workbench feature and then the subpermissions feature, both features show as Default and not overwritten.  If we install these two features last with a profile, both features show as overridden and the permissions are not correctly set.
Any idea why this is happening and how would we investigate?

thanks

Apparently things in a profile info file are loaded before things in a profile install file.  I moved the two features from the info file into the install file and put them last.  After a new site install, the features were not overridden and worked as expected.


Creating a content type with dynamic fields I'm trying to create a content type where the fields are updated dynamically. For example, I could have two term reference fields: Manufacturer and Product Name. When the user chooses the manufacturer in the form, the Product Name field would only display products that have the selected Manufacturer.

Whats the best way to approach this?

There is Conditional fields module, but stable version is available only for D6.


Why don't breadcrumbs appear on views generated pages? I'm maintaining a site I didn't build and I'm running into an issue with breadcrumbs. Pages generated by views don't seem to conform to the existing bread crumb system. For example I have a members section page, which has a sub page with a list of links. The links created from basic pages show the correct breadcrumb trail (i.e. home->members->subpage1->subpage2), while the views generated pages only show a breadcrumb trail back to home. So what is causing this? How I work the views pages in the breadcrumb system? Does each views page need it's own template?

Have you tried Views Breacrumb / Custom Breadcrubs / Views breadcrumbs modules?


Disabling the editing of Group Titles I'm trying to stop the editing of Group Titles (Content Types that are set as Groups) by users. With Drupal (v7.21) I've added Organic Groups (7.x-2.1) and set it so that the Group manager does not have full permissions. Instead I've created a Role for them called 'owner' and give them the ability to edit the group but not administer the group. I want them to be able to change the Group Body but not the Title. I have the Organic groups field access module installed and that lets me stop them editing fields like the Body but it doesn't allow me to stop them editing the Title. Does anyone know if there is a way to do this?

You could use either of these two modules Automatic Nodetitles or Automatic Entity Label to hide the title field. Use tokens to give the groups a name and hide the field on the edit form.


Not able to install modules I installed Drupal on my localhost (LAMP Stack), and I am trying to install modules, but I get the following error.

I tried changing the permissions of the folder, but still it is not working. It is showing same error from both the methods of installation.

It's not an error, but a warning reminding you that you aren't using an encrypted connection, and that the credentials you are using (username and password) could be read from somebody who can intercept the data exchanged between your computer and the server. If you look at the protocol used for the page, you will notice it's http://, not https://.
It's not an error caused from the file/directory permissions.

If you don't have a SSL certificate, just enter username and password that are accepted from the FTP server, and install the modules. The warning is just suggesting that using a secure communication would be preferable.

You could also avoid Drupal prompts for FTP/SSH credentials by setting the owner of the temporary:// directory (and its subdirectories) to the owner of the sites/default directory (which, in your case, I take is akshay).


How do you upload images to content other than articles How do you upload images to content other than articles? I tried adding  into the body of a block where I want a photo but it doesn't work. I've forgotten a lot of my html.

I'm doing something wrong. LEt's say, I want some sidebar blocks or even trtyptich blocks with an image in it. Do I start w/creating a view, a block, or an image that links to an article with the image and a caption showing in that block? That would help me immensely.

Enter images into your content fields. On Add content type, go to "Manage fields," and under "Field type" select "Image." This will allow you to upload an image into that content type. If you want to add a referent to the image with <img src="image URL">, I suggest you switching from filtered HTML to full HTML as input format of the node body.


How to redirect URL of kind node/nid to its url alias I want to replicate the effect seen in http://www.drupal.org/node/1 , where you are redirected to drupal.org/about.

I have a fresh Drupal 7 installation, I create a node with a path, and don't get the effect. I have tried with module Path Auto, and nothing.

Even though you've figured out a great solution, Rules may well be a module that can help you out with this for other problems you have in the future. Rules contains several options to fire off several events. For example, if you tell Rules to React on event Content is viewed, you can then set certain events, conditions, and actions. One of these Events will cause the user to be redirected to another page - not as simple as Global Redirect, but if there's something you need done before redirecting, this could do a lot for you.


How do I stop a module from installing optional configuration, or make sure it's installed by the time I want to remove it myself? I don't want the "Frontpage" view to be installed along with my installation profile.

I tried adding a hook_install to a module which does this:

\Drupal::entityTypeManager()->getStorage('view')
  ->load('frontpage')
  ->setStatus(FALSE)
  ->save();

But during installation that tells me that the frontpage view doesn't exist when my module is being installed. Fair enough, so I added the module that owns the frontpage view config (core node) to my dependencies:

dependencies:
  ...
  - drupal:node

Still didn't work. Then I realised it's optional config; maybe the module responsible for processing that config (core views) also needs to be a dependency. It would make sense, so my dependencies became:

dependencies:
  ...
  - drupal:node
  - drupal:views

Still didn't work, same problem - the View simply doesn't exist yet, so it can't be deleted.

So two halves of the same question:

How do I stop this config from ever having been installed in the first place (or installed but initially disabled)?
If that's not possible, what dependencies do I need to provide to ensure that the View in question is installed by the time my own hook_install is executed, so I can remove/disable it myself?

Hmm, have you tried in the .profile file an hook_install_tasks?

Or maybe with the hook_install_tasks_alter.

/**
 * Implements hook_install_tasks_alter().
 */
function MODULE_install_tasks_alter(array &$tasks, array $install_state) {
  $tasks['install_finished']['function'] = 'CALLBACK_post_install';
}

And deactivate the view in the callback.


Removing a row from a view depending on the user currently logged in I have a view which prints out a table of blog posts.  There are 2 columns - title and tags.

If a post has a tag assigned to it called core-team then users with the role non-core shouldn't be able to see the post displayed in the table.

The view which is created displays every blog post so everyone can see them - but I can't figure out how to remove or not show a row from the view if the user logged in is non-core and the post has the tag core-team.

Any ideas?

This isn't a views' problem. I'm assuming that the non-core users should not have access to the content that has the core-team tag anywhere (not just in the specific view). That's because if you use a "hack" to remove the result from the view, someone entering the specific blog post's url directly in his browser would take him to the node.

What you actually need to do is use the Taxonomy Access Control module to restrict access to the "core-team" tag. When you do that, the non-core user will not have permission to view the content tagged as "core-team", so the view will not display these results either (assuming that in the access restrictions of the view you left the default value of: "Permission").


How to replace the Secondary menu title with the current Username? Secondary menu - this is the system secondary menu title.
I need to replace it with current username, the same as the User menu block has it.

I do not want to use the User menu block because of some reasons.
I would like to use the deafault system menu:

<?php if ($secondary_menu): ?>
  <div id="secondary-menu" class="navigation">
    <?php print theme('links__system_secondary_menu', array(
      'links' => $secondary_menu,
      'attributes' => array(
        'id' => 'secondary-menu-links',
        'class' => array('links', 'inline', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Secondary menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#secondary-menu -->
<?php endif; ?>

Should I use token [current-user:name]?
If so, then where (file name) and how?

Note: I can not do it directly at /admin/structure/menu/manage/user-menu/edit because Menu name field is inactive.

I think you can simply do this by making change in page.tpl.php file.

Just replace,

'text' => t('Secondary menu'),

with,

'text' => t($user->name),

save and clear cache.

Image-1: Before changing code (I have deleted line 'class' => array('element-invisible'), so text can be visible)

Image-2: After change,

Final code,

<?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            //'text' => t('Secondary menu'),
            'text' => t($user->name),
            'level' => 'h2',
            //'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
    <?php endif; ?>


How to add expose View filter for a derived field I have a Drupal View looking at User profiles. One of the fields is derived, or calculated, which is done using Views PHP.

I'm trying to add an exposed filter for this View, but the expose option isn't visible.

Is there another module I use to add this?

Sadly I needed to filter the results myself in the Views alter hook.

Results Alter,
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

Query Alter
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7


drupal_goto is not refreshing the webform on submit I have a webform node. I need the users to fill it and on submit, the user will be redirected to some link.

if ($form_id == 'webform_client_form_970') {
    $form['#submit'][] = 'dl_pdf';
}

function dl_pdf(){
        drupal_goto("http://dev.site.com/ar/printpdf/9", $options);
    }

When the form is submitted, drupal_goto works ( it actually just downloads a PDF file automatically ) but the form does not get refreshed.

What i have been doing wrong. Any clue?

Solution:

if ($form_id == 'webform_client_form_970') {
        //$form['#submit'][] = 'dl_pdf';
        drupal_add_js(
            'jQuery(document).ready(function () {
                jQuery(".webform-submit").on("click", function(){
                    var win = window.open("'.dl_pdf().'", "_blank");
                    win.focus();
                });
            });',
        array(
            'type' => 'inline',
            'scope' => 'footer',
            'weight' => 5
            )
        );
    }

function dl_pdf(){
        return "http://dev.site.com/ar/printpdf/9?name=".$userinfo->title."&date=".$course_date."&course_type=off-non-reg&course_name_ar=".$courseinfo->title."";
}

If you redirect to a URL that does not return a page but instead returns some other type of resource (such as a PDF in this case), then the current page will not be refreshed, as you have observed, because the response to the form request is returning the PDF, not HTML.

If you want the page to be refreshed as well then a common technique is to return the HTML for the new page from the form, and then redirect again to return the PDF. Because you need the new page to load fully (so the browser renders it), you'll need to use JavaScript to provide the redirect to the PDF. You can have a link in the page as well, to say something like "If the file does not download automatically, click here".


How can I output a Drush report in table format? I'm getting into my first drush command and coming up with a ton of things I don't understand. Basically, I need to output a list of image files referenced in my content, and the best seemed to be to output it in a table format so that the different bits of information would be easy to see and distinguish from each other.

I started by following the tutorial and did this (in the COMMAND_drush_command $items array):

    'engines' => array(
        'outputformat' => array(
            'default' => 'table',
            'pipe-format' => 'json',
            // Commands that return deep arrays will usually use
            // machine-ids for the column data.  A 'field-labels'
            // item maps from the machine-id to a human-readable label.
            'field-labels' => array(
                'node' => 'Nid',
                'title' => 'Title',
                'filename' => 'Filename',
                'directory' => 'Directory',
            ),
            // In table format, the 'column-widths' item is consulted
            // to determine the default weights for any named column.
            'column-widths' => array(
                'title' => 20,
            ),
            'require-engine-capability' => array('format-table'),
        ),

That worked fine, because I built an array of output line by line and at the end of the command passed it back to drush which duly printed it. The only problem is that there is a LOT of data, so the command gives the appearance of hanging. So I thought I would try to print line by line and did this instead:

            $result[0] = array(
                'node' => $nid,
                'title' => $title,
                'filename' => end($file),
                'directory' => $directory,
            //    'orphan' => '?',
            );
            $output = drush_format_table($result,false,array('node'=>5,'title' => 20,'filename'=>30,'directory'=>25));
            drush_print($output);

The problem is, that the output is all over the shop, rather than being lined up nicely as it should be.

Where am I going wrong?

You are better off sticking with your initial implementation; if you use Drush output formatters, then the end-user will be able to convert your data to csv or yaml or other formats as needed. If it takes a long time to collect your data, then use drush_log or perhaps a progress bar to let the user know something is going on.


Live css module won't save my css I am using the live css module, but when I try to save the css on the fly I get the error message 'The url used contains a sub-filextension which poses a security threat. Saving not allowed.'
Any idea what might be causing this?

The error is generated by the following code in the module

  if (file_munge_filename($sanitized_url, 'css less') != $sanitized_url) {
    echo drupal_json_encode(array(
      'result' => 'failure',
      'filename' => $href,
      'msg' => 'The url used contains a sub-filextension which poses a security threat. Saving not allowed.'
    ));

This checks passes the sanitized url through the file_munge_filename function. The function checks for all the extensions in the file adds an underscore after the extension to make it secure. you can read the link for more information.

So I presume that there is some issue with the css file you are uploading. there might be more than 1 extension in the file name such as style.abc.css.


Custom form with Date textfield with jQuery popup I'm making a custom form and I would like to render a field that is just like the form that gets rendered for a Date with a jQuery Popup when editing a node.

I can't figure out how to build the array so that it will get rendered by drupal properly. I've tried a ton of different attempts, but this is what I've got currently:

$form['birthdate'] = array(
    '#title' => t("Offspring Birth Date"),
    '#id' => 'edit-field-filter-birthdate',
    '#type' => 'date_popup',
    '#default_value' => '2015-01-01 10:30:00',
    '#date_type' => DATE_DATETIME,
    '#date_timezone' => date_default_timezone(),
    '#date_format' => 'm-d-Y H:i',
    '#date_increment' => 1,
    '#date_year_range' => '-3:+3',
);

$html = drupal_render($form);

The README.txt in the date/date_popup module says:

  To include a popup calendar in a form, use the type 'date_popup':

  $form['date'] = array(
      '#type' => 'date_popup':
      '#title => t('My Date'),
      ....   );

  Set the #type to date_popup and fill the element #default_value with a
  date adjusted to the proper local timezone, or leave it blank.

However, all that ever gets rendered is just the '#title'.

What am I doing wrong?

You need to initialize the form with drupal_get_form():

$form = drupal_get_form('MYMODULE_birthdate_form');
$html = drupal_render($form);

function MYMODULE_birthdate_form($form, &$form_state) {
  $form['birthdate'] = array(
    '#type' => 'date_popup',
    // ...
  );
  return $form
}


Convert D6 user timezone offset to D7 timezone string In Drupal 6 user timezones are stored as second offset, such as: -3600. In Drupal 7 it's the timezone string, eg: Europe/Berlin.
I would to migrate users with their timezone setting to D7, but it's not obvious how to convert timezone offsets to strings.

My current solution is to create a full mapping table built from the timezone strings but I'm sure it's not the most elegant:

$d6_offset = -3600; // Input.
$zones = timezone_identifiers_list();
foreach ($zones as $zone) {
  $offset = format_date(time(), 'custom', 'Z', $zone);
  if (!isset($map[$offset])) {
    $map[$offset] = $zone;
  }
}
$d7_timezone = $map[$d6_offset]; // Output.

Do you know a better workflow?

I would use the following code.

$map = array();

foreach (timezone_identifiers_list() as $zone) {
  if ($timezone = timezone_open($zone)) {
    if ($datetime = date_create("now", $timezone)) {
      if (($offset = $timezone->getOffset($datetime)) !== FALSE && !isset($map[$offset])) {
        $map[$offset][] = $zone;
      }
    }
  }
}

Keep in mind that the same offset is used for different timezone identifies. Showing just an identifier for each offset would be less useful for users.

For example, for Europe you would show the following list. (The list is partial.)

Europe/Amsterdam 7200
Europe/Athens 10800
Europe/Dublin 3600

In your list, Europe/Rome, Europe/Madrid, Europe/Malta, and Europe/Kiev would not appear because the offset is already used for the three entries I shown.

A better code would the following one.

function mymodule_get_timezones() {
  $map = &drupal_static(__FUNCTION__);

  if (isset($map)) {
    return $map;
  }

  foreach (timezone_identifiers_list() as $zone) {
    if ($timezone = timezone_open($zone)) {
      if ($datetime = date_create("now", $timezone)) {
        if (($offset = $timezone->getOffset($datetime)) !== FALSE && !isset($map[$offset])) {
          $map[$offset][] = $zone;
        }
      }
    }
  }

  return $map;
}

As side note, I would not use format_date() if you use "custom" as date format, and you are not interesting in translating the returned date. In such case, the following code that is executed from format_date() is extra, and useless, for you.

  // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
  // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
  // input string.
  // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
  // The read-ahead expression ensures that A matches, but not \A.
  $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

  // Call date_format().
  $format = date_format($date_time, $format);

  // Pass the langcode to _format_date_callback().
  _format_date_callback(NULL, $langcode);

  // Translate the marked sequences.
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);

In the case I described, that code can be replaced with the following one.

return date_format($date_time, $format);


Create a responsive email at Drupal for phone does anyone successfully create a responsive email at drupal? I mean, with @media rule, but not just using width percentage(like 100%) to control element width.

We got one request to build two different email styles for pc and phone. We need different font size and different element width for this email. Now the email for pc is done, but I can't figure out an appropriate way to do the email for phone. I tried @media rule in css, but the @media rule will overwrite the regular css rule in pc too.

I sense it might be the reason that I have converted css class to inline css, so media rule is not working. However, inline css in email is recommended to meet most of the email clients out there, and I see the good email, like email from linkedin, uses the inline css too. The email from linkedin displays differently in phone and works perfect as an example of responsive email, having smaller image size, font size, element width and so on.

I tried this email template from this article https://www.emailonacid.com/blog/details/C13/emailology_a_free_responsive_email_template_using_media_queries_-_part_i# It doesn't work for me. The email at phone email client looks the same way as the email showing at pc. Not sure why this email template works for others, but not for me, or not for drupal?

For the record, I'm using mimeemail in Drupal6 and writing the code to send email directly.

Does anyone has idea to solve this issue? Any help will be appreciated, thanks!

Okay, this issue is solved by this module https://www.drupal.org/sandbox/dmitriytrt/1939698.

The issue happens because default "mimemail css compressor" module has excluded @media rules in email, so we need a different way of converting css to inline styles.

Another possible solution is to use emogrifier https://github.com/jjriv/emogrifier. This library's latest version has supported @media rules.


Modify Drupal's search to show custom fields I have some fields (say, pictures or whatever) in my custom content-type and I want them to appear in search results. How do I do that?

I know how to edit template files such as search-result.tpl.php provided by the search module. In this page, there is a single variable called $snippet which contains search result but as a rendered HTML output. How do I modify it/show my custom fields in search results?

I would like to have full control to contents of the files, rather than just rendered HTML for them. My Search display page requires customization a lot, so without getting each field individually, I won't be able to produce desired output.

Try the Display Suite module. There you can change the appereance of a content type in different view modes. One of these view modes is for example the search result.


Can I create an "unlimited" values variable? I'm trying to create an exclude list of sorts that is configurable via the variable admin interface. I have created lots of single value variables, but never a variable as an array where through the interface the user can "Add" another field/value like you can on nodes with "unlimited" field values.

Can this be done with the Variable module?

I'm not sure how well it will scale, but here is an example for a multiple variable in the Variable issue queue https://drupal.org/node/2019629

<?php
/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
    // Use '[custom]' as a placeholder for the variable name.
    // It will set these properties ('type' and 'multiple') automatically.
    $variables['custom_vars_[custom]'] = array(
        'title'        =>    t('Custom multiple variable'),
        'group'        =>    'site_information',
        'repeat'    =>    array('type' => 'string', 'default' => 'some default value'),
    );
    // if you need to expose your custom variable as token
    // you have to set 'token' key as TRUE,
    // and ought to set the properties (name, description and type)
    // Notice that 'first' it is a name of variable defined in custom_variable_options().
    $variables['custom_vars_first'] = array(
                    'token' => TRUE,
                    'title' => 'Custom variable',                        // name
                    'description' => 'My first variable description',    // description
                    'type'    => 'string'                                    // type
                    );
  return $variables;
}
/**
 * Implements hook_variable_type_info().
 * @return
 *  An array of information defining variable types.
 *  The array contains a sub-array for each variable type
 *  with the variable type as the key.
 *  The possible attributes are the same as for hook_variable_info().
 */
function MY_MODULE_variable_type_info() {
    $type['custom'] = array(
        'title' => t('Custom variables'),
        'type'    => 'select',
        'options callback' => 'custom_variable_options',
    );
    return $type;
}
/**
 * Callback for custom options.
 * @return
 *  An array of variables with the variable name as the key.
 */
function custom_variable_options($variable, $options) {
  return array(
    'first'  => t('My first variable', array(), $options),
    'second' => t('My second variable', array(), $options),
    'third'  => t('My third variable', array(), $options),
  );
}

I dont think this is exactly what you want -- but may give you some ideas (it does the multiple value per "variable". I'm not sure offhand how you build a variable_form to edit the values in function custom_variable_options().


"Load a list of entity objects from a VBO View" rules action not working I am trying to use the Rules action called "Load a list of entity objects from a VBO View." I had it working before, but I've since refreshed my DB from prod and I can't remember what my views looked like. I stripped the setup down to its most basic, vanilla configuration and I still can't get it to work.

Here's what I've done:

I created a view of Users. No page; no blocks; just a master display of users with no filter. Two fields: the user's name and the Bulk Operations checkbox (no actions; everything default).

I then created a rule. The event is just "view content" so I can iterate quickly. For the action, I selected "Load a list of entity objects from a VBO View." When I view a node (which triggers the rule), an error message pops up in the log that says, "Unable to get a data value. Error: Invalid data value given. Be sure it matches the required data type and format."

The reason is that the function views_bulk_operations_action_load_list() is trying to make an entity_metadata_wrapper out of FALSE. The exact line is views_bulk_operations.rules.inc:176:

$entities[] = entity_metadata_wrapper($entity_type, $vbo->get_value($result)); // $entity_type == 'user'

$vbo->get_value($result) ends up FALSE because $vbo->entities is NULL. Where are the entities? Did I miss something obvious when I set up my view?

You want to pass the userid as a parameter also, similar to what is shown around 7:30 in the video about Using VBO to load list of objects into Rules. Here is a summary of what is shown in this video:

  You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
  However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
  You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
  The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.


Add custom attribute to an external JS script It's not really clear how to add custom attributes when adding an external JS script to the page.

Currently I have this code:

drupal_add_js('https://code.jquery.com/jquery-3.4.1.js', array('type' => 'external'));

How can I add an integrity attribute to the rendered script tag?

The rendered script should look like this:

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="></script>

I know this post exists, but I'm not able to use that solution since the source is loaded externally and I will not be able to check on the source.

I solved the problem using drupal_add_html like this,

$data = array(
  '#tag' => 'script',
  '#value' => '',
  '#attributes' => array(
    'src' => 'https://code.jquery.com/jquery-3.4.1.js',
    'integrity' => 'sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=',
  ),
);
drupal_add_html_head($data, 'unique_key');


Locking fields on a content type Using Drupal 7:

I have several content types with their own sets of fields, but I also have a set of fields that they must all share in common. That is easy enough through the administrative UI, but I'm writing a module that programmatically will add the fields to all node content types that I specify. Additionally, I do not want the administrator to be able to remove or edit those fields through the administrative UI.

How can I make it so that as an administrator is managing content types that the admin cannot modify or remove these fields that I have specified?

Alternatively, I know that I can create a separate entity and force field existence that way, but then I loose access to a lot of the functionality already built into the node entity, especially the function hook_node_access which is also a requirement for this module.

Anyone have any suggestions or know how to solve this?

Refer to the field api documentation here. You do not have to add permissions to block the delete. All you need to do is add the "locked" attribute to the field definition.

  locked (integer): Whether or not the field is available for editing.
  If TRUE, users can't change field settings or create new instances of
  the field in the UI. Defaults to FALSE.


Translation table: How do I restore a deleted metatag string? At the Translation table module (admin/config/regional/translate/translate), I was translating metatags. By accident I deleted one (metatag:global:og:street-address). I thought I just delete all the useless translations, but then it deleted the whole tag.

Is there a way to restore or (if easier) add it again to the table?

Here are the steps to reproduce:

Enable Metatags, Entity Translation and Inline Entity Forms.
Make a node type translateable (using Entity Translation) and add an entity reference field that uses the inline_entity_form widget (it doesn't matter what it points to).
Create a node of that type, with custom meta tags and add one referenced entity, save it.
Add a translation in another language, translate the meta tags and save the translation (you can also translate the referenced entity, this isn't relevant for this bug though). At this point we have all content as it should be.
Now edit the translation again, leave the meta tags as they are (everything still looks fine) and make a modification to the referenced entity using the inline entity form widget, then save the entire form. The translated meta tags are gone and have been reset to the default values.

The cause of this issue is the following code in metatag_field_attach_form():

<?php
// Entity_Translation will trigger this hook again, skip it.
if (!empty($form_state['entity_translation']['is_translation'])) {
     return;
}
?>

This code works as intended when adding a translation, but not when editing a translation, because in that case $form_state['entity_translation']['is_translation'] is not defined (it gets defined later, only after the code above has already been executed). However, even though the logic is broken, the resulting behavior is correct, because when editing a translation metatag_field_attach_form() doesn't actually get called twice as mentioned in the code comment, so we really don't want to return yet.

The problem arises when using the inline_entity_form widget, which reloads part of the form using Drupal's standard ajax mechanism. This causes the form to be rebuilt, and the code above from metatag_field_attach_form() is run again, but this time after Entity Translation has set $form_state['entity_translation']['is_translation']. The code is now running as intended, but the resulting functionality is broken. Now the function returns prematurely, $form['#metatags'] doesn't get set, metatags' hook_form_alter() gets skipped and the form submit handler doesn't get set in metatag_metatags_form(), so meta tag information gets lost and is replaced with the default value.

The solution is to fix the code above to only return when a new translation is being added, not anytime a translation is edited:

<?php
// Entity_Translation will trigger this hook again when adding a new     translation, skip it.
if (isset($form_state['entity_translation']['is_translation']) &&     !empty($form_state['entity_translation']['is_translation'])) {
  return;
}
?>


How to wrap field out put in custom markup? Situation
I have a custom module that is using hook_field_formatter_info() to add an "fancy" option to the image field in the manage display of a content type. When this option is chosen I want to be able to surround the ENTIRE field in custom divs and markup. I want the solution to be a hook in my custom module and not a template override.

Process
A user wants the display of an image field to be the "fancy" option. They check it in the drop down and click save from the content types Manage Display admin page. Now on that content type node there should be custom markup surrounding the entire field even if there are multiple images, the new markup should surround ALL the images and not each individual image.

hook_field_formatter_view
hook_field_formatter_view seems to demand it's output be an array and I can't seem to be able to wrap the output in a div.

Template overrides
I can't just make a field.tpl.php for the specific field because like I initially mentioned I need to be able to switch themes and the module still work like normal. Unless there is a way to get my module to override any field where said field has hook_field_formatter_info() set specifically.

/**
 * Implements hook_field_formatter_view().
 */
function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  foreach ($items as $delta => $item) {
    if ($index === NULL || $index === $delta) {
      $element[$delta] = array(
        '#theme' => 'bootstrap_modal_image_formatter',
        '#item' => $item,
        '#entity_type' => $entity_type,
        '#entity' => $entity,
        '#node' => $entity, // Left for legacy support.
        '#field' => $field,
        '#display_settings' => $display['settings'],
        '#delta' => $delta,
      );
    }
  }

  // $element = '
' . $element . '
';

  return $element;
}

And here is the #theme function:

function theme_bootstrap_modal_image_formatter($variables) {

  $item = $variables['item'];
  $entity_type = $variables['entity_type'];
  $entity = $variables['entity'];
  $field = $variables['field'];
  $settings = $variables['display_settings'];

  $image = array(
    'path' => $item['uri'],
    'alt' => isset($item['alt']) ? $item['alt'] : '',
    'title' => isset($item['title']) ? $item['title'] : '',
    'style_name' => $settings['bootstrap_modal_node_style'],
  );

  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  // Allow image attributes to be overridden.
  if (isset($variables['item']['override']['attributes'])) {
    foreach (array('width', 'height', 'alt', 'title') as $key) {
      if (isset($variables['item']['override']['attributes'][$key])) {
        $image[$key] = $variables['item']['override']['attributes'][$key];
        unset($variables['item']['override']['attributes'][$key]);
      }
    }
    if (isset($image['attributes'])) {
      $image['attributes'] = $variables['item']['override']['attributes'] + $image['attributes'];
    }
    else {
      $image['attributes'] = $variables['item']['override']['attributes'];
    }
  }

  $entity_title = entity_label($entity_type, $entity);

  if ($style_name = $settings['bootstrap_modal_image_style']) {
    $path = image_style_url($style_name, $image['path']);
  }
  else {
    $path = file_create_url($image['path']);
  }

  $caption = 'some value';
  $gallery_id = 'some value';

  return theme('bootstrap_modal_imagefield', array('image' => $image, 'path' => $path, 'title' => $caption, 'gid' => $gallery_id));
}

Been working on this for days, I'm drowning here.

Might be misunderstanding but it sounds like you just want a #prefix and #suffix on the base render element:

function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  ...


Drupal 7 view to loop through store locations I am needing to setup a view in Drupal 7 that loops through content entries with fields. The content listing page will display teasers of each entry item with only the store name, address, suburb and phone number displayed. When the store name is clicked, I want the resulting page to display all details about the store. Could someone provide me insight on how to get this setup. I have a single content item with multiple field collections that works in a similar way, but it does not provide the click through functionality. It can be viewed here: http://endlessfitness.co.nz/swim-spa-retailers.

For the view format instead of using teaser you can select fields. And then add those fields which you want to show. To make the titles clickable, when you will add the title field it will give an option to link it to the content.
Here is the fields format option.

And here is the field which you will need to add. The screenshot will have different fields than yours because I don't know what fields are there in your content type.

And here is the option to link title. So when you will add title field you will get this popup


Adding workflow to custom content types I am trying to assign a workflow to my custom content type, but i can't find the option to get this working. Is it a bug or maybe just not part of the workflow module?

I would probably suggest to use Workbench Moderation instead of using the Workflow module. I don't know your exact use case, but I've had a lot of luck with the Workbench suite.


drupal 7 wildcard and parameter replacement? How can i use _load() function in drupal 7 ? Please look at this one.

function sample_menu() {
  $items['node/%hotel_node/images'] = array(
    'title' => 'Images',
    'weight' => -10,
    'page callback' => 'show_tab_page',
    'page arguments' => array(1, 'images'),
    'access callback' => TRUE,
    'access arguments' => array(1),
  );
  return $items;
}

function hotel_node_load($nid)  {
  //$node = node_load($nid);
  $node = node_load(array('nid' => $nid));
  return $node;
}

function show_tab_page($s1='',$s2='') {
  return('s1 is @s1 with $s1 @s2 with $s2',array('@s1' => $s1,'@s2' => $s2));
}

while trying in the url : http://localhost/drupal/user/2337/images

Am getting Page not found
The requested page "/drupal/node/232/images" could not be found.

Please help me out. thanks

There seems to be some disparity in your naming conventions here. Your functions should be named with MODULENAME_ as a prefix, including all hooks that you implement.

For example, if your module is called 'sample' then as well as the folder the module files are in being called 'sample', your files will need to be named similarly (sample.info, sample.module, etc.). If you don't follow this convention your hooks won't be called; and it's just good practice to prefix your module's functions with the module name.

The other thing here is that you don't actually need to use your own router load function...the node module has already done it for you (with the node_load() function). You can simply re-use that:

function sample_menu() {
  $items['node/%node/images'] = array(
    'title' => 'Images',
    'weight' => -10,
    'page callback' => 'sample_show_tab_page',
    'page arguments' => array(1, 'images'),
    'access callback' => TRUE
  );
  return $items;
}

You should be aware that node_load() returns a node object, so the first parameter to your page callback function will be that object. The second will be the string 'images', as per the arguments you've provided in page arguments.

Your page callback (which I've renamed :P) would then look more like this:

function sample_show_tab_page($node, $arg1) {
  // Use whatever you need from the node object
  $nid = $node->nid;
  $title = $node->title;
  // etc...
}

Finally, and perhaps most importantly to commit to memory, make sure you clear Drupal's caches once you've added/edited any hook. Such implementations are cached, and the system won't pick up these changes until you tell it to.


Editing user submission of user registration form with hook_user_insert() and $edit I recognize there is a similar question here:

drupal.stackexchange.com/questions/38124/hook-user-insert-get-form-values

but I've got Eclipse and XDebugger setup so I can see the variables and I am still stuck.

I provide the variables below, please note field_foo is a field the system has taken care of properly without my interfering, after the user submits it, field_bar is a field I want to change the submitted value of, it has the value 303031 when the system handles it from form submission, where the variables show "value 300501 " is my attempt to edit that value - clearly I'm editing something wrong)

$edit   Array [37]
[0...30]
    uid 63
    field_foo   Array [1]
        und Array [1]
            0   Array [1]
                value   asdasd
                    length  6
                    0   61
                    1   73
                    2   64
                    3   61
                    4   73
                    5   64
    field_bar   Array [2]
        und Array [1]
            0   Array [1]
                value   303031
        value   300501

Here is my code to try and set it...

function MY_MODULE_user_insert(&$edit, $account, $category) {

    $newBarValue = 300501;
    $edit[field_bar][value] = $newBarValue;

}

PLEASE NOTE:

I don't know if this is the case for all field_data_field Core fields but I had to use the following to get it to work:

$edit[field_bar][und][0][value] = $newBarValue;

This might be unique as I am working on someone else's work atm.

hook_user_insert() is invoked after the user object and all it's fields have already been committed to the database; that's why your code isn't taking effect at the moment.

There are a couple of ways you could go:

Use exactly the same logic in hook_user_presave(), which gets called before the data is committed to the database.
Implement hook_form_alter() for the registration form, add a custom validation function, and manipulate the field values in there.


How to add Shipping method for commerce flat rate module? i am working on drupal commerce's "shipping" part, i want to create two methods for shipping as
1.Free Shipping
2.Express 2-day Shipping
for USA .

For "free shipping" condition is if order total is greater than $100 then we can use "free shipping" else it should apply rate $4.

for "Express 2-day Shipping" condition is if order total is less than $140 then we  can cost $12 else it is free.

The Rules module integrates with Drupal Commerce in order to handle this type of requirement. There are many video tutorials available that explain how to setup various shipping rules.

There is also a module called Conditional Rules that may be useful if you need to have branching logic in your rules.

In this case I think you would only need two rules:

Conditions: type of shipping == "Free shipping" AND order total > $100 Actions: shipping cost = $0
Conditions: type of shipping == "Express" AND order total > $140 Actions: shipping cost = $0

You would set the default pricing for the "Free shipping" to $4 and the for the "express" to $12. The default prices would be overridden by the Rules in those two cases.


How to delete 'blocked' users in bulk? There are a spammer(s) out there constantly creating accounts on my site. The accounts are 'blocked' by default so they do not pose a problem, nor does the spammer gain anything from them.

Still, I would like to delete them all but without having to click on the /admin/people page 150 times: canceling accounts 50 at a time.

Is there a way to cancel all 'blocked' accounts in one step?

Drush only appears to let me cancel one at a time...

On the People page (admin/people), first select the blocked users and then from the update options select Cancel the selected user accounts. (Drupal 7)

Another way is using the Views Bulk Operations module.


How to add custom fields to menu items I've been looking at using menu attributes module for Drupal 7 to add an extra field to the menu navigation system. However this adds a new attribute to the attribute array and thus prints it out in the anchor link.

e.g.

  function themename_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below'])
  {
    $sub_menu = drupal_render($element['#below']);
  }

  $element['#localized_options']['html'] = TRUE;

  $subtitle = $element['#localized_options']['attributes']['subtitle']; //get sub text

  $linktext = $element['#title']. ''. $subtitle .'';
  $output = l($linktext, $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

But it comes out like this

About ussubtitleexampletext

is there anyway to hide the attribute in the link and just spit it out where ever I want it in the html? Or is there a better way of doing this? I've looked at power menu module as well, but thats not quite what I'm after either.

TIA

You can use hook_form_alter to alter the menu link edit form.
This way you can add a extra field to the form, in your case:

$form['subtitle'] = array(
 '#type'=>'textfield',
 '#title'=> t('Subtitle'),
);

Then add an extra submit hanlder to the form:

$form['#submit'][] = '_my_submit_handler';

In your submit handler you can access your custom value by using $form_state['values']['subtitle'].

You will have to store this value in an extra sql table or a variable_set,together with the menu-item ID.

Once you have done that, in your theme function you can access your subtitle by menu id.
Or you can use  MYTHEME_preprocess_menu_link to add extra info to $variables, which you then can access in your theme function.

Hopes this helpes you out.


What is the difference between the Workbench and Workflow modules? I use the Revisioning module to manage revisions of nodes on my Drupal 7 site.  I had been updating the site by myself, so Revisioning was sufficient; now, however, I will be adding some content editors to the project so I need to set up a more complex workflow.

I used to use the Workflow module on Drupal 6 and the Drupal 7 version has integration with Revisioning.  However, Workbench has been getting a lot of good press recently.

What are the significant differences between these two modules, Workbench and Workflow?

Workbench gives you an intuitive and friendly user interface to control content (nodes)transitions on a previously defined states on a role based access control means that every transition to the node from a state to a state for the role authorized to perform that transition, with the ability to create new transitions and states.

You won't get that feature unless you enabled the workbench moderation module.

Workbench access module allows you set sections, editors, roles (defined using a menu items or taxonomy terms) to work on the description above based upon the permission given for the role to work on workbench functionality which gives you a generic out of the box role based access control to previously define workflow to manage content publishing process.

Workbench media provides integration between media and the Workbench suite. It simplifies the pages content administrators need to visit in order to add media which makes workbench files
module useless and becomes depricated.

Workflow seems to be more powerful and provides you with one form to create and define workflows and manage states, transitions, assign roles, set labels for transitions and how states will be listed and logged read that awesome article

Besides have integration with many helpful modules may be used in your project in the future like og, rules, views and search_api due to the dependency on drupal entity system allows to set workflows defined to other entity types not limited to nodes.

Actions on each transition could be tied and notification created for users in concern like group members and admins or high level managers.

At the end each of the two modules have very good functionality that deserves showing respect to maintainers, Workbench focus on content closely to E-magazines and online news portals or forums, Workflow pay attention on the process thinking of workflows as business rules required and may be helpful in ERP, CRM and E-commerce like systems some how.

Finally close to scope of that question I found a very simple module provides ability to add custom publishing states with integration to rules and views, specify defined roles to transition nodes between states.

I hope that review helps you determine what is the best module for your project.


Content added in article tags, doubling content, even without article content I am displaying a content type through a view, using a contextual filter to limit results to one per page (nid). I believe this is a simple/standard way of displaying content, but being new to drupal I could be wrong.

My problem is that the content is duplicated. First within an 'article' tag, and then where I'd expect it to show up (inside the view tags).
I find it completely baffling because I don't even use the article content type. It's a problem I've had from the start, but I took the easy way out and simply hid the article content with display:none.
But now, for some equally baffling reason, drupal has placed a new view I created inside the article tags - which of course means it doesn't show either. :-(

Why would drupal decide to send along my content inside the article tags?

I'm not sure if this is enough to go on, but I would be more than happy to provide more information.

Thanks for your time,
Tobias

As per comments, I found my error:
I was talking about HTML tags. Sorry for not being precise there. I found my error though, which was incredibly stupid. I had given the content an url alias so as to function as a page, which would of course send along the content. I had then added a view as described above, adding the content once again. Silly me. Sorry for the inconvenience.


Hook to run afer config import I need to run some code after the config for my module is imported(it will create/update a css file that depends on configuration). So what is the correct hook to use? The module install will run only on first time when the module is instaled.

The config system has switched already to events and the documentation for events describes in "My First Drupal 8 Event Subscriber" how to subscribe to a config event:

https://www.drupal.org/docs/8/creating-custom-modules/subscribe-to-and-dispatch-events

See also this example from the Color module:

/core/modules/color/src/EventSubscriber/ColorConfigCacheInvalidator.php

<?php

namespace Drupal\color\EventSubscriber;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * A subscriber invalidating cache tags when color config objects are saved.
 */
class ColorConfigCacheInvalidator implements EventSubscriberInterface {

  /**
   * The cache tags invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
   */
  protected $cacheTagsInvalidator;

  /**
   * Constructs a ColorConfigCacheInvalidator object.
   *
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
   *   The cache tags invalidator.
   */
  public function __construct(CacheTagsInvalidatorInterface $cache_tags_invalidator) {
    $this->cacheTagsInvalidator = $cache_tags_invalidator;
  }

  /**
   * Invalidate cache tags when a color theme config object changes.
   *
   * @param \Drupal\Core\Config\ConfigCrudEvent $event
   *   The Event to process.
   */
  public function onChange(ConfigCrudEvent $event) {
    // Changing a theme's color settings causes the theme's asset library
    // containing the color CSS file to be altered to use a different file.
    if (strpos($event->getConfig()->getName(), 'color.theme.') === 0) {
      $this->cacheTagsInvalidator->invalidateTags(['library_info']);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[ConfigEvents::SAVE][] = ['onChange'];
    $events[ConfigEvents::DELETE][] = ['onChange'];

    return $events;
  }

}


How to override title for exposed filter views under cache? I want to override the title for Exposed Filter views.

I tried to use hook_views_pre_view hook_views_pre_render and hook_views_post_render and more. This doesn't help me because my views is under cache(if I clear cache then it works, but I have to do each and every time).

Is there any option to set title for cached views? I want searched field as page title.

Is there any option to set title for cached views. I want searched field as page title.

Yes, you could use jQuery to grab the search field text and then change the title on page load. Probably, you will need to use cookies.


Drupal 7 set default value from database in hook_form I have implemented a hook menu:

$menu['question-view'] = array(
  'title' => 'Question View',
  'page callback' => 'item_view',
  'access arguments' => array('access question view'),
);

item_view callback is generated using table theme:

$output = theme('table', array(
  'header' => $header,
  'rows' => $rows,
));

$output .= theme('pager');
return $output;

which displays a table like this:

Question            Edit
Question1     Click here to edit
Question2     Click here to edit
Question3     Click here to edit

where "Question1", "Question2", and "Question3" are just questions like "What is your name?", which were all obtained from questions table in database.

When I click "Click here to edit", it should go to a form containing that question. For example, when I click edit beside Question2, the form should display Question2 as default value in the $form['question'] field.

I want to do something like:

$form['question'] = array(
  '#title' => t('Question'),
  '#type' => 'textfield',
  '#default_value' => ... // This should come from the question where I clicked.
);

Question:
How should I set the default value of $form['question']?

Basically, you have to add an indicator with edit question link i.e query string to load the selected question from database and pass the default value to the form.

  A query string is the part of a uniform resource locator (URL) that contains data to be passed to web applications.

"Click here to edit" link may look like (clean URL enabled):

http://www.your-domain.com/item_view/question/44

or

http://www.your-domain.com/question/44/edit

44 in both cases represent question id.

Then, take question id from the url and pass it to a mysql query to retrieve question title and assign it to #default_value

Example as follow:

function question_form() {

  $question_id = 0;

  // assuming url: www.your-domain.com/item_view/question/44
  if (arg(1) == 'question') {
    $question_id = arg(2);
  }

  // retrieve question title by question id
  $query = db_select('questions', 'q')
    ->fields('q', array('question_title'))
    ->condition('q.question_id', $question_id);
  $result = $query->execute()->fetchAssoc();

  $form['question'] = array(
    '#title' => t('Question'),
    '#type' => 'textfield',
    '#default_value' => ($result && isset($result['question_title']))? $result['question_title'] : '';
  );
}


Error: Class 'DOMDocument' not found in Drupal\Component\Utility\Html::load() (line 286 of core/lib/Drupal/Component/Utility/Html.php) After a Debian update my Drupal 8 installation can not show single nodes and spits the following error.

  Error: Class 'DOMDocument' not found in Drupal\Component\Utility\Html::load() (line 286 of core/lib/Drupal/Component/Utility/Html.php).

I have no clue what to do and have installed all required php extensions, following some other issues with the same error.

I already removed all suspicious contrib modules and I am lost now with a broken project.

Any suggestions would be very helpful.
ENV: Drupal 8.5 | PHP 7.2.9

That sound like it can't find php Dom extension, to get that try sudo apt-get install php-xml, it should solve your problem


How to get jquery working on Drupal 7 - for Newbies I have been reading many tutorials online on how to get jquery working on drupal 7.
Although there are many lines of code and examples, what i cannot find is what piece of code to put where (maybe it is obvious for most of the developers)

So, what I do is

1)I create a new custom block

2)Over there from drupal UI, I write my code

(function ($) {

  $(document).ready(function(){

    // jquery here

  });
})(jQuery);

3)I display the block, but the jquery is not loaded.

I am reading that I should be putting this code in template files , theme files, css files, info files and I do not know whatelse!

It is not clear to me in which file exactly and in which path I have to put the above code to work properly ?

Any advice?

Many thanks!

A couple of things here:

If you can avoid entering javascript and PHP into the site via the UI it will possibly save you troubles down the line. If you have no alternatives it is ok but here are some reasons why it is not a great idea: https://drupal.stackexchange.com/a/2512/10729 (note that that is aimed at PHP, not js but most of the points still stand for js). The examples module has an example of creating custom blocks.
For attaching js, if you want it on all pages you can add it to your theme's info file. If you only want it in some places though, best to use drupal_add_js() so it is only on pages it needs to be. For attaching js behaviour to forms you can also use #attached attribute on your form items.
If you use $(document).ready(), it will fire your javascript when the page loads, however if the page is updated via ajax then your javascript will not fire again, so new markup won't be affected by whatever your javascript is. To handle these cases you should use drupal behaviors instead of document ready.

For example:

(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
      // Do your thing here.
    }
  };
})(jQuery);

I recommend reading these pages:
Managing JavaScript in Drupal 7
Working with JavaScript and jQuery


Same CSS file generates under different folder when I flush A question from a newbie:

I am using a theme in my site and I made some changes in the CSS file.
The CSS file I am modifyiing is Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css

and it is in the folder: /sites/default/files/less/1TKupTVXZyLFbxdskTDq5OyCMsRMsIZmPQc_nx40j0Y/sites/all/themes/XXXXXX/less

So when I flush the caches, a new folder named randomly like above appears in

/sites/default/files/less/

with the unmodified version of my CSS file Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css in it.

Where is the source of this Style.XcVzbo5GbrB4v7QVES377fts6uudS0o0YbaMpBamvPg1.css so I can modify it for ever?

It's in a theme, module, library, Drupal's misc folder, or basically anywhere that the web server can read; that's as much as can really be said without more info.

To get that info, turn off css aggregation in Configuration -> Development -> Performance, then try inspecting the page again. Now you should see the original, unaggregated source file of the rule.

Bear in mind that if you're compiling Sass/Less to CSS, the file you find might not necessarily be the last place you need to look - it depends how the compilation actually happens in your application. But it gives you a good starting point at least.

Also bear in mind the nature of Cascading Style Sheets - if you introduce an identical rule with new styles after the original, it will take precedence. So as an alternative to tracking down the original, you could just add a new css file to your theme and give it an appropriate weight so it loads last and your styles "win".

Don't forget to switch aggregation on again afterwards if you need it.


Filling form with user entered values after submit How do I fill a custom form with the values entered from the users before the form was submitted? I have saved the $form_state values, but when I put them back into $form_state on loading, the form fields aren't filled.

Drupal 7

If you are not redirecting and want to preserve the values in the Form API fields add $form_state['rebuild'] = TRUE; on the submit handler.

/**
 * FORM submit handler.
 */
function FORM_form_submit($node, &$form_state) {
  // Rebuild the form and keep the filter values.
  $form_state['rebuild'] = TRUE;
}

Drupal 8

In Drupal 8 you would use $form_state-> setRebuild();

See public function FormState::setRebuild for more detail.

Custom submit handlers in Drupal 8 are dealt with differently — here is some useful discussion on Drupal 8 submit handlers.


How to load node with AJAX on a Calendar click? I want functionality like this: when user clicks a node link in a calendar view, the details of the node should be loaded tu another region with AJAX. How to achieve this?

You can take help of Drupal hook_menu with Json object output and a Drupal JS beahvior to handle click event.

Idea : In the click event call an ajax function to your menu callback that gets you a JSON object of required content. Load the content in your desired DOM element.

code for hook_menu; considering your module name 'mymodule'

function mymodule_menu() {
  $items['mymodule/%node/load-content'] = array(
      'page callback' => 'mymodule_ajax_node_load_content',
      'page arguments' => array(1),
      'access arguments' => array('access content'),
  );
  return $items;
}

code for Page callback :

function mymodule_ajax_node_load_content($node) {
  // The variable holds complete node object for you.

  $data = array();

  $data['body'] = $node->body['0']['value'];
  // Consider providing any other node details if required.

  $output = array('status' => 'ok', 'data' => $data);

  return drupal_json_output($output);
}

JS code for attaching a behavior to Drupal,

Drupal.behaviors.nodeLinkClick = {
  attach: function(context, settings) {
    // sort by click.
    $("a.node-link").click(function(e){
      e.preventDefault();
      $.ajax({
        url: Drupal.settings.basePath + 'mymodule/' + nid + '/load-content',
        type: 'GET',
        data: data,
        dataType: 'json',
        success: function(response) {
          $(".dom_to_load_content").html(response.data.body);
        },
        error: function() {
          // show error in any DOM.
        },
      });
    });
  }
}

NOTE : The above code not tested; a small snippet cut-out from my project.
Hope this helps you. Let me know if you still facing any problem.


hook_node_insert() doesn't work hook_node_insert() doesn't work after node insertion in Drupal 8. When I'm trying to get the node details in that hook, it's not working.

My code is the following one.

use Drupal\Core\Entity\EntityInterface;

function test_node_insert(EntityInterface $node) {
    dpm($node);
}

How about hook_entity_insert

function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity){
  // do something
}

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_insert/8


How to define Views filters and relationships for custom Civicrm contact fields that are indexed via Search API? I followed the steps on skvare to index CiviCRM contacts via Search API, then to have Views list the contacts with the search box as an exposed filter.

I need to expose a filter that filters results based on what membership type the contact has. That might require a relationship, which is currently not an option in Views for me, so I might have to write a custom relationship handler as well as the custom filter handler. I have been trying to find the code to read to use as a guide but I have been unable to figure out whether these handlers are being defined in CiviCRM, Views, Search API, or the Civicrm Entity module which I'm also using.

How do you define a custom relationship and filter handlers for custom fields on CiviCRM contacts being displayed via Search API, CiviCRM Entity, and Views?

If this is about getting Membership fields showing in the ADD RELATED FIELDS selector at the bottom of admin/config/search/search_api/index//fields then I expect this is a civicrm entity issue in which case you could check at this chat channel

Otherwise you may be looking for sites/all/modules/civicrm/drupal/modules/views


How can I set a message on the page I am `drupal-goto`ing towards? I have a page which makes certain verifications and needs to redirect the user in certain cases. In those cases, I want the destination page to show a message, but I can't get it to work. Here is my code:

if ($userNeedsToBeRedirected) {
  drupal_set_message(null, "You've been redirected because ...");
  drupal_goto('destination');
}

The redirection works, but the message doesn't appear. What can I do?

Note: I also tried the following:

if ($userNeedsToBeRedirected) {
  drupal_goto('destination', array(
    'query' => array(
      'message' => "You've been redirected because ..."
    )
  ));
}

and in the destination page:

if (isset($_GET['message'])) {
  drupal_set_message(null, $_GET['message']);
}

but is doesn't work either because (I believe) drupal_set_message is being called too late the the page creation process.

You are setting a NULL message in drupal_set_message, the correct syntax would be:

if ($userNeedsToBeRedirected) {
  drupal_set_message("You've been redirected because ...");
  drupal_goto('destination');
}

The second drupal_set_message $type parameter is for the message type:

'status'
'warning'
'error'


Allowing users to 'follow' taxonomy terms. Then creating a view which displays a list of nodes which are assigned the 'followed terms' I'm looking for the recipe which emulates a feature from the popular tech blog: Mashable.com

Here's what I'm looking for:

Nodes are assigned taxonomy terms.
Users may view a node, and see the taxonomy terms which are assigned to this node.
Users may 'follow/subscribe' to each taxonomy term assigned to this node.
A custom view (called "My Custom Stories") will be configured, for each user, which displays a list of nodes which are relevant to the taxonomy terms to which he subscribed.

For example:

A node X is created which is assigned the terms 'Politics', 'Apple', and 'China'.
User A follows/subscribes to 'Politics', while User B follows 'Apple'.
User A's 'My Custom Stories' view will only contain a list of nodes which are assigned the 'Politics' taxonomy term, while User B will see a list of 'Apple' nodes.

I'm particularly interested in the 'taxonomy term follow' modules required for this recipe, as well as how the 'Custom Stories' view will be configured.

I'd appreciate any tips. Thank you!

My idea:

You could create a new content type Taxonomy Subscriptions, using taxonomy and user reference (you will need References module).

Then with Rules module you could manage (create) the subscriptions for terms and then you view will be joined with the created content type.


How to join values of multiple geofields in a view? I have a content type in which the site of organizations are displayed in a leaflet map with the help of an addressfield. (And all organizations are displayed in a joint map.) But certain organizations don't have convertible postal address, therefore geocoding from addressfield doesn't work. For these organizations I created a second geofiled in which I add latitude/longitude values manually.

The problem is that the display of leaflet map in Views can handle only one field as the source of geodata. Is it possible to combine these two geofields into one?

Have you tried conditional views?
You could have 2 fields, using the first by default, and the second instead if the value of the first is empty.
This module has helped me a few times. Just add the module, in your view add a field type "Views conditional", exclude from display your fields and use replacement patterns in your conditional field in one case or the other, depending on the condition (let's say address field is empty, then use latitude/longitude).

EDIT:
What about 3 fields in your content type:

Address field [field_address]
Lat/long [field_lat_long]
Composed field (type text) with token value [field_address][field_lat_long] using field token value or field tokens
In this way the composed field will always have a value from one or another field, and then you can use this field as data source.
Then you may need to manage field dependencies to avoid that both fields are used.


Bootstrap theme overrides "theme_list_item" function and removes div's "item-list" class How can I stop Bootstrap theme from overriding the them_item_list and replacing the div's class from item-list to panel-body?

I have the following form and it does not render the items

$stages = array(
1 => array('data' => '1. Step 1'),
2 => array('data' => '2. Step 2'),
3 => array('data' => '3. Step 3'),
);

$stages[$current_step]['class'] = array('active');

$stages_list = theme('item_list', array('items' => $stages));

$form['header'] = array(
    '#type' => 'fieldset',
    '#title' => '',
    '#value' => $stages_list,
);

the Above renders a navigation steps menu just fine with Bartik and other themes however, when it comes to Bootstrap it  is empty rather having list of items.

I did some googling and found out this issue that might be somewhat relevant but, the solution does not seem to work for me. I tried to override the mytheme_item_list($variables) in template.php with following but, still no sign of the naviagtion.

function bootstrap_subtheme_item_list($variables) {
   $items = $variables['items'];
   $title = $variables['title'];
   $type = $variables['type'];
   $attributes = $variables['attributes'];

   $output = '
';
   $output .= "<$type" . drupal_attributes($attributes) . '>';

   $count = 1;
   $num_items = count($items);

   foreach ($items as $item) {
      $attributes = array();
      $children = array();
      $data = '';
      $count++;

      if (is_array($item)) {
        foreach ($item as $key => $value) {
          if ($key == 'data') {
            $data = $value;
          }
          elseif ($key == 'children') {
            $children = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $data = $item;
      }

      if (count($children) > 0) {
        // Render nested list.
        $data .= theme_item_list(array('items' => $children, 'title' => NULL, 'type' => $type, 'attributes' => $attributes));
      }

      if ($count == 1) {
        $attributes['class'][] = 'first';
      }
      if ($count == $num_items) {
        $attributes['class'][] = 'last';
      }
      $output .= '
' . $data . "
\n";
   }
   $output .= "</$type>
";

   dpm($output);

   return $output;
 }

The dpm above prints the exact thing piece of html that I want, the following but, the same is not rendered in the page.

1. Step 1

2. Step 2

3. Step 3

Not sure what I am doing wrong. Any solution that do not break other theme's would be very much appreciated.

1) Default markup. To return default item list markup just do this:

function bootstrap_subtheme_item_list($variables) {
  return theme_item_list($variables);
}

2) But. Your issue is not caused by Bootstrap markup. Try this:

$form['header'] = array(
  '#markup' => $stages_list,
);

You are using fieldset incorrectly, learn Form API Reference.


Slight design problem with Roles, Rules and Profile2 on my site I'm a little stuck with the registration flow on my site. What I have is a multi-user environment, where each user can, but does not have to, create a secondary/Profile2 "shop" profile.

Now I don't want to just expose the Profile2 shop type to everyone. So I've set up a shopkeeper role, and would like to somehow allow users to request or opt into the role.
This isn't for security or anything. It just doesn't look professional having the menu link available to users who don't want or need the profile. Also, some newbie is bound to get curious and enter random crap, which will later mess with the display of their content.

My solution was to use a flag on the user page, which triggers a rule to promote the user, but the problem is; there's no Flag option to prevent users from being able to flag other user's accounts. Unless I use a page template to hide the flag link, but that's a perhaps a little too hacky, and as far as I understand, doesn't actually disable the link.

All I really want is some sort of link or checkbox somewhere(preferably on the user-page) saying, "I have a shop, lemme create a profile". So if anyone has a suggestion for my issue, it would be greatly appreciated!

Cheers,

Matt

Here's a fairly straightforward way to do it.

Create a field (boolean) on the user account manage fields page.  Assign it useful label such as "I want to run a store" etc.
Create a rule to add the role as follows:

Event After saving user account AND After updating an existing user account

Conditions Data comparison (user account field value) == yes AND User has role (store) NOT

Actions
Add user role (store)

And create another rule to remove the role:

Event After updating an existing user account

Conditions Data comparison (user account field value) account-unchanged == yes AND data comparison (user account field value) account == yes

Actions Remove user role (store)

This should let the users check the box and then the role will automatically be toggled on or off.


Date field exposed filter - select year Back in Drupal 7 I've created exposed filter with Year from date field. (Selet list).

View all
2017
2016
2015
etc...

And when creating such filter we had options like on this picture:

BUT, now in Drupal 8 I cannot see that is supported.

I've installed Better Exposed filters but only thing is that I can select datepicker instead of plain text field for this filter, but I need select list and only years.

If it's not possible yet, where I can find examples of creating custom exposed filters or something like that?

Luckily just a day before your question this tutorial for year select filter was posted on Drupal planet:

https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8


Migrating into custom node type with multi value field I'm doing a migration into D8, and I'm migrating into a custom video player field with multiple values. Here's the schema for the field as defined in its plugin:

  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return array(
      'columns' => array(
        'vid' => array(
          'type' => 'int',
          'size' => 'normal',
          'not null' => TRUE,
          'default' => 0,
        ),
        'video' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'video_hd' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'video_sm' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'thumbnail' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'poster' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'show_ads' => array(
          'type' => 'int',
          'size' => 'tiny',
          'not null' => TRUE,
          'default' => '1',
        ),
        'raw_file' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
      ),
    );
  }

I have a custom source plugin that gathers all of the information needed for these columns into appropriately named items. My question is, how do I get those pieces of data into the destination field. Can I do it in the .yml file configuration, as can be done with the body field?

  'body/format':
    plugin: migration
    migration: d6_filter_format
    source: format
  'body/value': node_body
  'body/summary': teaser

Or do I need to have a custom destination plugin that takes these pieces of data and puts them into the correct places in the node? I'm seeing a lot of blogs and documentation on source and process plugins, but not much on destination plugins, so I'm not sure.

Thanks.

Nothing to do with destination plugins, what you need to do would be in the process pipeline. You could write a custom process plugin like, say, d6_cck_link. Or, you can use the iterator process plugin - see, for example, how d6_upload.yml in core populates the target_id/display/description columns of the 'upload' field.


How to get the current field value in Ajax callback? I 've a problem with Drupal 8 ajax callbacking. I created a multivalue field for country - region listing as new field type using a custom module. In first selectlist I loaded all country codes and I set this field as multivalued.

I wrote the below code in FieldWidgetType Class.

     public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element['value'] =  array(
      '#type' => 'select',
      '#title' => 'Select Country',
      '#name' => 'value',
      '#options' => array(
        0 => t('- Select Country -')) + $termNameArr,
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#ajax' => [
              'callback' => array($this, '_regions_ajax_callback'),
              'event' => 'change',
              'progress' => array(
                 'type' => 'throbber',
                 'message' => t('Please wait.Fetching data...'),
                ),
             ],
      '#suffix' => ''
    );
    return $element;
    }

I have to load regions of the selected country in an another select box using ajax. The selectbox should populate with the regions of selected country in change event of country select box item (here I'm calling ajax). Or else, can ajax simply return the selected country value to append in span (.email-valid-message) specified in #suffix.

My current callback to return at least the selected country name is:

    public function _regions_ajax_callback(&$form, &$form_state) {
      $response = new AjaxResponse();
      $element = $form['value'];
      $default_value = isset($element['#default_value']) ? element['#default_value'] : NULL;
      $value = $form_state->getValue($element['#name']);
      $changed = $default_value == $value;
        if ($changed) {
       $response->addCommand(new HtmlCommand('.email-valid-message', $value));
       }
    return $response;
    }

I used namespaces

    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\HtmlCommand;

What am I doing wrong? How can I change my callback function to get current field value? Did I miss to add any namespace?

in your _regions_ajax_callback()

$element = $form_state->getTriggeringElement();
element['#value'] <-- value is in here


Is it possible to get the last number of a views pager to display after and before the elipses? I'm trying to create a custom pager similar to the Amazon pager:

  < 1 2 3 4 ... 82 >

and after a certain point:

  < 1 ... 7 8 9 10 ... 82 >

But, I cant figure out how to display the last pager number after the elipse. Is this possible? What would be the best way to go about this?

I'm not sure if this is the best approach, but it's been working for me.

First I set the pager items to display as inline-block. Then I styled the .prev/.next items to float left/right respectively so they're on the outside.

I used hook_preprocess_pager and $pager_total to set the last pager number $variables['tags'][4].

function hook_preprocess_pager(&$variables, $hook) {
  global $pager_total;
  $variables['tags'][4] = $pager_total[0];
}

I added a conditional so the last pager item wouldn't appear twice on the last couple pages:

function hook_preprocess_pager(&$variables, $hook) {
  global $pager_total;
  $variables['tags'][4] = $pager_total[0];
  if( is_numeric( $_GET['page'] ) &&  $pager_total[0] - 6 < $_GET['page'] ) $variables['tags'][4] = '';
}

I set the first page to "1" in the view settings, then use a similar conditional so it doesn't appear twice on the first couple pages.

function hook_preprocess_pager(&$variables, $hook) {
  global $pager_total;
  $variables['tags'][4] = $pager_total[0];
  if( is_numeric( $_GET['page'] ) &&  $pager_total[0] - 6 < $_GET['page'] ) $variables['tags'][4] = '';
  if( is_numeric( $_GET['page'] ) && $_GET['page'] < 5 ) $variables['tags'][0] = '';
}

This seems to work pretty well.


how to set the source connection in drupal d2d migrate I am migrating my taxonomy and users from d6 site to d7 site. How can I set the legacy connection of source db of d6 site.

The user is root and password id empty with source database name as d6 for the Drupal 6 site.

  hook_flush_caches().

 $common_arguments = array(
        'source_connection' => 'd6_migration',
        'source_version' => 6,
      );

will it migrate data from d6 to d7 when I install the custom migrate_d6 module in Drupal 7 site?

My Settings file of Destination project is

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'd6_migration' =>
  array (
    'default' =>
    array (
      'database' => 'd6',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

The migrate module provides basic migrate functionality while the migrate_d2d module extends on that functionality providing interfaces for reading and importing into Drupal 5, 6 and 7. Migrate comes with Drush integration and supports rolling back migrations which is very handy during development.

Add the following code into your settings.php file or you can specify database connection details within your migration scripts:

<?php
// Our Drupal 7 database configuration.
$databases = array (
'default' =>
  array (
    'default' =>
    array (
      'database' => 'db_drupal7',
      'username' => 'drupal7_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  // Here we add in the connection to our Drupal 6 database.
  'legacy' =>;
  array (
    'default' =>;
    array (
      'database' => 'db_drupal6',
      'username' => 'drupal6_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

If you want to create the script for migrating the content than please have look at this useful tutorials:

http://devblog.com.au/migrating-drupal-6-to-drupal-7-with-the-migration-framework
https://drupal.org/node/1813498

Personal suggestion:
Now the migrate_d2d module is providing a stable UI for migration the contents and that is very easy to do as well, have a look at it documentation here: https://drupal.org/node/1813498

Also if you have a larger database than you can use the drush commands to migrate the contents after setting up the database connections, the list of drush commands for migrating the content: https://drupal.org/node/1561820