How do I add the page number to the page title on drupal default paginated pages? It has been recommended by an SEO consultant that for paginated pages the page number is included in the page title to avoid duplicated content. How do I achieve this?

I did this:

    function hook_pager_link($variables){
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574

  //put the pagination page number into the title tag
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  //add page
  $page = t('page');
  $pattern = '/' . $page . ' \d/';
  $title = drupal_get_title();
  preg_match($pattern, $title, $matches);
  if(!$matches){
    $new_title = $title . ' - ' .  t('page') . ' ' . ($page + 1);
    drupal_set_title($new_title);
    }
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

Have you investigated the Page Title module? It, among other things, features

  Pagination Suffix: One of the things you may noticed about Drupal in terms of SEO is that whenever you go through a paged list of content, the page title never changes. Google Webmaster Tools will flag this up as a problem as you essentially have several different pages all being identified with the same page title. A new feature, introduced in Page Title 2.1, is the ability to append the page number as a suffix pattern. This means any URL which contains something like page=2 in the query string will also have an optional token pattern suffixed onto the end of it. Important: for this feature to work properly, you need to be running Token 1.12 or later.


how to get password as submitted by the user in hook_user_insert? I have extended the core using hook_user_insert. but when i print the $edit argument inside the function i get password fields as encrypted.

Is there any way i can get the non-encrypted value of password as submitted by the user.

I am using drupal 7

Following is the $edit array

Array
(
    [uid] => 28
    [hostname] => 127.0.0.1
    [roles] => Array
        (
            [2] => authenticated user
        )

    [cache] => 0
    [administer_users] =>
    [name] => raul1
    [mail] => raul1@tst.com
    [pass] => $S$DskyNMYOrdQoEdErlYPN701I1jSBBrzetjSjb2XPzlooVcfcp8Rp
    [status] =>
    [notify] => 0
    [timezone] => Asia/Kolkata
    [signature] =>
    [picture] =>
    [picture_delete] => 0
    [picture_upload] =>
    [signature_format] => filtered_html
    [init] => raul1@tst.com
    [field_first_name] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Raul
                        )

                )

        )

    [field_last_name] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Garcia
                        )

                )

        )

    [is_new] => 1
    [created] => 1356067366
    [theme] =>
    [access] => 0
    [login] => 0
    [language] =>
)

is there any tweaking to get the user submitted password from D7 registration form?

I know its impossible to get back the hashed value. or how to find out the salt associated with each hashed password

Any hook that is invoked from user_save() is too late to get the password as entered from the user. In fact, the first lines executed from user_save() are the following ones.

if (!empty($edit['pass'])) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}

What you can do is adding a form submission handler to the form used to create new user accounts. That submission handler can access the password as entered from the user in $form_state['values']['pass']. I would rather add a form submission handler that is executed right after user_register_submit(), as that submission handler contains the following code.

  if (!variable_get('user_email_verification', TRUE) || $admin) {
    $pass = $form_state['values']['pass'];
  }
  else {
    $pass = user_password();
  }
  $notify = !empty($form_state['values']['notify']);

  // Remove unneeded values.
  form_state_values_clean($form_state);

  $form_state['values']['pass'] = $pass;

I would use the following code.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  // Add your submission handler.
  $form['#submit'][] = 'mymodule_user_register_submit';
}

function mymodule_user_register_submit(&$form, &$form_state) {
  // The password is in $form_state['values']['pass'].
}


Filtering exposed filters with views_get_view_result() function I have built a module so that I can display PDFs with phpwkhtmltopdf. I am currently calling my view data using:

$view = views_get_view_result('course_catalog');

My question is, is there a way to have filter my exposed filters with this function? If not, what is the best way to go about this? --I suppose I could manually filter through the results with PHP, but that hardly seems efficient.

It seems views_get_view_result does not allow setting filters: https://www.drupal.org/node/1428696

Instead of using views_get_view_result, you might try with other functions of the Views API:

$view = views_get_view('course_catalog');
$view->set_exposed_input($my_exposed_input);
$view->init_display();
$view->pre_execute();
$view->execute();
$result = $view->result;

You can check the documentation for the set_exposed_input method, and also this related Drupal Answers question, for alternatives: How to change programmatically exposed filters in views


How to check if a referenced entity is being used in other places? I have a paragraph component that has a single field (reference) that calls on other paragraph components. I'd like to remove one of the paragraph reference field options so that users do not accidentally select it, however, when I do this I start receiving errors across my multisite environment that a reference no longer exists. Is there a quick way to check if a paragraph (or any entity) is being used and in which places (preferably one that shows paths) so that I can remove the reference before deleting this paragraph reference option from my paragraph component?

Any and all assistance would be greatly appreciated, thanks!

Is there a quick way to check if a paragraph (or any entity) is being
  used and in which places (preferably one that shows paths) so that I
  can remove the reference before deleting this paragraph reference
  option from my paragraph component?

A paragraph can only be used in one place. So I'm first answering the part "or any entity", which also reflects the question title, and address the paragraphs specifics later.

I would do this in two steps. First find all entity reference fields which are configured to target this entity type, then run an entity query for each field.

As example how to find all entities where term #1 is used:

use Drupal\field\Entity\FieldStorageConfig;

$target_id = '1';
$target_type = 'taxonomy_term';

$map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('entity_reference');
$results = [];
foreach ($map as $entity_type => $fields) {
  foreach ($fields as $field_name => $field) {
    // we are only interested in configured fields, not base fields
    $config = FieldStorageConfig::loadByName($entity_type, $field_name);
    if ($config && $config->getSetting('target_type') == $target_type) {
      $ids = \Drupal::entityQuery($entity_type)
        ->condition($field_name, $target_id)
        ->execute();
      $results[$entity_type][$field_name] = $ids;
    }
  }
}

If the field is configured in a paragraph type, the IDs you find are of paragraph entities. Load the paragraph and get the parent entity with $paragraph->getParentEntity(). For nested paragraphs do this multiple times, until you find a non paragraph entity, for example a node.


Extend an existing Views filter (NumericFilter) throws exception I am trying to do something that should be easy in Views but I can't seem to be able to make it work.

I need to create a filter on top of the existing NumericFilter (Drupal\views\Plugin\views\filter\NumericFilter), but with a minimalistic approach like the following it is simply not working.

<?php
// @file src/Plugin/views/filter/FoobarProjectSizeRangeSelectionFilter.php

namespace Drupal\foobar_extra\Plugin\views\filter;
use Drupal\views\Plugin\views\filter\NumericFilter;
/**
 * Class DateYearFilter
 * @ingroup views_filter_handlers
 * @ViewsFilter("project_size_range_select")
 */
class FoobarProjectSizeRangeSelectionFilter extends NumericFilter {
}

The way I use is is pretty straight forward:

<?php
// @file foobar.views.php
/**
 * Implements hook_views_data_alter().
 */
function foobar_views_data_alter(array &$data) {
  // clone an existing field
  $data['node__field_a']['field_a_value_range'] = $data['node__field_a']['field_a_value'];
  // change name and filter ID
  $data['node__field_a']['field_a_value_range']['title'] = t("Foobar");
  $data['node__field_a']['field_a_value_range']['filter']['id'] = 'project_size_range_select';

  return $data;
}

Whenever I try to save a view using this filter plugin i get the following error:

InvalidArgumentException:
 The configuration property display.default.display_options.filters.field_a_value_range.value.min doesn't exist.
 in Drupal\Core\Config\Schema\ArrayElement->get()
 (line 74 of ROOT/web/core/lib/Drupal/Core/Config/Schema/ArrayElement.php).

Right now I have "worked around it" implementing some custom and terrible hacks, but i'm pretty sure this is so simple that it should just work.

So, yeah I ended up investigating more and more and I needed to specify a config schema definition as it follows.

# @file config/schema/foobar.views.schema.yml
#
# Schema for the views plugins.

views.filter.project_size_range_select:
  type: views_filter
  label: 'Foobar numeric'

views.filter_value.project_size_range_select:
  type: views.filter_value.numeric
  label: 'Foobar Numeric'

The full gist is available here if anyone is interested.


Configuring Drupal with a dynamic IP address I have now a problem with the multisite configuration of Drupal 7 installed on my linux machine.
I want this site to be accessible from outsite from my local machine. For this I have a domain name from no-ip, that redirects the requests to my machine, and a multisite Drupal 7 configuration.
When I check the configuration, I am facing the result below:

I can access the non-drupal sites with no problem from the linux
machine using the mydomain.no-ip.org address.
I can access the drupal sites with no problem from the linux machine using the local network address (192.168.1....).
I CAN'T correctly access the drupal sites (drupalsite1, drupalsite2) from the linux machine using the local network address. This is the problem: I am redirected to the main drupal site, although I request the drupalsite1.

And, for information, I can't access the linux machine from my W7 other machine using the mydomain.no-ip.org address (I have the STB interface). All is right with local addresses.

It seems that Drupal doesn't recognize the specified drupal site I want to get, and then redirects me to the default main drupal site.
Has somebody any idea?
May I get any example of Drupal configuration working with a dynip or no-ip service?

I am quite newbie in D7.

Thanks in advance.

There's no need to use external DNS when working locally on a development box.

You can add the required mapping to your /etc/hosts file

e.g:

127.0.0.1 drupalsite1 drupalsite2 drupalsite3

Then you can access the site by visting, e.g http://drupalsite1 in your browser

You could even use something like

127.0.0.1 drupalsite1.no-ip.org drupalsite2.no-ip.org

If you'd prefer.

The /etc/hosts file is checked prior to external DNS lookup and will override / take precedence over the latter. There's a similar file in Windows as well.

More info: http://en.wikipedia.org/wiki/Hosts_(file)


SEO friendly URL for drupal commerce products I am using Commerce Product Url module for generating unique url for commerce products like follows,

For each product it provides id parameter,

mycommercesite.com/node/1?id=1
mycommercesite.com/node/1?id=2

as well as sku parameter,

mycommercesite.com/node/1?sku=pr1
mycommercesite.com/node/1?sku=pr2

But I need SEO friendly URL for each product

for example,

mycommercesite.com/node/1/product1
mycommercesite.com/node/1/product2

Is there any way to do this?

Thanks.

the module Commerce product Url is for make unic urls based on product variations, it means when you have one product display showing different product variations.

Check this issue where they explain a little bit better what Im telling you

But there is a non-drupal solution to convert dinamic urls into SEO-friendly urls, that is using mod_rewrite:

EXAMPLE

Sad Original URL = site.com/node/1?id=54

Happy URL :) =  site.com/node/1/rueben-sandwich/

Use mod_rewrite in your .htaccess file to parse out the elements of the URL. Like this:

RewriteEngine On //check that in drupal's .htaccess the rewrite engine is on by default

RewriteRule /(.*)/$ node/.*$?id=$1

the (.*) pulls the element out and puts it in variable $1. and the .*$ is just a wildcard that accepts everything after node/

Try it and tell us if it worked because I have not tried it with Drupal websites.

by the way, try to use sku, or some other argument in the url through the module configs, so your url would look better because using "id" the final result of the above code would be /node/1/54


Add attribute to content title I'd like to add a custom attribute into the title element whenever a particular content type is displayed, whether as an individual node or through a view (specifically when displaying 'full content').  How do I do this?

I'm using Drupal 7.

You could modify the field.tpl like monymirza suggested. But you may want to use hook_preprocess_field(&$vars) and target the title element within the $vars array.

Use that function in your theme and you may view the content/structure of the $vars array with dsm($vars) from the devel module.


Why is data-quickedit-entity being printed in plain text when I'm signed in? I have a template for theming paragraph sections that, for some reason, prints out data-quickedit-entity-id="paragraph/2" in plaintext above any of my paragraphs that contain images.

{% set bgcolor = content.field_background_colour[0]["#markup"] ?: color_class %}
{% set bundle = paragraph.bundle ?: base_class %}
{% set image = content.field_section_image|without("label") %}
{%
  set classes = [
    "paragraph"|clean_class,
    "paragraph--" ~ bundle|clean_class,
    "paragraph--" ~ bundle|clean_class ~ "--" ~ bgcolor|clean_class,
  ]
%}
{{kint(attributes)}}
{% if attributes %}

{% else %}

{% endif %}

{% if content %}
  {{ content.field_main_heading }}
    {% if content.field_sub_heading %}
      {{ content.field_sub_heading }}
    {% endif %}
    {% if content.field_section_image["#title"] %}
    {{ attributes.removeClass(classes) }}
      {% include "@base/layouts/grid/00-grid.twig" with {
        items: [image, content.field_body_text],
        grid_base_class: "grid",
        grid_modifiers: ["columns-2"]
        } %}
    {% else %}
      {{ content.field_body_text }}
    {% endif %}
{% else %}
  {{ dummy_content|raw }}
{% endif %}

This happens right above the image, inside the  on line 18. Screenshot below:

It only gets output when logged in as it's obviously something to do with the quickedit system.

Has anyone seen this or can advise on how to prevent it?

This line prints the attributes in plain text:

{{ attributes.removeClass(classes) }}

If you want to remove classes without printing then use set:

{% set attributes = attributes.removeClass(classes) %}


how do I build a dynamic URL in views? I am using drupal 7, have a content type and two taxonomy categories, size and shape.

Im trying to build a dynamic url such as mysite.com/node/nid/tid/tid, which would get rewrote as e.g mysite.com/page-1/large/square.

I want the content of the url to just show the node, so in this case node/1. But I am also going to make 2 blocks one for category size and another block for category shape which will get the relevant IDs from the url and show the relevant content, in this case block 1 will show large and block 2 will show square.

I thought I could generate the page in views by setting the URL to node/%/%/% or node/%//
and setting arg 1 to nid, but this comes back as page not found.

So I am wondering is this possible in views if not how can I create a url such
/arg1/arg2/arg3 which represents /a nid/a category 1 tid/a category 2 tid, and then populate the page dynamically?

Thanks for any help

edit/

So I have got the arguments working. mysite.com/%/%/% by setting the last argument as the target page rather than the first argument. But how can I rewrite the url. So arg1 becomes node title, arg2 becomes term id 1 and arg3 becomes term id 2 title?

You'll need to set your pathauto pattern settings to rewrite your URL. Goto Configurations > Search and metadata > URL aliases > Patterns. Set the pattern for your content type to:

[node:title]/[node:field_...]/[node:field_...]

Where the "node:field_..." is replaced with the respective tokens for your taxonomy fields.


Is it possible to use image styles in Views field rewriting? I would like to add "no results" behavior to an image field displayed in Views, such that the image from an alternate field is displayed. Ie., if Image1 is empty, display Image2.

Is it possible to use an image style in the rewrite code? I'm sure I can display the second image, using something like <img src="[field_Image2]">, but how can I specify that the image be displayed using the max_height_125 image style?

I figured it out! What you have to do is include a copy of the second field, set to "Exclude from display" in the options, and arrange the fields such that Image2 comes before Image1 in the list. You can set the image style in the options for Image2, and that information will get carried over when Image1 is empty and gets rewritten using the behavior specified in the "No results" option. Also, you don't have to write <img src="[field_Image2]"> in the rewrite area.  All you need is the token for the other field, like [field_Image2].


Panels modules got rid of all my pages I recently installed a theme that called for Panels Everywhere, Mini Panels, and Page Manager modules to be installed.  The theme looks great but I don't understand where all my custom pages went?

I had created a bunch of pages in my custom module using hook_menu().  Now my site is completely driven by Panels and Page Manager.  I assume all my MENU_NORMAL_ITEMS were being stored in a block that is now being suppressed by panels everywhere.

How do I get all my old menu items to work with my new theme?  How do I link up the elements of my theme with my existing pages?

Panels everywhere is like it says, a way to use Panels all over your site. This means that whats normally outputted by page.tpl.php will now be run through a Panel.

Enable the site template (if not already done) here: /admin/structure/pages
Edit the site template and add the page elements as you want your site to be built. Eg. add the site header, then the page title, page content etc.

There is also a setting to create a sample site template variant for you here /admin/structure/panels/settings/everywhere.


Failed opening install.inc' when upgrading Drupal 7.x core with Drush 7.x I have Drush 7.x installed and when I run 'drush up', on a Drupal 7.x codebase, I get the following error:

Drush command terminated abnormally due to an unrecoverable error.
[error]Error: require_once(): Failed opening required '/home/user/public_html/core/includes/install.inc'

It seems like Drush 7.x may be looking for Drupal 8.x file structure. How should I be running this command?

I managed to get it fixed after tracking the issue in drush 7, this is caused as you said by trying to load install.inc as Drupal 8 folder structure while you have Drupla 7 structure

I simply modified DRUSH_ROOT/commands/core/core.drush.inc line 1120

require_once DRUPAL_ROOT . '/core/includes/install.inc';

to be like

require_once DRUPAL_ROOT . '/includes/install.inc';

I hope this help you.


Programmatically a create content form I want to implement the create content form programmatically. In hook_menu() I have the following code.

$items['create/content/video'] = array(
  'title' => 'Create Video',
  'page callback' => 'create_content_video',
  'access arguments' => array('create video'),
  'type' => MENU_LOCAL_TASK,
  'weight' => 1
);

In hook_init(), I have the following code.

if (arg(0)=='node' && arg(1)=='add') {
  drupal_goto('create/content/'.arg(2));
}

In hook_theme(), I have the following code.

'video_node_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'my_theme_video_form',
  'render element' => 'form',
),

In the page callback, I have the following code.

function create_content_video() {
  module_load_include('inc', 'node', 'node.pages');
  return node_add('video');
}

In the template file, I render form element correctly.
My problem is with the the AJAX uploader in the form. Without, I use the upload button to upload the file, and the node is correctly saved; when I use the AJAX uploader, it returns an error.

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of /var/www/mysite/includes/form.inc).
  Notice: Undefined index: #node in comment_form_node_form_alter() (line 1193 of /var/www/mysite/modules/comment/comment.module).
  Notice: Trying to get property of non-object in comment_form_node_form_alter() (line 1210 of /var/www/mysite/modules/comment/comment.module).
  Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /var/www/mysite/modules/menu/menu.module).
  Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /var/www/mysite/modules/menu/menu.module).
  Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /var/www/mysite/modules/menu/menu.module).
  Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /var/www/mysite/modules/menu/menu.module).
  Notice: Undefined index: #node in translation_form_node_form_alter() (line 135 of /var/www/mysite/modules/translation/translation.module).
  Notice: Trying to get property of non-object in translation_form_node_form_alter() (line 135 of /var/www/mysite/modules/translation/translation.module).
  Notice: Undefined index: type in xmlsitemap_node_form_node_form_alter() (line 136 of /var/www/mysite/sites/all/modules/xmlsitemap/xmlsitemap_node/xmlsitemap_node.module).
  Notice: Undefined index: nid in xmlsitemap_node_form_node_form_alter() (line 136 of /var/www/mysite/sites/all/modules/xmlsitemap/xmlsitemap_node/xmlsitemap_node.module).
  Notice: Undefined index: field_news_attachment in file_ajax_upload() (line 276 of /var/www/mysite/modules/file/file.module).
  Notice: Undefined index: #suffix in file_ajax_upload() (line 285 of /var/www/mysite/modules/file/file.module).

When I create content without this method, it works fine.
I am using Drupal 7.14.

I agree with Clive, that this seems like a great deal of trouble, but what you should be doing generally, is calling field_attach_form(), and more specifically for nodes, node_form(), which calls the former. The arguments it expects are

You can see an example on the first here: Is displaying a working Field Widget Form on its own possible?


How to show album title for 'album with no photos' in view I am using node gallery module to create albums and upload photos. I have created a view to create albums and upload photos.It is working fine.But when i create album with no photos, album title is not getting displayed.I want to show 'default image and title of the album' for 'albums with no photos'.I have specified 'title and default image' in 'content:photo' no result behaviour in my view and Only the node author can see this but other users are not able to view this album. How to do this?

One of two ways:

1) Create a Header. Under Header (middle of page) create a Global Text. This will create a title for the View regardless of it's contents

2) Under Advanced, create a NO RESULTS BEHAVIOUR. This functions on the view as a whole, so that if there is not content to display at all, this will be displayed


template.php breadcrumb function I'm trying to change the breadcrumb in Drupal to display in Danish through the template.php in my theme, but I cannot change it. I've flushed the cache.

This is what I've put in the template.php.

  function modeindeks_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];

    if (!empty($breadcrumb)) {
      // Provide a navigational heading to give context for breadcrumb links to
      // screen-reader users. Make the heading invisible with .element-invisible.
      $output = '
' . t('Du er her') . '
';

      $output .= '
' . implode(' › ', $breadcrumb) . '
';
      return $output;
     }
    }

Breadcrumb is made up of an array. So to add any element in the breadcrumb you have to give the offset.

So if you want to set t('Du er her') in place of the front page link then you should try this:

$breadcrumb[0] = l(t('Du er her'), 'front');

To know the exact position of element which do you want to add, you can use var_dump($breadcrumb).

I would rewrite the code as follows.

function modeindeks_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    // Instead of front, you can use the URL of your site's front page.
    $breadcrumb[0] = l(t('Du er her'), 'front');

    $output .= '
' . implode(' › ', $breadcrumb) . '
';

    return $output;
  }
}

If you want to add only You are here link then use the below code.

function modeindeks_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '
You are here: ' . implode(' › ', $breadcrumb) . '
';
  }
}


How to make user picture editable without opening edit profile page? I wanted to allow users to edit profile without going to edit profile page. I found few useful modules like Editable field and Editable fields as link. These modules provide field formatter which make the field editable without leaving the page except the user picture. I am not able to use this technique with user pictures because It is not a normal field as other fields.

How can I make user picture an editable field without going to edit profile page?

Note: I have created a custom profile page using panels. There is a module Picture Changer which allows users to change picture in a modal, but it does not work with panels.

You would have to write your own form where a user can upload the picture and save it as profile picture.


How can I set product price per taxonomy term on Ubercart? I need price per taxonomy terms for products. Here is what I need precisely. So when I add products 'X', 'Y', 'Z' to Ubercart I sets them taxonomy term 'Offer' which has price 10$. These products then have same prices. So when customer add any of these products from this term to cart it will get same price for every product.

Thanks for help M.

If you want to automate this, use Rules module. another option is ubercart core options.


entityQuery to get Nodes referenced by other nodes like an SQL JOIN I have an entity query to get content of type article that has a field that matches a given value, which works as expected.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'article');
$query->condition('field_some_field', 'some value');

Now I have a second content type detail_page that has an entity reference to a node of type article. I would like to get content of type article, same as before, but only those that have been referenced in the field_detail_page_article_ref field of a detail_page content type.

Is that possible with Entity Queries? Playing around with the raw SQL, what I basically need to do is an INNER JOIN or LEFT JOIN with the field field_detail_page_article_ref to see if the nid exists. But it doesn't seem like there is any sort of join() function available for entity queries.

You can use 'entity' field query

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'article');
$query->condition('field_some_field.entity:node.title', 'Referenced node title');


How to send mails to users with bulk operations in drupal7 I want to select some users from a view with the field VBO , and to send to this users an email which cotaining a subject and a body. How can I proceed?

Thanks for the response.
I'm a new user of drupal and my authenticated user have to send a mail for selected user with VBO, and have to enter the contents of mail. (subject + body). After confirmation the system send to selected users the mail.

You can use Rules module with VBO to extend the operations of VBO. In Rules module, you can select the action to send mails to users with whatever text you want.


Query for child nodes On any node in Drupal 7, I want to show a list of its child nodes.  How do I do this?  I basically want to create my own navigation system.

I'm still unfamiliar with the terms in drupal 7. I establish the hierarchy of nodes via the following steps:

go to admin dashboard menu and click on "Add content"
select the "Page" content type
fill out the fields
under "Menu settings," I select "Provide menu link"
I choose the parent node under the "Parent item' drop-down menu
save and publish

Out of the box, there is no concept of sub pages or child nodes in Drupal. What you refer to is the menu structure used for navigation. A node can have a menu items linking to it and menu items can be organized hierarchically. The system was not designed to create and define relation between nodes, but only for navigation. If you look at the API, there is no simple way to retrieve the children of a menu item.

The book module included in Drupal core can be used to create a hierarchical structure for nodes. There are other options such as the relation, references and node hierarchy modules.


Is it possible to have term permission vocabulary id's match taxonomy vocabulary id's when creating a feature I am attempting to create a feature to be used in an install profile that exports a vocabulary and the permissions that are associated with the vocabulary. The problem that I am running into is that the vocabulary vid's on my development site do not match the vid's when running an install profile. Features exports the vocabulary and when imported the next available index in the table is used to create the new vocabulary being imported by the feature. Term permissions use the vid, so when you export the permissions with a feature they look something like:

// Exported permission: edit terms in 4.
  $permissions['edit terms in 4'] = array(
    'name' => 'edit terms in 4',
    'roles' => array(),
    'module' => 'taxonomy',
  );

When I run my install profile the vocabulary I exported is imported with vid 1. So when it attempts to add the permissions for vid 4 it throw an integrity constraint error. I could change the features permissions code to align the id's but this does not bode well when I need to release a new feature that uses vocabularies and their permissions on top of an existing site that already has some vocabularies associated with it. I wanted to check here first before submitting an issue with features. Does anyone know a trick on how to get vocabularies and their permissions exported properly with features?

I was originally using features 7.x-1.0-rc2 then attempted to rectify the issue with 7.x-1.0-rc3 as there are a number of threads with similar issues but not quite the same issue as I am having.

That's not possible in Drupal 7 (and earlier) — permissions are hardcoded to use vocabulary autoincrement IDs, and there's no hook to override them.

This issue proposes switching to using the vocabulary's machine name for permissions in Drupal 8 — please consider reviewing the latest patch on that issue and providing feedback.


THEME.libraries.yml having no effect My THEME.info.yml file reads:

name: 'name'
type: theme
description: 'description'
core: 8.x
base theme: stark
screenshot: images/image.png
libraries:
  - THEME/navbar

and my THEME.libraries.yml reads:

navbar:
  css:
    theme:
      css/navbar.css: {}
  js:
    js/scrolling.js: {}
  dependencies:
    - core/jquery

From all the guides I've found online, this should mean that navbar.css and scrolling.js get included on all pages that use the theme. But that isn't happening. What have I done wrong here, or what steps do I need to take to figure out why it isn't working?

In case it's relevant, the file structure is:

drupal_root
    themes
        custom
            THEME
                css
                    navbar.css
                js
                    scrolling.js
                images
                    image.png
                THEME.info.yml
                THEME.libraries.yml
                THEME.theme

The jQuery code in scrolling.js is just:

$(window).on("scroll", function() {
  if ($(this).scrollTop() > 50) {
    document.getElementById("logo").style.width = '150px';
    document.getElementById("logo").style.marginTop = '0px';
  } else {
    document.getElementById("logo").style.width = '300px';
    document.getElementById("logo").style.marginTop = '20px';
  }
});

When I manually add

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="{{ theme_path }}/js/scrolling.js"></script>
<link rel="stylesheet" href="{{ theme_path }}/css/navbar.css">

to the top of html.html.twig everything works fine. But as I understand it, this is not considered the proper way of going about things, so if possible I'd prefer to do it using libraries.

The extremely helpful comment added by (I think) Ivan Jaros which was unfortunately and rather rudely removed helped me to find that I needed to add <head-placeholder token="{{ placeholder_token|raw }}">, <css-placeholder token="{{ placeholder_token|raw }}"> and <js-placeholder token="{{ placeholder_token|raw }}"> to my html.html.twig file. This helped somewhat: it's now including the CSS file. However:

It didn't manage to include the js file, for whatever reason.
The head-placeholder token is mostly useful, but seems to be overriding the favicon that I had already specified. Is there a way to keep the other stuff it gives without the link rel="shortcut icon" that it's including from core?

In D8 believe you need to wrap your code around this tags in order for Drupal to recognize it.

(function ($, Drupal, window) {

 // code goes here

})(jQuery, Drupal, window);

So try

(function ($, Drupal, window) {
   $(window).on("scroll", function() {
     if ($(this).scrollTop() > 50) {
       document.getElementById("logo").style.width = '150px';
       document.getElementById("logo").style.marginTop = '0px';
     } else {
       document.getElementById("logo").style.width = '300px';
       document.getElementById("logo").style.marginTop = '20px';
     }
   });
})(jQuery, Drupal, window);


How to redirect to external URL upon form submission I've extended a FormBase and I've defined the submitForm method. In this method I want to redirect to an external URL (https://example.com/my/path?amount=33&gift=0&product_id=1)

$myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
$redirect = Url::fromUri($myurl);
$form_state->setRedirectUrl($redirect);

And I get the error:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

Ok, no problem, let's create one:

$myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
$redirect = new TrustedRedirectResponse($myurl);
$form_state->setRedirectUrl($redirect);

Here's the error:

Argument 1 passed to Drupal\Core\Form\FormState::setRedirectUrl() must be an instance of Drupal\Core\Url

So it appears we've gone full circle. Is there a way that maybe I can convert the TrustedRedirectResponse to a Url object?

You'll want to use $form_state->setResponse() instead to utilize the TrustedRedirectResponse you're creating.

Something like this should work:

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)->toString());
  $form_state->setResponse($response);
}

This response may be cached depending on your page cache settings. If you need to change this behavior, you can modify the caching metadata. This should disable this type of caching completely for the response (not tested):

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)->toString());

  $metadata = $response->getCacheableMetadata();
  $metadata->setCacheMaxAge(0);

  $form_state->setResponse($response);
}


Link to nodes in WYSIWYG Editor and Domain Access I  have a Drupal installation using Domain Access.
Is there a solution for inserting links on nodes using WYSIWYG-Editor considering if the node is published to the particular domain.
For Example:

Node A, published to domain Y and Z, has a link to node B, published only to domain Z.
Viewing node A on domain Z the link is rendered as a link. Viewing node A on domain Y the link is rendered as plain text (without

Thanks in advance

See the LinkIt project.

Its flexible API should let you hook into the node listing logic it uses to inject SQL to group node listing by Domain. You should be able to make a plugin with it ... I see no existing solution off-hand (I've used LinkIt and DomainAccess, but not had users linking around sub-domains from the WYSIWYG. My domains were very separate from one another).


Adding AJAX to existing node form Creation of new content type by D7 core is intuitive, fast and nice looking. We don't have to worry about db tables and simple validation. We have widgets, displays, etc. And actually we are building a form (company_node_form).

Example:

Custom content type: Company

Field group: Company address (vertical tab)

Field (simple text): Street
Field (simple text): No.
Field (simple text): Zip code
Field (simple text): Country

Field group: Company contact (vertical tab)

Field (check box): Has phone
Field (simple text): Phone
Field (check box): Has fax
Field (simple text): Fax

Field group: Privacy (vertical tab)

Field (check box): Show address
Field (check box): Show phone

Question

How to add alternation using custom module "my_module" to provide AJAX behavior while adding or editing content type, i.e. to show "Phone" field only if "Has phone" is checked or show text "Sorry, we don't have authority to add companies from selected country." when UK goes to "Coutry" field?

Exclamation

I know that the above form is very simple to code inside my_module, but I wish to use core node constructor to build that form instead of coding.

Your module needs to implement hook_form_alter() to add '#ajax' arrays to the elements that trigger a change in the form. The #ajax elements will include 'wrapper' and 'callback' elements that specify the html ID of the part of the form to replace and a function in your module that returns the part of the form that is being replaced.

For example, if the element 'my-element' should be replaced, add

'#prefix' => '
',
'#suffix' => '
'

to the form array with key 'my-element'. The element that triggers the replacement will get

'#ajax' => array(
   'wrapper' => 'my-element-id',
   'callback' => 'my_callback',
   'method' => 'replace',
),

Here is the callback function:

function my_callback($form, &$form_state) {
    return $form['my-element'];
}

Your hook_form_alter() will hide/show elements and generate your custom messaging depending on $form_state (which it will read when the ajax callback happens).


Right way to add a field to be used as a filter in Views with ranges? I need to add a field to a content type which is going to used as a exposed filter in Views.In this filter the visitor will see ranges. I've done this in the past and ended creating 2 fields to set both limits of a range. I need to remake this and I think this can be done in a smarter way.

What I need is:

1) create the content type: flat

2) add the field price to the content type flat

3) create a view Flats

4) create a exposed filter to filter by the field price but using ranges, e.g: "From 100 000 to 200 000", "From 200 001 to 300 000" and so on. I need these options to be a Select dropdown list.

Then my questions are:

about point 2): I would create a integer type field for this, is this right and enough?
about point 4): How do I do to create the ranges that I need? Maybe a module for this?

This module might help: Views Contextual Range Filter

Module Page Description:

  Views Contextual Range Filter is a simple plugin for Views that adds
  the option to contextually filter not just by a single value, but also
  by range. Numeric, alphabetical (string) and list ranges are all
  supported. Node ids, user ids and even taxonomy term ids are all
  special cases of numbers so will work also. Range-filtering on the
  "created" (posted) and "updated" (last modified) node properties is
  also supported, provided you use the correct format as dictated by
  Views. So, YYYYMMDD for full dates or one of the shorter formats, i.e.
  year+month, year-only, month-only, week-only or day-only. You may use
  the OR operator (i.e. +) and the negate operator. You negate by
  ticking the "Exclude" box on the Views Contextual filter configuration
  panel, in the "More" section.


How to assign a section to a specific node with Workbench? I'm creating nodes using a custom modules

$node = new stdClass();
$node->type = $link['content_type'];

node_object_prepare($node);

$node->uid = $user->uid;
$node->name = $user->name;

$node->title = $html['title'];
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = $html['html'];
$node->body[$node->language][0]['summary'] = $html['summary'];
$node->body[$node->language][0]['format'] = 'filtered_html';

$node->menu['enabled'] = 0; // 1 to enable providing a link in main menu
$node->menu['link_title'] = urlencode($html['title']);
$node->menu['description'] = urlencode($html['summary']);
$node->menu['parent'] = 'main-menu:0';

$node->menu['weight'] = 5;
$node->path['alias'] = urlencode($html['title']) . time();
$node->comment = 1;

$node->status = 1;        // 1 means published
$node->promote = 0;
$node->revision = 0;

$node->changed = $_SERVER['REQUEST_TIME'];
$node->created = $_SERVER['REQUEST_TIME'];

node_submit($node);
@node_save($node);

$node->path['alias'] .= '+' . $node->nid;

node_submit($node);
@node_save($node);

db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('vid', $node->vid)
    ->execute();

But now I need to assign each node a I create a workbench section, so I tried doing this:

$node->workbench_access = array('66');

node_submit($node);
@node_save($node);

$node->path['alias'] .= '+' . $node->nid;

node_submit($node);
@node_save($node);

db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('vid', $node->vid)
    ->execute();

This add the workbench access id temporarily, but when the page is refreshed it doesn't apply it. Is there a way to assign a node to a workbench section using php?

You could try an insert query to inject the access ID, node ID and access scheme into the workbench_access_node table.


What is causing the "username_link not found" error in the LDAP integration module? After integration and configuration of the LDAP integration module, my site is unable to access the LDAP Server. During testing it throws below error:

  Notice: Undefined variable: username_link in theme_ldap_authorization_test_results() (line 91 of /var/www/drupal/sites/all/modules/ldap/ldap_authorization/ldap_authorization.theme.inc).

I am using Drupal - v7.44, and LDAP v 7.x-2.0-beta8 and the same LDAP server is working on other sites.

Is this a configuration issue or a bug?

According to comment nr 2 in issue nr 2751219 this is not a bug, but it's just a configuration issue. Here is a quote from it:

  Incorrect admin password for LDAP server.

So double check the password is correct, and try again ...


Uncaught TypeErrors have me baffled This is my first Drupal 8 site but I have been building Drupal sites since Drupal 6. I am getting lots of Uncaught TypeErrors in the JavaScript console that I can't figure out. I have spend hours searching and have not found an answer. What am I missing?

I am developing a custom theme. The site is on Mamp. Any insight would be helpful.

It seems like all js variables are missing, that are in:

<script type="application/json" data-drupal-selector="drupal-settings-json">{...}</script>

This json array is on every page drupal delivers. You can check this on a fresh drupal install.

There can be a problem with your theme, probably with the html template.


Capturing Views AJAX pager click I am on Drupal 7.

I have a Views block with a pager sitting on the bottom part of it. I am using AJAX pager, meaning the page isn't reloaded. When the pager is clicked, the block reloads all the elements inside of it to display elements on the second page. But because my block is kind of long, when the pager is triggered, I would like to take my user again to the top of the block. I can do that with an anchor that will slowly scroll the page to the anchor that sits on top of that block. There is no issue with this. My doubt is: how can I add a javascript listener that will capture a Views AJAX pager click so that my code can be executed? What is the right Drupal way of doing this? Thank you so much.

In ajax view, by default this functionality is already there. When you click on ajax pager it will automatically scroll to top of content. If it is not working check your console for is there any error showing.


Drupal 7 Views: Display a Taxonomy term as its Term-ID number for a node I have a View that displays Nodes. Each of the nodes have a taxonomy term applied to it.
I would like this taxonomy term to be display as it's Term-ID number. How can I do this?

Steps I have tried

In relationships, I have added "Content: Taxonomy terms on node". This is the only option for taxonomy terms in a node View. But it doesn't have options for accessing the term ID.

In fields, you can add a field to display the term on a Node. I have checked "Rewrite the results". There is a token called Raw, but it only displays "Raw Text" as opposed to a number.

Here are few things you need.

In relationships, add Content: Taxonomy terms on node.
In Filter Criteria(I think this is the one you are missing), add Content: has taxonomy term and check the "is not empty(NOT NULL)".
In Fields: Add Taxonomy term: Term ID

PS: in step 2, you may pick other operator based on what you need.


What is the first parameter of this db_query call for? I've inherited some code. It works, but I'm wondering what the "5" does in this db_query statement.

$result = db_query(5, "SELECT * FROM {foo} WHERE bar = '%d'", $bar_val);

The first argument taken from db_query() is the query string to execute; the next parameters are the values of the placeholders used in the query strings.

If you see code similar to the one you show, it means the content of includes/database.mysql-common.inc, or includes/database.pgsql.inc (depending on the database engine used) has been changed to alter the first parameter used from db_query(). If you are using third-party database drivers, check the database.<database-engine>.inc file that should come with that database driver.


Under what circumstances should a site be placed into maintenance mode I was recently ask to deploy a set of changes to a production server. The changes included Drupal core and contrib module updates, as well as, updated custom theme related code.

In preparation for deployment, I placed the site into maintenance mode. Then took a database backup (using drush sql-dump).  I then pulled in the latest changes with git and updated the database (using drush updatedb). In this case there were several updates which were executed.  Finally I took the site out of maintenance mode.

The site owner was not so keen on the fact that the site was placed into maintenance mode for this procedure.  He mentioned that in general they don't use maintenance mode when updating a site.

This got me wondering under what circumstances, when updating a site, should one use maintenance mode? Are there any situations when one could get away with updating a site without using maintenance mode?

In my experience working on some very high profile D7 installations, maintenance mode is always required during updates. The steps you took to perform your update are essentially the same as I've experienced. The reason for using maintenance mode is to essentially lock out users from making database changes that might corrupt the DB when update.php(drush updb) is run. I can't think of any good reason why you would do a production update without maintenance mode, unless you like playing Russian Roulette with a production DB. I also hope you're doing the updates during non-business hours or during a scheduled maintenance time.


Conditionally require user to complete a content type based on answers from other content types? I'm working on a drupal project that collects information about a business and then offers advice based on the information submitted.

Following the initial sign up process, a user can add a new business profile content type.  This will be the entity referenced by all other nodes related to this entity aka the "business profile". Based on the answers provided within this initial questionnaire, I want to require the user to complete other supplemental questionnaires (basically other content types with entity reference to the main business profile content type) before submitting a finalized business profile.

For example, in the initial business profile there may be the question "Do you have any foreign operations?", if the user answer yes, I would want to make them complete the "foreign operations" content type questionnaire with many fields that relate to foreign operations.  Further, if the user answers no to a question such as "do you have any employees?" I don't want to make the user complete an extended questionnaire (aka an employee related content type) regarding employees.  In addition to simple yes/no answers, if a user selected a certain business industry SIC code from a select list, I would want to require specific content types to be completed with questions related to this industry.  In my mind, I could have 50 content types with questions, but for each business's unique operations, they may only need to complete 5 of those content types.  Finally, I would need a dashboard to keep track of what content types are required, pending and have been completed - then once all of the required supplemental content type questionnaires are verified completed, allow the user to submit a finalized profile.

I would say my level of drupal is intermediate as I understand the basics of entity referencing, structure and views; however, admittedly my experience in rules is limited. I'm using drupal 7.x.

I'm hoping someone can help to offer me a rough step by step of how best to accomplish this. (i.e. use this module, within rules conditions add blah, etc. etc.)  Is my approach the correct one or is there a better solution such as webform, etc.?

Any help or guidance is appreciated.

Interesting question (challenge), with quite some background info (so well documented question). It seems that at its core, this is the key challenge you need to address:

  Finally, I would need a dashboard to keep track of what content types are required, pending and have been completed - then once all of the required supplemental content type questionnaires are verified completed, allow the user to submit a finalized profile.

Here is a "rough step by step" answer you asked for:

Use the Flag module to introduce a set of flags related to your business content type. That set consist of 1 flag for each extra questionnaire (content type) that might possibly be needed. E.g. 1 flag related to "foreign operations" and another flag related to "employees".
Use the Rules module to automatically set the appropriate flags to indicate that some related content type is required, but still missing (or not fully completed yet).
Whenever such related content type gets completed, you "unset" (automatically, via Rules) its corresponding flag.
Should you want to implement some review process (as per your "review completed" you mentioned), you may want to add the Workbench module to the mix (maybe some of its related modules also?), so that the "unset" of these flags only happens after the "status" of some related content type became something like "approved".
As soon as a business profile no longer has any of such flags set, your business content type can be considered as a "finalized" profile.
Possibly you may want to add the Content Access module to the mix, to implement some additional features that you may want to use.
To implement your "dashboard", you just have to build a few (rather basic) reports using the Views module, with appropriate fields, filters, etc related to the various flags.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module.


Drupal Database User 1 Permissions From the community documentation, create database permissions, the superuser/1 should have these permissions:

SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES, CREATE TEMPORARY TABLES

There is comment here about install.mysqt.txt that the docs may be incomplete or ambiguous. Also, my Cpanel configruation shows additional permission options that I am unfamiliar with as does the GUI program I am using for MySQL.

My question is, are there situations where modules for things like services, SOAP, REST, SPARQL, SSL, or other APIs and connecting technologies need to use the additional database permissions?

Short answer: yes.

Long(er) answer:
There are definitely modules that would make use of those MySQL permissions.  Not to mention administrative functions like installing new modules, doing updates, etc.

'grant all' for your Drupal database user is the easiest/best way to do this.  However, once a site is up and running,  I would imagine that you could remove a LOT of those permissions.


Module to manage lots of blocks Any module to manage lots of blocks?
Since the block page is so huge to load.
Or any other methods to manage lots of custom user defined content expect node.

Try the Context module.

  Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

  Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.


How to create a list of webform submissions for a particular webform How to create a list of webform submissions for a particular webform. I have multiple Webforms on my site. I want to display list of Webform submissions for a particular webform only.
Tried to Use View module  but it shows all Webform submissions

To view the submissions for a particular form you can just click the Results tab on the webform node, and you will have a list of submissions for that form, or go to node/1/webform-results where 1 is the node id.

You can also go to Administration > Content > Webforms (admin/content/webform) and click the Submissions link for the form you want to see the submissions for.

This is for Drupal 7 and Webform 3, but I believe it's more or less the same for the other versions.


Drop down triggering image_button callback I have a custom form with 2 dropdowns which trigger an ajax callback on change and change the html inside a wrapper. If I use a submit input with this form which has its own submit callback function, it works fine but if I change the input to image_button with same callback function, changing the values in dropdown ends up triggering image_button callback.

$form['fieldset1'] = array(
    '#type' => 'fieldset',
    '#title' => t( 'Fieldset Title' ),
    '#title_display' => 'invisible'
);
$form['fieldset1']['select1'] = array(
      '#type' => 'select',
      '#title' => t( 'Select 1' ),
      '#title_display' => 'invisible',
      '#options' => $options,
      '#default_value' => $default_value1,
      '#ajax' => array(
          'event' => 'change',
          'callback' => 'select1_callback',
          'wrapper' => 'my_wrapper_id',
          'method' => 'replace',
          'prevent' => 'click',
          'effect' => 'fade'
      )
  );
$form['fieldset1'] ['select1'] = array(
    '#type' => 'select',
    '#title' => t( 'Select 2' ),
    '#title_display' => 'invisible',
    '#options' => array_combine( range( 1, 10 ), range( 1, 10 ) ),
    '#default_value' => $default_value2,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'select2_callback',
        'wrapper' => 'my_wrapper_id',
        'method' => 'replace',
        'prevent' => 'click',
        'effect' => 'fade'
    )
);
$form['fieldset1']['to_be_changed'] = array(
    '#type' => 'item',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => $to_be_changed_value,
);
//This works.
$form['fieldset1']['submit'] = array(
    '#type' => 'submit',
    '#value' => t( 'Submit Button Value' ),
    '#submit' => array( 'button_callback_function' )
);
//This doesn't work. The button works but dropdown callbacks call button callback
$form['fieldset1']['image_button'] = array(
    '#type' => 'image_button',
    '#name' => 'image_button_name',
    '#value' => t( 'Image Button Value' ),
    '#src' => drupal_get_path( 'module', 'my_module' ) . '/assets/img/image.png',
    '#submit' => array( 'button_callback_function' )
);

Not sure what I'm missing over here.

Found the problem with the code. Image_button won't have any #value. It will only have return_value which in this case can be same as what I was putting in #value.

    $form['fieldset1']['image_button'] = array(
    '#type' => 'image_button',
    '#name' => 'image_button_name',
    '#return_value' => t( 'Image Button Value' ),
    '#src' => drupal_get_path( 'module', 'my_module' ) . '/assets/img/image.png',
    '#submit' => array( 'button_callback_function' )
);


Hook into update/install process callback (Update manager) - providing a custom message after installing a module from URL After installing a module from a given URL (on admin/modules/install), I can see the following messages:

So it outputs 3 links in the "Next steps" list, but I would like to hook into the update callback process, extend this list, and provide another link which points to a callback page defined by my own module, where I can enable the module immediately. I don't need help for the latter, only for the way to hook into the process of altering/extending the messages in the result.
After hooking into to the process of generating the output (hooking into the callback process), I will need to know the module's machine name.

This is what the expected result would look like:

OR

OR

What would be the appropriate way to provide custom messages in the update callback?

The "Installation was completed successfully." text is defined by update_authorize_install_batch_finished() in modules/update/update.authorize.inc (and gets into $_SESSION['authorize_results']['page_message'] as an array), and the "Next steps" list is provided by ModuleUpdater::postInstallTasks in modules/system/system.updater.inc.

I think the easiest way would be to extend the ModuleUpdater class to provide your own postInstallTasks() implementation:

class MyModuleUpdater extends ModuleUpdater {

  /**
   * Overrides ModuleUpdater::postInstallTasks().
   */
  public function postInstallTasks() {
    return array(
      l(t('Enable @module module', array('@module' => $this->title)), 'admin/modules/enable/' . $this->name),
      l(t('Install another module'), 'admin/modules/install'),
      l(t('Enable newly added modules'), 'admin/modules'),
      l(t('Administration pages'), 'admin'),
    );
  }

}

And then implement hook_updater_info_alter() to let Drupal know you want to use that class instead of the default:

function MYMODULE_updater_info_alter(&$updaters) {
  $updaters['module']['class'] = 'MyModuleUpdater';
}

You'll also need to add this to your module's .info file so the new class can be autoloaded:

files[] = path/to/MyModuleUpdater.php

Once you clear the caches the change should take effect.


Too many redirects error with https and domain access module I'm redirecting traffic for my various domains to HTTPS. Things seem to work fine on my local, but when I deploy to my production site I get the "www.mysite.cn redirected you too many times." error. I'm on Acquia Cloud, so I have limited access to debug apache stuff on the server.

I suspect that this may have something to do with the Domain Access module b/c we have another site with a couple domains running a multisite install (no domain access) and redirects / ssl work fine.

Details:

Drupal (7.56) site running domain access (7.x-3.13) for about 10 domains for various languages (site.com, site.de, site.cn)
Running on Acquia Cloud Professional (use of "HTTP:X-Forwarded-Proto" should handle load balancer issues)
UCC (SAN) SSL certificate with 20 domains on it
the .com domain (default for domain access) switches to https with no problems when deployed, all other domains give me the "too many redirects" error
on my test environment test.mysite.com resolves to https despite the "RewriteCond %{HTTP_HOST} !^.test..$ [NC]" condition

Relevant code:

.htaccess

#Send sites to www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^.*devcloud.acquia-sites\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Send PROD sites to https
RewriteCond %{HTTP_HOST} !^.*dev\..*$ [NC]
RewriteCond %{HTTP_HOST} !^.*test\..*$ [NC]
RewriteCond %{HTTP_HOST} !^.*local\..*$ [NC]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

settings.php (standard domain access bootstrap include at the bottom)

// domain access
include DRUPAL_ROOT . '/sites/all/modules/contrib/domain/settings.inc';

Just in case anyone stumbles upon this (or perhaps for my future self). The issue ultimately ended up being Cloudflare. If you use Cloudflare for any of your domains don't forget to include it in the stack of things you're looking at when debugging (like I did).

If you use Cloudflare, there is a section under the "Crypto" menu for "SSL". I believe the default setting is "Flexible", if you leave this setting you can end up in a situation where you're bouncing between your load balancer and Cloudflare.
The setting you want is "Full" once it is set to "Full" you shouldn't keep getting bounced around.

This also explains why our .com was not getting the redirect error. Our .com is the only domain not on Cloudflare b/c that DNS is out of my control


Bizarre Behavior with Markdown Filter and Cache Clearing We are trying to allow Markdown input on long text fields for certain content types. It is proving difficult. Here is what I have done:

Installed Markdown filter module.
Added a new Text Format in Configuration -> Content Authoring -> Text Formats.
Edited the text fields on our "Lesson Plan" content type so that the user can select "Markdown" text format.

That should be everything I have to do, right?

BUT WAIT -- number 2 above is giving me very strange behavior!

In my "Markdown" text format configuration page, I can't see the Markdown option unless I first clear all the caches while I am on that page.
After I have cleared the cache, the Markdown checkbox shows up, and I can select it.
But after hitting "Save Configuration", the option disappears, and none of my content formats correctly when I try to select the Markdown text format.

Why is this happening? I don't know where to start looking!

I fixed the problem. I don't know why it acted the way it did, but it started working after I deleted the markdown folder in sites/all/modules, and re-installed using the "official" /admin/modules page (which is SSL enabled).


Event volunteers registration module I'm looking for a module for an event website which calls for volunteers to register by sending name/email.

Ideally, it would allow some users to access the registered volunteers database in some downloadable format (CSV for instance).

Is there something like this for D7? I've been googling but found nothing.

I've used the Webform module for this situation in the past.   Just create a name and email component!

  Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.


Weird spacing in Views content after unspecified module update I'll preface this by saying, I am very new to Drupal and pretty much have no idea what I am doing.  I did not develop the site I am going to reference.  With that said, recently I updated a handful of modules, I couldn't say which ones (I can't remember) and now there is some weird spacing on one of our pages which was created with Views.

The page that is throwing a weird spacing issue is https://tarltontest.law.utexas.edu/about-the-library/hours

The issue is that the data range between parentheses is now on three lines, rather than inline with the title, ie Fall Semester Hours, Fall Finals Hours, etc.

I cannot figure out where the spacing is coming from.  I cannot see anything in the Views settings that would cause this.  IS this a template file>  CSS? I don't even know where the parentheses are coming from.

I would love any help in identifying where to possibly look to fix this.

The issue is that the data range between parentheses is now on three
  lines, rather than inline with the title, ie Fall Semester Hours, Fall
  Finals Hours, etc.

looks fine to me...


Field for if the current user is a member of the organic group I am working with Services module to create an API. I have created a View that shows list of Organic groups.

Now I need to add a field which will show if the current user is member of the group or not. Can anyone please tell me how to do this?

There is no field or direct method to show "If the current user is member of the group or not". In your case I have found a solution here:

Create a view - showing list of all groups(you have already created).
Add new Relationship - OG membership: OG membership from Node group
Add new field - (OG membership from node group) OG membership: Group ID (Group ID), you can exclude it from display.
Add new field - Global: PHP (you have to enable Views PHP module for this field) and put below code in this field:

<?php

global $user;
$account = user_load($user->uid);
$ugrpid = $account->og_user_node['und'][0]['target_id'];

if($row->gid == $ugrpid){
  echo "Already Subscribed.";
}else{
  echo "Not member of this Group.";
}

?>

This is how my view look like( Screenshot ).


Customize admin form field in I need to customize the aspect of one single field in a editing admin form.
More specifically I want change the height of a multiselect field.
Have I to create complete admin sub-theme containing just a one-line CSS file or there is another way to achieve this?

You could use hook_form_alter in a module to attach a the CSS (library) to the form with the needed changes.


How to display 'new' by unread forum posts (like drupal.org)? If I go to my drupal tracking page while logged in I can see a red 'new' by forum posts that have changed since ive visited them. How can I add this functionally? I need to be able to do this without the advanced forum module.

This is the page but you wont see the red 'new' as your not logged in as me. See the attached image to see what I see. Thanks
http://drupal.org/user/643368/track

You can do this by a custom module.

Create a new table in database with 3 column [ nid | uid | viewed_time ] representing node view history.

And override hook_node_view(). The logic could be something like:

if (user is authenticated) {

  if (the node type is forum && nid with current uid is not in a row of view history table) {

    append 'new!' to node title

  } else {

    write [nid , uid, current time] to the view history table

  }

}


Boostrap dropdown menu only working on parent page I have a question, which I want to solve for a really long time now.
I'm creating my own boostrap sub-theme.

I 3 links in my drupal menu:

I want this menu to be available on every page, and it should be possible to access every link on every page. My code in page.tpl.php:

<div class="<?php print $navbar_classes ?>">

        <?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>

                    <?php print render($primary_nav) ?>
                    <?php print render($secondary_nav) ?>
                    <?php print render($page['navigation']) ?>

        <?php endif ?>

However I can only go to the sub (e.g. /info/sub) when I'm on  the parent (e.g. info). I have tried to use superfirsh but then I loose all advantages of boostrap.

Home page, there isn't a caret:

Info page, there is a caret:

Note that the HTML code for the dropdown menu isn't available on the home page.

I know this is possible, but how? Thanks!

Can you please try this:

Go to structure and then open your menu link
Enabled the "Show as expanded" option for your parent menu item.(in your case it is info menu item).

I hope it will work for you.


How to send e-mail to node author 1w before date field in node? I've got a content type with date fields. What I'd like to do is send a reminder e-mail to the post author one week before the value of the date field, with the rules module, or in another way. How would you go about this?

Requirements
Rules, Rules UI, Rules Scheduler, Date, and Date API modules
Add date field
Go to your content types Manage Fields and add a field of type Date.
I called mine Deadline, machine name: field_deadline
Create a Rule
Action: After saving new content
Type: Article

This is all you have to do for now, will get back to this rule later.
Create a component
Component Plugin: Rule

Component action

Add action of Fetch Entity by Property

Add action Send Mail

To: [author-email:0]

Edit your Rule now

Add action of Schedule component evaluation. In SCHEDULED EVALUATION DATE click on the grey switch to data selection button. (not visible in screenshot since I already click it)

Testing
Go to the components tab and click on schedule

You'll need to click those grey switch to ...  buttons to get it to look like mine.
Put a node ID in the last one.

Important
Your e-mail will get sent once the time has been reached, but also once cron runs. So if your cron runs once a day, it may not get sent until the day after, so you may need to adjust your cron to run more often.
You might want to use Ultimate Cron so you can schedule specific crons to run at different intervals, instead of running everything every x minutes, days, hours.


Allow anonymous users to custom menus I recently inherited a legacy project that I've been trying to work with. I defined a custom menu using the menu hook but it looks like anonymous users can't access that menu and instead gets redirected to the user login page. This is a fairly large project and I'm trouble figuring out where exactly the call is intercepted and redirect. Any help would be great.

This is what the redirected looks like if it helps: localhost/user?destination=results

function test_results_menu() {
  $items = array();
  $items['results'] = array(
    'page callback' => 'display_test_results',
    'access callback' => 'test_results_resource_access'
  );
  return $items;
}

function test_results_resource_access() {
  return TRUE;
}

function display_test_results() {
  //  TODO Display results
  return "hi";
}

Update: The odd thing for me is that the project also recently got a rest endpoint using the services module which allows anonymous users to see the data there.

If you want your menu access by everyone set access callback TRUE(not need determine function and it pass TRUE,(maybe this is test and you want in future have condtional menu)).

function test_results_menu() {
  $items = array();
  $items['results'] = array(
     'title' => 'your title',
     'description' => 'menu description',
    'page callback' => 'display_test_results',
    'access callback' => TRUE,
  );
  return $items;
}

function display_test_results() {
  //  TODO Display results
   print "hi";
}

This will be work . please after any change in hook_menu clear your drupal cache.


how to get row field for each node i created a field called : (sitename_ar) and i have two rows (two domains) in  {domain} field :

and i have in my database these two fields {node} and {domain_access} :

and i want display in view page:
node : Title
node : Domain (sitename_ar)
i have created a view and i added a Title field and a Global:php field to call rows from database :

and i addedd those lines :

but always it display the same field (the first row) :

How i can Join all those 3 fields and display for each node her domain (with sitename_ar)

The error is in your php snippet. You request all rows, but $query->fetchObject(); only returns the first one, as you do not iterate over them.
Use something like $query->fetchAll() or $query->fetchAllAssoc('domain_id'); instead to access all rows.

But, I think there must be smarter ways to handle this. Can't you add a relationship from the node to the domain? (I never used domain before). Such relationship would give you the domain entity associated with the node, so you always have the right one.


Is it possible to use Rules to make an action to entities that refers to other with entity reference I have type Article that refers one user with entity reference.

article1 refers to user1
article2 refers to user1

I want a Rule to show a message on user profile with all the articles that refer to this user. Is it possible without coding?

Finaly i found the solution to this problem using module Views Rules.

I create a view of users, i pass the nid as an integer and set a content referencing to the user.

I don't know if there's a better way but this works fine.


How to change drupal commerce views like checkout,payment? i configured drupal commerce module all working fine.question is how to format or design the checkout page,billing page,review page,payment page. i can add more data but how change existing data..i make tpl file for related name but by this we can add more data but how to change existing data plz tell me ASAP.

in detail:actually drupal commerce provides four page for checkout (1)checkout(2)billing address(3)order review(4)payment all are working fine problem is: can i change the all four page's design and add more data to it.how can i find out the html of these four page. i can't figure out by making template file of those four page.

Have you learned Views?
you can try change default views shoppingcart,checkout page,billing page,review page etc.
Eg: to modify shopping cart block you can go to
http://your.site/admin/structure/views/view/commerce_cart_block/edit


Using Panels - Node Template.. How do i pass additional arguments for my blocks? I have content types: Project, News, and Country.

I have a node template that displays details of a Project. This node template displays a view, which displays all the News. I want to filter all the news by the project's Country.

Project has a cck field: country_id. How do i pass it's value to my News view?

tl;dr: using a panel node-template, how do i use the node's cck field as argument?

You need to use content pane for the view to make it accept arguments.

Then when you insert the content pane, you should be able to use the node and all fields on the node using a token system to pass any variable to the view pane. How you setup the content pane determines which types of variables it will accept.


View that shows all children content of parent Been searching and cannot find this anywhere for Drupal 8. Very basic view request, can't figure out why it's not straightforward.

I want a View that shows Parent content and under it all Children content. Nothing to do with taxonomy, just want this to display in a view:

Parent Content 1
 - Child content 1
 - Child content 2
 - Child content 3

When trying a contextual filter, I get "This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'."

It doesn't seem your situation calls for contextual filters, you're not listing anything dependent on circumstances, you aim to list all of the Children, and group them by parent.

Since it's Children being referencing Parent nodes all you have to do to solve this is to a create Views that list Children, add the Parent field (the entity reference field you have on Child nodes), then under your Format settings set the Grouping field Nr.1 to the Parent entity reference field. This is how you display the children nodes in a sort of a hierarchy based on which Parent they reference.

You can edit that Field settings if you want to Exclude from display and you can change the Style settings, the grouping output will take that into consideration most of the time.


Storing images as nodes I am building a Drupal 7 platform where users can share images. In a nutshell, people should be able to comment on images and like them.
The way I realized this is by creating a custom content type called "image" and adding an image field to it. And then I grant users the permission to create "image" nodes.
However, yesterday I came across this Drupal 6 article http://drupal.org/node/325688 and it's section 'Images as nodes'. It introduces the Image module, which lets you upload images as nodes automatically. Unfortunately, the Image module hasn't been ported to Drupal 7.

Is this the clean way to implement images?
The article also mentions the solution that I made use of:

For example, using Imagefield, you could create a custom content type that contains one CCK imagefield, and configure that field to "contain" (refer to) only a single file. However, note that this custom CCK node type would not be compatible with Image module or its add-ons, and should be named something other than "Image" to avoid confusion.

Is there any point in not naming your custom content type "image"? I mean, it would be a super suggestive name. And the Image module which would provide a content type with the same name will most likely never be ported to Drupal 7. So there should never be confusion.
Lastly, the article mentions that

It is theoretically possible that, for sites with lots (say hundreds of thousands) of images, storing them all as individual nodes could result in a performance hit from the extra database overhead.

Well, storing lots of images is exactly what image sharing platforms are aiming at, isn't it? Is there a better way (in terms of performance) to store images in Drupal 7 while still making it possible for people to comment on them?

The image module does not exist in Drupal 7 because this functionality is added to Drupal 7 core.

Implementing images as nodes was a clean way to do this in Drupal 7. You may still do this in Drupal 7. However, Drupal 7 has gone a long way and offers the entity alternative. At Drupal 6 'everything can be a node'. At Drupal 7, 'everything can be an entity'.
Nodes were meant to be used for publishing text. They come with a lot of functionality that you may find redundant in your use case. All this extra functionality can slow down your site if you have thousands or millions of entries.

I am not sure I understand why you should not do this. It was probably a suggestion and module specific. In Drupal 7 you can name your content type anything you want.

As I told you before, using entities for storing images is a better alternative, as far as the performance is concerned. But then you should implement your own method of commenting.

EDIT: In Drupal 8 there is some advances made in decoupling the comment module from node. See this issue.


Backup and Migrate module - no option to back up files? In Drupal's Backup and Migrate module (/admin/config/system/backup_migrate), the only option for "Backup from" is "Default Database". In tutorials, that drop-down seemingly should also have "Public Files Directory".

I'm a new Drupal user - is there something simple I'm missing here?

There was a module which did this earlier, Backup Migrate Files, but it got obsolete and the code is not merged with Backup Migrate module, and is available with version 7.x-3.0
Make sure you use the latest version of the module.


How to change the label of exposed grouped Filter field in Views? Ok, I also have the Better Exposed Filters module installed and enabled on this view, but this does not help.  I have no control over the label of this exposed filter that is being grouped.  There is no option to change the label on grouped items, only on single items.

What do I have to do to be able to change the label?  Am using Drupal 7.24 and Views 7.x-3.7 and Better Exposed Filters 7.x-3.0-beta3.

Thanks to anyone who can help... right now it is showing the machine label in parenthesis next to the actual title of the field.  I'd rather just have only the title of the field.

Here is what the settings look like for an exposed grouped filter to me:

And here is what the filter looks like on the actual view:

How to get rid of the (field_department) text or change the label completely?

Normally you can remove field machine name from the configuration itself as shown below, but seems like those portion is hidden from your screenshot. Please check those portion, also check this troubleshoot Can't set the label for an exposed grouped filter.

If still no help you can use hook_form_alter(&$form, &$form_state, $form_id) to change the label


Full content view mode per role I've looked around but didn't find the right solution. In D7.5x I would like to create different view modes (of Full Content) per role. I am using Display Suite.

The situation should be like this: I have teaser view mode, Full content (limited) view mode, Full Content (extra) view mode. Is there any quick solution, to let users with role A after clicking onto link in teaser view mode get to see Full content (limited) and users with role B get Full content (extra)?

tnx

Oh, It looks like I've found an answer myself, so I will post it here in case someone will have similar issue. One of the solutions (I am still not sure if this is the optimal one, but it works) is to use module Contextual View Modes (It requires Context module and Entity API). With this combination of modules it is possible to create context rules where in Conditions section there is particular user role and in Reactions one must define particular View mode for Content Type. And that's it! It just requires at least 3 modules to be installed, so maybe there is some simplier solution...


Is there a way to export ALL translations into a single .PO file? To translate my website, I need to export translations one by one per group type.

This gets to be confusing as some fields share core terms ect...

Is there a way to do a consolidated ONE .po file for all translations?

Each entry in .po file has only two strings;

msgid untranslated-string
msgstr translated-string

Thus, by it's very nature it can only keep two languages: original and one translation. So no, there is no way to do it because format does not support that. For details, see documentation.


Taxonomy view : add token term_name in url I have a view overriding taxonomy term pages with the help of Panels. I defined that pattern in URL aliases : destinations/[term:parents]/[term:name].

Now I'd like to set a clone of that view, slightly different in its filters, with the same panelizer variant (or a variant clone), following URL pattern :destinations/[term:parents]/[term:name]/foo where foo is a fixed word.

How could I do that please ?

This does what expected.

In the content pane view, Contextual filters : Content: Has taxonomy term ID (with depth), use the filter value type "Term name converted to term ID"

In the custom page, in basics, set the path almost as in the question destinations/[term:name]/foo (I abandoned the [term:parents] part, no way).

And in arguments, choose "argument type:term name".


How to set a new value in a paragraph field on submit? In an edit form for a content with paragraphs, I set errors on the paragraph specific field with this particular syntax:

$form_state->setErrorByName('field_paragraphs][' . $key . '][subform][field_sharepoint_file_url][' . $key2, t('Invalid URL'));

(see the missing square brackets at the beginning and at the end, solution found here)

This is working well.

However, I also need to register a different value on this field, and I can't seem to find the right way to do so.

I've tried to do this in a submit callback:

$form_state->setValue('field_sharepoint_file_url', $data->alias);

Or by retrieving the paragraph object in the hook_ENTITY_TYPE_presave:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'page') {
    $result = $entity->get('field_paragraphs')->referencedEntities();
    if (!empty($result)) {
      foreach ($result as $paragraph) {
        /* @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
        if($paragraph->getType() == 'sharepoint_file') {
          /* @var \Drupal\Core\Field\FieldItemList $url */
          $urls = $paragraph->get('field_sharepoint_file_url');
          /* @var \Drupal\Core\Field\Plugin\Field\FieldType\StringItem $url */
          foreach ($urls as $url) {
            // [...]
            $paragraph->set('field_sharepoint_file_url', $data->alias);
          }
        }
        $paragraph->save();
      }
    }
  }
}

But the new value is never registered in database.

Thanks for any tip on this.

I'd imagine the first didn't work because your custom submit handler is run after the form default submit handler so it's too late (You didn't provide this code so can't be certain). You'd need to make sure your submit handler is run before any other submit handlers. To do that in the array of submit handlers your needs to be first in the array

Similarly for the 2nd option you've tried, you're in hook_presave so you're changing things but then when the normal entity save function happens after this any changes you made are overwritten


How to show thumbnail for image when edit the node Drupal 8 I need to add thumbnail for field image when I edit node

Field settings and type:
Could you please explain How to do it. Thanks.

I resolved that issue.

Me steps:

go to image style and create new image style (/admin/config/media/image-styles).
go to View modes (/admin/structure/display-modes/view)
find Media section and create new view mode for media (/admin/structure/display-modes/view/add/media)
go to Media bundles (/admin/structure/media).
edit Image and go to Manage display (/admin/structure/media/manage/image/display)
click edit to your view

Now we can configure Paragraph content type or Content type


How to get Media image values (alt and title) in Views? I want to edit the Media library module View to show the images Alt and Title field value, but it is not in the available fields (only "Thumbnail(alt)" which prints the image).

All available relationships also do not give alt or title.

It seems the Image settings fields are not available in views?

alt and title are stored in field_media_image of the media type Image. To access the values in Views add this field to FIELDS and select/configure a field formatter to display the values.

To output the raw values outside of a formatted image rewrite the field and use the replacement patterns:

{{ field_media_image__title }}
{{ field_media_image__alt }}


How to override system_time_zones in Drupal 7 How can I override the system_time_zones() function without hacking the Drupal 7 core?

I would like to modify how the dropdown list is presented, but cannot seem to get at it with hook_form_alter().

My end goal here is to reformat the timezone dropdown list to include only the location and offset by removing the date/time from the <select> lists <options> text.

For example,

'Pacific/Honolulu: Friday, June 1, 2012 - 6:43pm -1000' would change to
'Pacific/Honolulu: -1000'

This would be a simple edit to system_time_zones() in system.module, but hacking core is not an option for me.

If I were to hack core, this is what I would like to do.

Before Edits (for reference):

function system_time_zones($blank = NULL) {
  $zonelist = timezone_identifiers_list();
  $zones = $blank ? array('' => t('- None selected -')) : array();
  foreach ($zonelist as $zone) {
    // Because many time zones exist in PHP only for backward compatibility
    // reasons and should not be used, the list is filtered by a regular
    // expression.
    if (preg_match ('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
      $zones[$zone] = t('@zone: @date', array('@zone' => t(str_replace ('_', ' ', $zone)), '@date' => format_date(REQUEST_TIME, 'custom', variable_get('date_format_long', 'l, F j, Y - H:i') . ' O', $zone)));
    }
  }
  // Sort the translated time zones alphabetically.
  asort ($zones);
  return $zones;
}

After Edits (Changes are to $zones[$zone] in @zone string):

function system_time_zones($blank = NULL) {
  $zonelist = timezone_identifiers_list();
  $zones = $blank ? array('' => t('- None selected -')) : array();
  foreach ($zonelist as $zone) {
    // Because many time zones exist in PHP only for backward compatibility
    // reasons and should not be used, the list is filtered by a regular
    // expression.
    if (preg_match ('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
      $zones[$zone] = t('@zone: @date', array('@zone' => t(str_replace ('_', ' ', $zone)), '@date' => format_date(REQUEST_TIME, 'custom', ' O', $zone)));
    }
  }
  // Sort the translated time zones alphabetically.
  asort ($zones);
  return $zones;
}

How can I accomplish this without messing with core?

I was able to access the timezone dropdown list by implementing hook_form_alter() with an #after_build function.  You can filter, clean and modify the array here.

function MYMODULE_form_user_profile_form_alter(&$form, &$form_state) {
   $form['#after_build'][] = 'MYMODULE_timezone_modify';
}

function MYMODULE_timezone_modify($form, &$form_state) {
   $form['timezone']['timezone']['#options'] = array(/*Your New or Modified Array Here*/);
   return $form;
}