Accessing field variables in Views 3.0 Since the Documentation for Views 3.0 isn't out yet, does that mean that the way you access field variables is different from Views 2.0? That's because whenever I try the following code (from Views 2.0 docs: http://drupal.org/node/352970), all I get are errors:

<?php
    dsm(array_keys($fields));

    //ERROR message after placing it in views-view.tpl.php:
    Notice: Undefined variable: fields in include() (line 33 of D:\xampp\htdocs\foo\sites\all\themes\foofoo\views\views-view.tpl.php).
    Warning: array_keys() expects parameter 1 to be array, null given in include() (line 33 of D:\xampp\htdocs\foo\sites\all\themes\foofoo\views\views-view.tpl.php).
?>

In my modules I have Devel and Theme Developer enabled so why isnt it working? I also rescan my template files like a boss and clear my cache like a disease but still nothing.

Have you tried:

<?php
 dsm (array_keys(get_defined_vars()));
?>


AJAX callback inside hook_form_alter() I don't know how to implement AJAX callback in hook_form_alter().

The field is plain text by default and it is populated by NID (number) of the client company. The module name is "my_car". I didn't use node reference in this field.

Here is the code:

function my_car_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'car_node_form') {

        $clientCompanies = companyTitle(12); // TID 12

        // Replace Client company NID with title
        $form['field_car_company']['und'][0]['value'] = array(
            '#title' => 'Client company',
            '#type' => 'select',
            '#default_value' => $form_state['node']->field_car_company['und'][0]['value'],
            '#options' => $clientCompanies,
            '#required' => TRUE,
            '#empty_option' => t('- Select -')
        );
    }
}

Here I use companyTitle() function to return all companies (nodes) that have TID 12 and replace field type ("textfield" with "select") and it's content - a number with text (NID with title).

function companyTitle($tid) {

    $results = db_query("
        SELECT n.nid, n.title
        FROM {node} AS n
        LEFT JOIN {field_data_field_company_type} AS ct ON ct.entity_id = n.nid
        WHERE n.type = 'company' AND ct.field_company_type_tid = :tid
        ORDER BY n.title ASC",
        array(':tid' => $tid))->fetchAllKeyed();

    return $results;
}

I have written the function that returns NID and title of client company based on TID and title:

function ajaxCompanyTitle($tid, $companyName) {

    $query = db_select('node', 'company')
        ->fields('company', array('nid', 'title'))
        ->condition('company.type', 'company', '=')
        ->condition('type.field_company_type_tid', $tid, '=')
        ->condition('company.title', '%'.db_like($companyName).'%', 'LIKE')
        ->orderBy('company.title', 'ASC')
        ->range(0, 10);

    $query->leftJoin('field_data_field_company_type', 'type', 'type.entity_id = company.nid');

    $results = $query->execute()->fetchAll();

    return $results;
}

Now is the question of how to implement AJAX with the last function. I need text field (it does not to be a select list) with AJAX search where NID will be rendered as title (NID remaining only in the database in the field_car_company_value column).

Apparently, I don't know how to implement a callback function.

function my_car_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'car_node_form') {

        // Replace Client company NID with title
        $form['field_car_company']['und'][0]['value'] = array(
            '#title' => 'Client company',
            '#type' => 'textfield',
            '#required' => TRUE,
            '#ajax' => array(
                'callback' => 'ajax_callback',
                'wrapper' => 'edit-field-car-company-und-0-value',
            )
        );
    }
}

function ajax_callback($string = '') {

    $matches = array();

    if ($string) {

        $clientCompanies = ajaxCompanyTitle(12, $string);

        foreach ($clientCompanies as $clientCompany) {
            $matches[$clientCompany->title] = $clientCompany->title;
        }
    }

    drupal_json_output($matches);
}

There are two types of ajax in Drupal. Traditional AJAX, and the Drupal Form API #ajax api. You are mixing the two, by using #ajax in your form, but returning and AJAX response, rather than an #ajax callback response.

To understand #ajax, you need to understand the process by which the Form API works. This is how a standard non-Ajax Form API form works in Drupal:

Some function is called which builds a render array representing the form.
Form alter hooks are called, allowing other modules/theme to alter the form.
Drupal caches the render array in the database, to be used for comparison on submission, as a security measure to ensure that the submitted data matches the type of data expected to be submitted.
The form is rendered into HTML and sent to the browser.
The user submits the form.
Drupal retrieves the form from the database, confirms that the submitted data is allowed, and sanitizes it.
Drupal validates the form, runs submission hooks, and redirects the user to whatever page they are supposed to be on after form submission.

When #ajax is implemented, the process is the same as above, but with some additional steps in the middle.

Some function is called which builds a render array representing the form.
Form alter hooks are called, allowing other modules/theme to alter the form.
Drupal caches the render array in the database, to be used for comparison on submission, as a security measure to ensure that the submitted data matches the type of data expected to be submitted.
The form is rendered into HTML and sent to the browser.

---------- #ajax behavior start --------------

The user does something that triggers #ajax
The browser sends all the data in the form back to Drupal, as if the form were submitted.
Drupal retrieves the form from the database, and confirms that the submitted data is allowed, and sanitizes it.
Validation and submit handlers for the form are called. The form must be set to be rebuilt in the submit handler for the ajax to work.
The form is rebuilt from the original form definition, passing it the #ajax submitted values.
Form alter hooks are called, allowing other modules to alter the form, using the #ajax submitted values.
Drupal caches the new render array in the database, to be used for comparison on submission.
The ajax built form is passed to the #ajax callback handler. The handler then returns the part of the form to be injected back into the DOM on the browser. This can be part or all of the form.
The new content is inserted into the DOM.

---------- #ajax behavior end --------------

The user submits the form.
Drupal retrieves the form from the database, confirms that the submitted data is allowed, and sanitizes it.
Drupal validates the form, runs submission hooks, and redirects the user to whatever page they are supposed to be on after form submission.

Referring back to your code, your ajax callback will receive two arguments, $form and $form_state, and needs to return a section of your form. So it should look something like:

function ajax_callback($form, $form_state) {
  return $form['some_element']['of_the_form'];
}

In your form, this is likely $form['field_car_company']['und'][0]['value']. You will build the options of that form element when the form is initially rendered the way you are now, and if the form has been submitted using ajax, use the submitted values to determine the new options to show.


form_state->setRedirect(to_a_new_node_page) from the submitForm function, route "does not exist" issue I created a custom module, It generate a custom Form in a page.
When I submit my form, I create a new node.
So, I am redirect to the form page but I would like be redirect to the new node page.

I add this line at the end of my submitForm function :

$form_state->setRedirect('node/'.$mynewnode->id());

But when I submit my form from the website, I get the empty-white-screen-of-the-death. My apache log :

...
Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "node/153" does not exist.
...

And then, when I go manually to the node/153 page, there isn't any problem. The page work well.

My question : where is my mistake ? How can I set the redirection after create the new node ? Is it possible from the submitForm function ?

I think if you want to use the setRedirect function then you might want to look at its documentation found https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AsetRedirect/8

You can then base the ff. code from FormSubmitter::redirectForm or FormSubmitterInterface::redirectForm. So your code might look something like:

$form_state->setRedirect('entity.node.canonical',
  array('node' => $mynewnode->id()),
));

You can also find out where is "entity.node.canonical" from by searching in core/modules/node and where it is declared and what it's about.

Hope everything's going great!


How do I control what to publish as Facebook Instant Articles? I am using this Facebook Instant Articles module to integrate articles being published as Instant articles on Facebook. I have successfully tried to publish instant articles using the RSS Feed and Views modules.

When I look at the preview of the feed, the articles being added on the feed are all the articles recently published. This is not what I want. I checked the configuration, and I found out that I have to select each article.

Now, after doing this, I still can't filter out the articles which are selected to be published as instant articles. I tried adding a filter, but I can't add a Filter on my view. I have not yet added custom codes just via the administrative dashboard.

What I want is to freely filter out specific articles I want to publish as instant articles. In my case, the articles processed from the feed are the latest ones; if I edit an article to add it as instant article, it won't be shown.

Can someone help me here?

You can for example add a taxonomy to the articles and filter by that in the view.


Drush command to check if Drupal is installed? Is there any way to use Drush to determine if Drupal is installed, and have it return true or false? The boolean output would be used elsewhere in a bash script's logic.

Bonus: it needs to work for both Drupal 7 and Drupal 8.

$ cd /path/to/drupal6or7or8
$ drush status bootstrap | grep -q Successful

Then, $? will be 0 if Drupal has been installed, or 1 if there is no site, or it does not have a database, or the site has not been installed.


How do you output views reference field views in Twig? I'm currently trying to output views referenced in a node (with Views Reference Field) inside page.html.twig Twig template.

I know I can just add or embed a view using {{ drupal_view('machine_name', 'block_1') }} (with Twig Tweak) in my Twig template. But I want the editors to have the flexibility to add or change views in the node and have them printed without writing code.

I can't seem to find any documentation on how to output a referenced view to my Twig template.

Got it!

You have to pass the view ID and the display ID to drupal_view() dynamically.

But first let me tell you that what you are doing, printing node stuff inside page level templates, should be considered bad practice. Good practice is to leave templates untouched, and to offer field formatters and other stuff instead that keeps the admin UI intact. So, when you get your first maintenance breakdown in a year or so, don't tell us we didn't warn you.

page.html.twig

{% if node.field_views and not node.field_views.isEmpty() %}
  {% for view in node.field_views.value %}
    {{ drupal_view(view['target_id'], view['display_id']) }}
  {% endfor %}
{% endif %}

You won't get the view title from here. Simply add some Global: unfiltered text to your view HEADER with any title markup. That will get printed.

drupal_view() requires Twig Tweak.


How to create a custom content-type with template for an "empty" page I want to display a Unity webplayer in a modal/overlay. I figured out a way to show a drupal page with the webplayer in the overlay, so I'm almost there. But that page then displays everything, including menus etc. The Context module allows me to strip most of it, but not everything. So it seems having an empty page to start with will be easiest.

What would be the best way to create a Drupal page that only shows the content and is otherwise empty? I have already created a custom content-type for the webplayer, so maybe there is a way to associate that with a custom template file that only prints the content? I'm also writing a module for this, so the solution can require changes that need to be implemented in code.

I'm not very familiar with theming, so I'm also interested what template file needs to be created or changed (page.tpl.php, node.tpl.php or something else altogether).

By code, if you want a page that display's only content, here's how I would do it.

function module_menu() {
$items['overlay/location']=array(
 'title' => 'Title of page',
 'page callback' => 'module_callback',
 );

return $items;
}

function module_callback() {
 echo 'show what ever!';
 //no return!
}

Take a look at hook_menu()


Workbench sections - notify users in a section on state change I want to, for example, use rules to notify all users in a particular section that an item of content in their section is 'awaiting moderation'.
Is there a way in Rules to get access to a node's Workbench section?

I can get access to the workbench access term id/menu id, depending on the scheme I'm using, but how can you find the users in that section from there...

If you use workbench access with a taxonomy scheme you could try this

In rules, add an event After moderation transition.
Add the conditions (previous state moderation, current state moderation) according to yours states in workbench moderation
Add the condition Entity has field and then select the field of your workbench access section (field_section for example : should be the field of your taxonomy vocabulary)

Add an action : send an email.

Then in the field TO of the email , you could use this snippet php wich return the user's email wich have access to the section (specified in Editorial assignments by editor in Workbench Access) and have a specific role id. This snippet return too all the users who have been assigned by their role to the section by their role (Editorial assignments by role in Workbench Access)

<?php

$sections = $node->workbench_access;

$terms=taxonomy_term_load_multiple($sections);

foreach ($terms as $term) {

$parents=taxonomy_get_parents_all($term->tid);

  if (!empty($parents)) {

    foreach ($parents as $parent) {

    $tid=$parent->tid;

    $voc_name=$parent->vocabulary_machine_name;
      if (!in_array($tid, $sections)) {
        $sections[$tid]=$tid;
      }
    }

  $sections[$voc_name]="'".$voc_name."'";
  }
};

// Only the users who have the role id [ROLE_ID]
$role_id=[ROLE_ID];
$emails = array();

foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_user workbench, users_roles roles WHERE roles.rid=$role_id AND user.uid=roles.uid AND user.uid=workbench.uid AND access_id=$section");

  foreach($result as $record) {
    $mail=$record->mail;
    if (!in_array($mail,$emails)) { $emails[] = $mail; }
  }
}

foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_role workbench, users_roles roles WHERE user.uid=roles.uid AND roles.rid=workbench.rid AND access_id=$section");

  foreach($result as $record) {
    $mail=$record->mail;
    if (!in_array($mail,$emails)) { $emails[] = $mail; }
  }
}

print implode($emails, ",");

?>

And you complete the others email's field with the token available.

This sandbox project Workbench Notify implement this snippet


Unable to set custom breadcrumbs I've enabled the Custom Breadcrumbs module and given the administator (me) rights to create custom breadcrumbs.
I am seeing this message on nodes, where it should allow me to set the custom breadcrumb:

Custom breadcrumbs have not been created for this test_content_type page. Use the Custom Breadcrumbs Administration Page to create a breadcrumb.

Going to this page the settings are as follows:
Show only custom_breadcrumbs where

Type is node

Where I see:
Namesort descending Breadcrumb Type Operations
No custom breadcrumbs have been defined.

What am I missing?

From the custom breadbcrumbs README.txt:

  Enable the module
  Assign 'administer custom breadcrumbs' permission to those roles that should   be allowed to add/edit/delete custom breadcrumbs.
  Assign 'use php in custom breadcrumbs' to roles that should be allowed to use   php to determine breadcrumb visibility.
  Go to Administer > Site building > Custom breadcrumbs to add new breadcrumbs
  Click "Add a new custom breadcrumb"
  Choose the node type to create a breadcrumb trail for
  For the titles, put each "crumb" one line after another (There is no need to   put in "home"):

  Item 1   SubItem A   SuperSubItem X
  For the paths, put the path to each crumb starting after the domain name.   Don't include a leading or trailing slash.

  item1   item-1/subitem-a   item-1/subitem-a/supersubitem-x
  Click save to save the breadcrumb
  Visit the page and your breadcrumb should appear!


How to add nofollow attribute to links in profile text field and url field I add 2 fields via Profile module,one is textarea field names "About me", the other one is url field names  "my website". My questions is how to add nofollow attribute to the links in these 2 fields. I googled for a while but without luck.

In your link field settings, there is a setting...

Rel Attribute rel = " "

When output, this link will have this rel attribute. The most common usage is rel="nofollow" which prevents some search engines from spidering entered links.


Add headers to each grouped section in a view I've got some content (Employees) and I've got a View that is showing the content in a grid grouped by Department (i.e. it shows the title "Customer Support" and then a grid of Employees and then the title "Sales" and a grid of Employees, etc.)

I would like to include a paragraph of text before each section, preferably from a content node so that my users can modify the description before each section.

I've seen something online (although I'm having trouble finding it again) about being able to attach a view above another view. Is it possible to somehow display a DepartmentDescription node before each section of my grouped view?

You certainly can, if you use a Views relationship to load in those other Department nodes, add a field using that relationship showing the Department node body, set it to "exclude from display" (so it doesn't appear twice) and in Format: Settings set Grouping to use that specific field.

The key question then is - how does each Employee node know which is the Department node that corresponds to it? I'd suggest you use one of the node relationship/reference modules to link them together - I can vouch for relation which is good, powerful and (since a few months ago) works well with views. It isn't so easy to use and doesn't have a great interface yet, but learning to use it is time well spent, especially for the sort of site you seem to describe. If you think Relation is overkill (it is for many very simple sites), here's a guide which covers the many simpler alternatives.

With Relation, a step-by-step could be:

Create the relation type (say, "is in department" source>target, "has employee" target>source, valid source: employee, valid target: department)
Create a relation for each employee, linking it to its department
In the view, create a node-node Relation relationship using "is in department" from the 'source' endpoint
Add a content:body field, using this relationship. Set it to exclude from view
In View Format: Settings, choose this body field  to group the view


Administer simplenews subscriptions with views In simplenews the default path to manage the subscriptions to newsletters is: admin/people/simplenews. The problem with that page is that it doesn't, for example, have any columns that would allow you to see when the subscription was added or even select all the subscriptions and perform actions on them (a feature that is available by default in vbo).

My question is the following:

Is there any way to make the specific page available for further configuration through Views so that I can add extra fields/features to it? What I'm looking for is basically something like Administration Views but for the simplenews interface.

Answer for 2016 and Drupal 7.  Simplenews module does now include bulk operations.  Simplenews has Views integration built in.  It does not come with a pre-defined view, so you have to create one.

Here is an export of a view that shows when the subscriber was added and by what means.  However Simplenews does not current provide VBO integration to allow a bulk action.

  $view = new view();
  $view->name = 'newsletter_subscriptions';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'simplenews_subscription';
  $view->human_name = 'Newsletter subscriptions';
  $view->core = 7;
  $view->api_version = '3.0';
  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['use_more_always'] = FALSE;
  $handler->display->display_options['access']['type'] = 'none';
  $handler->display->display_options['cache']['type'] = 'none';
  $handler->display->display_options['query']['type'] = 'views_query';
  $handler->display->display_options['exposed_form']['type'] = 'basic';
  $handler->display->display_options['pager']['type'] = 'full';
  $handler->display->display_options['pager']['options']['items_per_page'] = '25';
  $handler->display->display_options['style_plugin'] = 'table';
  $handler->display->display_options['style_options']['columns'] = array(
    'mail' => 'mail',
    'name' => 'name',
    'timestamp' => 'timestamp',
    'activated' => 'activated',
    'source' => 'source',
    'status' => 'status',
    );
  $handler->display->display_options['style_options']['default'] = 'mail';
  $handler->display->display_options['style_options']['info'] = array(
    'mail' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'name' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'timestamp' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'activated' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'source' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'status' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    );
  /* Relationship: Simplenews subscription: Subscriber ID */
  $handler->display->display_options['relationships']['snid']['id'] = 'snid';
  $handler->display->display_options['relationships']['snid']['table'] = 'simplenews_subscription';
  $handler->display->display_options['relationships']['snid']['field'] = 'snid';
  /* Relationship: Simplenews subscription: Term ID */
  $handler->display->display_options['relationships']['tid']['id'] = 'tid';
  $handler->display->display_options['relationships']['tid']['table'] = 'simplenews_subscription';
  $handler->display->display_options['relationships']['tid']['field'] = 'tid';
  $handler->display->display_options['relationships']['tid']['label'] = 'Newsletter';
  /* Field: Simplenews subscriber: Subscriber */
  $handler->display->display_options['fields']['mail']['id'] = 'mail';
  $handler->display->display_options['fields']['mail']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['fields']['mail']['field'] = 'mail';
  $handler->display->display_options['fields']['mail']['relationship'] = 'snid';
  /* Field: Taxonomy term: Name */
  $handler->display->display_options['fields']['name']['id'] = 'name';
  $handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
  $handler->display->display_options['fields']['name']['field'] = 'name';
  $handler->display->display_options['fields']['name']['relationship'] = 'tid';
  $handler->display->display_options['fields']['name']['label'] = 'Newsletter';
  /* Field: Simplenews subscription: Timestamp */
  $handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
  $handler->display->display_options['fields']['timestamp']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
  $handler->display->display_options['fields']['timestamp']['date_format'] = 'short';
  $handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
  /* Field: Simplenews subscription: Source */
  $handler->display->display_options['fields']['source']['id'] = 'source';
  $handler->display->display_options['fields']['source']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['source']['field'] = 'source';
  /* Field: Simplenews subscriber: Activated */
  $handler->display->display_options['fields']['activated']['id'] = 'activated';
  $handler->display->display_options['fields']['activated']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['fields']['activated']['field'] = 'activated';
  $handler->display->display_options['fields']['activated']['relationship'] = 'snid';
  $handler->display->display_options['fields']['activated']['type'] = 'unicode-yes-no';
  $handler->display->display_options['fields']['activated']['not'] = 0;
  /* Field: Simplenews subscription: Status */
  $handler->display->display_options['fields']['status']['id'] = 'status';
  $handler->display->display_options['fields']['status']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['status']['field'] = 'status';
  $handler->display->display_options['fields']['status']['type'] = 'unicode-yes-no';
  $handler->display->display_options['fields']['status']['not'] = 0;
  /* Filter criterion: Simplenews subscriber: Subscriber */
  $handler->display->display_options['filters']['mail']['id'] = 'mail';
  $handler->display->display_options['filters']['mail']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['filters']['mail']['field'] = 'mail';
  $handler->display->display_options['filters']['mail']['relationship'] = 'snid';
  $handler->display->display_options['filters']['mail']['operator'] = 'contains';
  $handler->display->display_options['filters']['mail']['group'] = 1;
  $handler->display->display_options['filters']['mail']['exposed'] = TRUE;
  $handler->display->display_options['filters']['mail']['expose']['operator_id'] = 'mail_op';
  $handler->display->display_options['filters']['mail']['expose']['label'] = 'Subscriber';
  $handler->display->display_options['filters']['mail']['expose']['operator'] = 'mail_op';
  $handler->display->display_options['filters']['mail']['expose']['identifier'] = 'mail';
  $handler->display->display_options['filters']['mail']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );
  /* Filter criterion: Taxonomy term: Term */
  $handler->display->display_options['filters']['tid']['id'] = 'tid';
  $handler->display->display_options['filters']['tid']['table'] = 'taxonomy_term_data';
  $handler->display->display_options['filters']['tid']['field'] = 'tid';
  $handler->display->display_options['filters']['tid']['relationship'] = 'tid';
  $handler->display->display_options['filters']['tid']['group'] = 1;
  $handler->display->display_options['filters']['tid']['exposed'] = TRUE;
  $handler->display->display_options['filters']['tid']['expose']['operator_id'] = 'tid_op';
  $handler->display->display_options['filters']['tid']['expose']['label'] = 'Newsletter';
  $handler->display->display_options['filters']['tid']['expose']['operator'] = 'tid_op';
  $handler->display->display_options['filters']['tid']['expose']['identifier'] = 'tid';
  $handler->display->display_options['filters']['tid']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );
  $handler->display->display_options['filters']['tid']['type'] = 'select';
  $handler->display->display_options['filters']['tid']['vocabulary'] = 'newsletter';
  /* Filter criterion: Simplenews subscriber: Activated */
  $handler->display->display_options['filters']['activated']['id'] = 'activated';
  $handler->display->display_options['filters']['activated']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['filters']['activated']['field'] = 'activated';
  $handler->display->display_options['filters']['activated']['relationship'] = 'snid';
  $handler->display->display_options['filters']['activated']['group'] = 1;
  $handler->display->display_options['filters']['activated']['exposed'] = TRUE;
  $handler->display->display_options['filters']['activated']['expose']['operator_id'] = '';
  $handler->display->display_options['filters']['activated']['expose']['label'] = 'Activated';
  $handler->display->display_options['filters']['activated']['expose']['operator'] = 'activated_op';
  $handler->display->display_options['filters']['activated']['expose']['identifier'] = 'activated';
  $handler->display->display_options['filters']['activated']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );

  /* Display: Page */
  $handler = $view->new_display('page', 'Page', 'page');
  $handler->display->display_options['path'] = 'newsletter-subscriptions';
  $handler->display->display_options['menu']['type'] = 'normal';
  $handler->display->display_options['menu']['title'] = 'Newlsetter subscriptions';
  $handler->display->display_options['menu']['weight'] = '0';
  $handler->display->display_options['menu']['context'] = 0;
  $handler->display->display_options['menu']['context_only_inline'] = 0;


How do I call an object in a prepressor only once In drupal8 is there a way to call a function only once in the theme layer. Can I call this function only once and not on other preprocessor hooks or
am I using the wrong hook?

function template_preprocess(&$vars){
    //-- can I call this function only once and not on other preprocessor hooks
    _updateFieldOnNode('field_metatag_title');
}

If you want to call the preprocess hook on nodes only you can use template_preprocess_node().


Behat - Selenium failing I am trying to setup behat tests with Selenium and Chromedriver for my D8 project.

All @api tests work perfectly, but as soon as I add @javascript, it stops working with

Behat\Testwork\Call\Exception\FatalThrowableError: Fatal error: Call to a member function elements() on null in vendor/behat/mink-selenium2-driver/src/Selenium2Driver.php:488

My Behat.yml

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
 extensions:
   Behat\MinkExtension:
     goutte: ~
     javascript_session: 'selenium2'
     browser_name: 'chrome'
     selenium2:
       wd_host: 'http://192.168.56.1:5555/wd/hub'
     base_url: http://mydev.dev
   Drupal\DrupalExtension:
     api_driver: "drupal"
     blackbox: ~
     drush:
       root: "/usr/share/drush"
     drupal:
       drupal_root: "/var/www/mydev"

It is important to note that i am running inside a vagrant box and that I am also running my behat tests from within the vagrant box using:

bin/behat -v -c behat.yml features/my_feature/

My current feature just contains:

@api @javascript
Feature: Create a Quiz
In order to have a quiz on my site, as a Content Editor, I need to be
able to create one

Scenario: Create a quiz
  Given I am logged in as a user with the "administrator" role
  And I go to "node/add/quiz"
  #Then show last response

I have registered a node on my local machine (host) to the selenium hub within the vagrant. I have also validated that http://192.168.56.1:5555/wd/hub/ is working just fine.

Thanks in advance

It turned out to be a bug in the Drupal extension that is fixed here: https://github.com/jhedstrom/drupalextension/pull/379


Custom Page type and variables In my preprocess_page() function, I'm setting variables based on the user that is logged in.

I created a custom page that is used as a Welcome page with the information about the user that I set in the variables in the preprocess_page() function.

The problem I have is that the page is not allowing me to put the print statements to echo out the variable, i.e.

<?php print $FirstName. " ".$LastName; ?>

It doesn't echo out the variable values.

Also, I need later to do something based on the value of a variable. I have tried using an if statement like this:

<?php
  if($designations == 'ABCDE') {
?>

</php
  } else {
?>
              &nbsp;
<?php
   }

but all it does is print out part of the PHP:

if($designations == 'ABCDE') {
?>
} else {
?>

What am I doing wrong here???

Updated (Added preprocess_page function code):

function mix_and_match_preprocess_page(&$vars) {
  $vars['page_color'] = theme_get_setting('mix_and_match_page_bg');
  if(user_is_logged_in()) {
    // Get the user's info and assign the values to variables.
    $vars['ParticipantID'] = 1007945;
    $vars['Username'] = 'JOESMITH';
    $vars['Password'] = 'passwd';
    $vars['FirstName'] = 'Joe';
    $vars['MiddleName'] = '';
    $vars['LastName'] = 'Smith';
    $vars['Suffix'] = '';
    $vars['PreferedEmailAddress'] = 'joe_smith@mysite.com';
  } // if($logged_in)
}

Showing new code and results:
This code:

<?php print $FirstName. " ".$LastName; ?>

produces (When view source):

<?php print $FirstName. " ".$LastName; ??>

this code:

drupal_set_message('I got here');
<?php if($designations == 'ABCDE': ?>

drupal_set_message('I got here');
<?php else: ?>
                  &nbsp;
<?php endif; ?>

produces (When view source):

drupal_set_message('I got here');

<?php if($designations == 'UACIC'): ??>

drupal_set_message('I got here');
<?php else: ??>

<?php endif; ??>

Assuming you put the preprocess code in your theme's template.php, coding this inside a node ought to work  - but in order for it to do so you have to

make sure the Core "PHP Filter" module is enabled and
make sure the node's Input Format is set to "PHP code."

As I noted, this is not the most secure or maintainable way to do things, but it'll let you do what you want without messing about in page or node templates.


What order should configuration import and module updates be run? Since the schema version of modules is stored in the key-value storage, it is unique to each site and is not synced through configuration management.  That makes sense, since updates may need to make adjustments that are not encapsulated in config (such as database updates), but there are other changes that may also be included in config (e.g. adding a new config value).

Are there any risks to running config import and database updates in either order?
What is the preferred order for running those operations?
Do update hooks need to make any special accommodations for config items that may have already been imported?
Are there any other operations that may be required to fully update the production environment?

Updates must be run before configuration is imported

A pending issue against core will ensure that the code and schema versions match before allowing configuration to be imported.

Problems with config import before updates

An update hook relying on a configuration value could end in a different result than if it were run on the pre-import value.
An update could potentially fail if it tried to create configuration entities that already exist.

Concerns for config import after updates

If an update that introduces a new configuration entity is run first, it will create a new configuration item that will have a differing UUID than the one that is in config.  However, once the config is imported the entity should be replaced with the config version.

There could be a potential problem here if replacing the entity would affect associated content.  For example, if an update migrates content from one field to another, on config import the field would be completely replaced and the content potentially lost.  In this instance the deployment process may need to be adjusted to run the updates on the target environment and export the resulting configuration.


drupal_static array losing values I have a module that i created for the sole purpose of integrating it with sitecatalyst.  If you are unaware of what sitecatalyst is, it is an api that helps create reports based on statistics of your website. EX: Pageviews, Visitors, etc.  Im aware there already is a module for omniture sitecatalyst but is not something i can really use.  I need to track many different variables as well as make it track when certain events fire.  EX: User Login, Create New Account, Comment Submitted, Search for something, etc.  Below i have code that fires everytime in preprocess_page, whenever a user logs in successfully, the properties i need set, and the setting of a static array with all the values i need to create the javascript code needed in order to track everything correctly.

My problem:
I used mymodule_user_login and launches as soon as a user logs in successfully.  I set all the properties and then set all those variables inside my static array.  However, the code in the preprocess_page gets launched everytime and therefore would overwrite the static array created when the mymodule_user_login function was called.  Can someone please help me how to figure out how to do this.  Ive been racking my brain.

Thank you in advance for any help

function mymodule_preprocess_page(&$variables) {
    if (arg(0) == 'admin') {
       return;
    }

    $props = retrieve_props();
    foreach ($props as $key => $data){
        mymodule_set_variable($key.'=', $data);
    }

    //CODE TO CREATE JAVASCRIPT CODE GOES HERE FOR SITE CATALYST
}

function mymodule_user_login(&$edit, &$account) {
    $props = retrieve_props();
    foreach ($props as $key => $data){
        mymodule_set_variable($key.'=', $data);
    }
    mymodule_set_variable('s.events=', 'event13');
}

function retrieve_props(){
    $props = array();

    /*Program Properties*/
    if (isset($_COOKIE['tsource']))
        $tsource = $_COOKIE['tsource'];
    else
        $tsource = 'Organic';
    $props['s.campaign'] = $tsource;

    $server = $_SERVER['COMPUTERNAME'];
    $props['s.server'] = $server;

    $header = drupal_get_http_header();
    if(isset($header['status'])){
        $pageType = 'errorPage';
    }
    else{
        $pageType = null;
    }
    $props['s.pageType'] = $pageType;

    $rel = getNodeRelation();
    $deg_level = null;
    $cat = null;
    $sub_cat = null;

    if (isset($rel['level']))
        $deg_level = $rel['level']['val'];

    if (isset($rel['category']))
        $cat = $rel['category']['val'];

    if (isset($rel['subject']))
        $sub_cat = $rel['subject']['val'];

    $props['s.prop1'] = $deg_level;
    $props['s.prop2'] = $cat;
    $props['s.prop3'] = $sub_cat;

    $schoolName = null;
    $program = null;
    $channel = null;
    $pageType = null;

    if(arg(0) == 'node'){
        $currentURL = drupal_get_path_alias($_GET['q']);
        $arrURL = explode('/',$currentURL);
        $channel = $arrURL[0];

        if ($variables['node']->type == 'school') {
            if (count($arrURL) > 1)
                $schoolName = $arrURL[1];
        }
     }
     else if (arg(0) == 'online-degree'){
         $program = arg(1).'-'.arg(4);
         $pagetype = 'program';
     }
     $props['s.prop4'] = $schoolName;
     $props['s.prop5'] = $program;

     $searchTerm = null;
     if (isset($_GET['textsearch']))
         $searchTerm = $_GET['textsearch'];

     $props['s.prop6'] = $searchTerm;

     return $props;
}

function mymodule_set_variable($name = NULL, $value = NULL) {
  $variables = &drupal_static(__FUNCTION__, array(), FALSE);

  if (empty($name)) {
     return $variables;
  }
  else {
     $variables['variables'][$name] = $value;
  }
}

function mymodule_get_variables() {
  return mymodule_set_variable();
}

If you look at the code for the form submission handler used for the user login form (user_login_submit()), you will notice that it executes the following code.

  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);

user_login_finalize() is the function that invokes the hook_user_login() implementations.

  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array('login' => $user->login))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);

Effectively, the user is redirected after hook_user_login() is invoked, which means a new page is being served, and Drupal is bootstrapping once again. The content returned from drupal_static() is then reset.

The solution is saving the value in a session variable, for example using functions like ctools_object_cache_get(), and ctools_object_cache_set(), which are already available if you are using the Views module on your site, as it requires the Chaos tool suite, on Drupal 7.


Migrating to a Field Collection I'm working on a project that requires a CSV of speaking engagements to be migrated to Drupal. With Migrate, I've been able to migrate over basic fields, like name, title, etc.

However, the speaker field is a field collection, which is driving me nuts. While the field collection allows unlimited speakers, the CSV only has one per event. I've tried using the node_insert hook, as described here but to no avail. Is there a better/easier way to migrate a single speaker into the speaker field collection?

There is a Field Collection issue with a Field Collection Migrate destination (in the patch in comment #222). The added field_collection.migrate.inc file contain a bit of documentation on how to use it.

In you case, I guess you have a speaking engagements migration class which load your CSV file and create Speaking engagement nodes. You will then need a speaker migration class to load the same CSV file and create Speaker field collections. This second migration class depends on the first one, so when a Speaker is created, it will be linked to its Speaking engagement.

Something like

class SpeakerMigration extends Migration {

  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->dependencies = array('SpeakingEngagementMigration');
    $this->source = new MigrateSourceCSV('path/to/speaking/engagement.csv', array(), array());
    $this->destination = new MigrateDestinationFieldCollection('field_speakers',array('host_entity_type' => 'node'));
    $this->map = new MigrateSQLMap($this->machineName, array(
      'id' => array(
        'type' => 'char',
        'length' => 40,
        'not null' => TRUE,
        'description' => t("Speaking Engagement's identifier"),
      )), MigrateDestinationFieldCollection::getKeySchema());
    $this->addFieldMapping('host_entity_id', 'id')
      ->sourceMigration('SpeakingEngagementMigration');

    // ... Add field mapping here.
  }
}


webTestCase->drupalPost() or drupal_http_request()? I'm writing a simpletest for a module that posts XML directly to a URL (it's on a closed system so there's no user or auth or anything at this point).

I've manually tested getting the response code by using drupal_http_request() to POST the file, but since I'm now doing the same thing in an actual simpletest, I feel like I should use webTestCase->drupalPost().

The only problem is that drupalPost() seems to expect a save button value. I'm not POSTing via a form with a submit button, so can I still use drupalPost()? Or should I just use drupal_http_request() in my simpletest?

As said in the documentation page for DrupalWebTestCase::drupalPost(), that method supposes to be called for a Drupal page containing a form; if that is not the case, you should use drupal_http_request().

The reason is that the method tries to emulate a click on a submit button, as said in the description for the $submit parameter.

  $submit: Value of the submit button whose click is to be emulated. For example, t('Save'). The processing of the request depends on this value. For example, a form may have one button with the value t('Save') and another button with the value t('Delete'), and execute different code depending on which one is clicked.


Deleted content type shows in the "Add content" menu I had some content types I wanted to delete so I went to Structure >> Content types. I deleted the content types that I didn't want to have anymore, and I cleared all the cache through drush and performance.

I also went to my database and look through to double check if they were deleted, and I found they were deleted correctly.

I have also restarted my MAMP local server.

The problem is that the deleted content types appears on "Add content" but they are not clickable. I don't want them to appear there. why does this happen?

I had the same problem which I just managed to fix - thanks to  Mołot's comment which made me think of menus.  It looks like creating a content type adds an entry to the Navigation menu but deleting it doesn't delete the entry.  I just disabled that menu item and now it's gone from the Add Content page.


Display Views results in a specific order? I have a Views result set that I would like to give a very specific order not just 'ascending, descending' or defaults.

Currently I am saving them in reverse order and sorting by date updated descending, but this is somewhat of a pain.

Any thoughts on how to do this? Existing modules? Thanks!

You can set arbitratry order on Views using the various ordering modules listed here.

Draggable Views is probably the most popular.


Flag: update link to processed via JS I'm using flag module to flags my nodes. Now, in frontpage the list of nodes (html) is get and put in the main DIV via AJAX,  so the flag module has not parsed these nodes. How can I say to flag module to re-get and process all flag link ? I know that I need to insert the call in my AJAX .get() function, but which is the correct flag-JS-function to call ?

Thanks.

You probably should run Drupal.attachBehaviors($('.newcontent')); instead of trying to add this logic manually for each module. But since you asked for flag 3.x it is Drupal.behaviors.flagLink.attach($('.newcontent'));


How to convert image URLs in Drupal node's fields while rendering? I have developed a new CCK module using Plupload where users can drag and upload images using native HTML5 apis. Since, I do not know how to drag images directly inside CKEditor, what I am doing is that after images are uploaded using plupload's jQuery widget, I show an image instead of a filename from where users can drag that image inside a CKEditor. Its a 2-step drag-n-drop process.

Now, when I drag & drop images into a CKEditor using Chrome, CKEditor generates following code

When I do similar action using Firefox/Safari, CKEditor generates following code

Problem is depending on from where I am viewing the node (views, panel etc), images sometimes shows up and sometime not, because they point to location starting with ../../ and not with http://myportal/.

So, how do I make sure that when Drupal is generating node's view, "../../sites/myportal/files/plupload/p15sjle1js11r5289aibk0m1n7q3.jpg" is expanded or converted to "http://myportal/sites/myportal/files/plupload/p15sjkcj2c1o3koe3hsp19761ep14.jpg"

One way I  can do this is using jQuery to find all  tags with a word 'plupload' in their src attribute , and then changing that attribute with full URL. But, it will slow down display a lot. Any other ideas using Drupal module or custom coding?

You can probably accomplish that with a custom filter involving a regular expression using either Flexfilter or Custom filter.


When using Rules to set a value on a taxonomy term reference field, I get choices like "field:0", "field:1", etc. What do these numbers mean? When I add a "Set a data value" action for my taxonomy term reference field, Rules allows me to choose from the following:

field-age
field-age:0
field-age:1
field-age:2
field-age:3

What are these ":0" ":1" etc. fields?

EDIT: These appeared when I changed the "Number of values" for field-age from "1" to "2".  However, since I only changed the number of values to 2, why did 4 things appear?

It's basically letting you have access to a zero-based array for the different instances of a multiple cardinality field (as I think you've already worked out).

It seems the reason there are 4 shown is just a default; a visual cue to let you know there are more than one possible values for that field.

If you have a field with 20 values you'll still only see 0...3 in the Rules data selector, even though you can use 0...19.


How to get count on how many times a term is used on a node I'm about to create a Tag cloud module that shall have a block showing a list of all terms. The most used terms shall be in big text; the terms that not used often shall be in small text, as in the following screenshot.

I want to have a $count variable that holds the count of how many times each term is used.

I think that I can do so:

$database = \Drupal::database();
$terms_count = $database
->query('SELECT COUNT(tid) FROM {taxonomy_index}')
->execute();

foreach($terms_count as $term_count) {
  print $term_count;
}

But it doesn't show anything.

Here's the query you're going for.

SELECT count(*) AS count, tid FROM taxonomy_index GROUP BY tid ORDER BY count DESC LIMIT 100;

You'll need to use AddExpression to get the count in there.

$query = $this->database->select('taxonomy_index', 'ti');
$query->addField('ti', 'tid', 'tid');

$query->addExpression("count(*)", 'count');
$query->groupBy('ti.tid');
$query->orderBy('count', 'DESC');
$query->range(0, 50);

$data = $raw_data = $query->execute()->fetchAll();

Here's how you might convert the data to a render array:

$term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');

$build = [];
foreach ($data as $count_group) {
  $term = $term_storage->load($count_group->tid);
  $label = $term->label();
  $link = $term->toLink();
  $link->setText($this->t($label . ' (' . $count_group->count . ')'));
  $build[] = $link->toRenderable();
}

return $build;


Joining Taxonomies in an Ubercart Views into a single Field Group (D6) I have a view for a taxonomy term filtered by the argument.

A particular product has more than one taxonomy term related to the individual node.

This works for only all nodes that have just one taxonomy term. Unfortunately i have a product that has more than one taxonomy term.

Thus on the page with that particular product I have them grouped by fields. When i do this they're displayed as two different fields. All the products with a singular term and another taxonomy term with two terms.

Is there a way for me to group the node into one field ?

The solution was adding "Term" as a field.

Then grouping terms by the field "Term" and not "All Taxonomy Terms"


How can I get field labels from submission data? I have created a custom webform handler by extending WebformHandlerBase. And I can get the data from the WebformSubmission. However, I can only get the machine name of the field. I would like to get field label. For instance, I get "fname" machine name as the key, but I want to get "First Name" or what ever label is set in the admin for this webform.

Does anyone know how I might get to that information from a webform submission entity?

I assume that you pass $form, and $form_state into your custom handler function. You can always access your webform field "label" via $form variable.

Try kint() or dd() $form['elements'] on specific form and go into depth to find your field, then you can easily get $form['elements']['my_field_name']['#title'] etc.


What does maintenance mode do? What does maintenance mode actually do?  I'm not asking for a high level overview, nor am I asking for a code dump.  I'm asking for a technical, functional definition.  What does maintenance mode actually do?  Does it shut down everything for all users except admin and just show them a static page?
Is there a technical reference (short of the code itself) that covers what maintenance mode actually does?

The main functionality of maintenance mode is that it allows the site to use the theme system without requiring the database.

It does almost exactly what you had guessed, it locks out all users that do not have the 'use site in maintenance mode' permissions or administrator roles.  A site in maintenance mode will use a different template file than the live site, normally maintenance-page.tpl.php.

Maintenance mode also kicks in in other situations:

Site installation
Updates
Any time the database fails


Is adding indexes to a Drupal database safe? I have been searching and reading about this, but I have not seen anything definitive about the topic of adding indexes to Drupal tables (both core and contrib).

My main concern is what happens with any custom indexes when you update core or contrib code and there are schema changes.  What happens in this case?

EDIT:

I think some context may help.  I am primarily concerned with adding indexes to tables to tune site performance (queries showing up in the slow query log, pages with slow views, etc).  This may involve adding an index to a table in someone else's module.  For example

I install module foo
Module foo creates table foo
I add an index to table foo
Module foo has an update that changes the schema

What happens?

Yes, it could result in problems.

If a module wants to do something with the column on which you have added an index, it will remove it's own indexes and then do whatever operation it intends to do.

What exactly will happen will depend on your database type and the actually executed operation. For example, a rename of the column will work fine with MySQL, but will fail on PostgreSQL. But if it tries to delete that column (maybe after migrating data to a different table/colun), it will fail.

The chances that this will happen are relatively low, at least for minor updates (does depend on the actual module however. I usually don't add any changes which could break something to minor releases), but it is possible.

My suggestion would be that you try to work together with the module maintainers. If the problematic query/ies are from the module itself, then the maintainers will probably happily add the indexes, if you provide a patch. Provide DESCRIBE output of the problematic query/ies before and after adding the index. Also provide a patch that updates the schema (include an update function to set it for existing installations).

Someone who is actively working on performance related things and does the above really well is catch, here is an example: http://drupal.org/node/983950


jsmin+ causes high server load in drupal 6 I have the JavaScript aggregator module on my site. Whenever I check the jsmin+ checkbox (so it uses jsmin+ instead on jsmin), the server becomes really slow. I have to use jsmin+, instead of jsmin, because jsmin doesn't group JavaScript files correctly, and I get JavaScript errors (Ckeditor and Vertical Tab are breaking).

Drupal 6.20
JavaScript aggregator 1.6
jsmin+ 1.4

Give AdvAgg a try. It works around the limitations of jsmin+


How do I get inline tags to wrap nicely? Inline tags are presented as a series of
s, with no whitespace in the HTML between them. These elements are styled display:inline, the result of which is an unbreakable string. When you have enough tags this breaks layout. What you want is tags to word-wrap around, but they don't.

The only way I can see to achieve this is by hacking core to insert a space after the field-item items'
s (or after the content before the closing
.

Is there another way? Perhaps a way for a theme to override the formatter function?

Try using display: inline-block instead. It gives you the functionality of an inline element, but you can apply margins and padding to it just like a block-level element.


Can a disabled module pose a security risk? Is it possible for a module that is installed but not enabled to pose a security risk?

Corollary question: Is it a recommended practice to update disabled modules when security updates become available?

I say yes since the vulnerable code is still sitting right there in the web directory which can (will) be scanned by potential attackers. Monitoring disabled modules is certainly part of our update routine.

I didn't find a whole lot of discussion on this in regards to Drupal in particular, likely because it isn't really a Drupal-related issue (see note below). Greg Knaddison (@greggles on Drupal.org) noted on a thread a few years back that:

  Sometimes the vulnerabilities exist regardless of whether or not the
  module is enabled, so I think it's better to warn on all modules.

Source: Issue #942960: Don't warn about security updates for disabled modules

As always, best to err on the side of caution.

Note: I think this is more a server admin related question, but I hesitate to flag it as not relevant since IMHO people who aren't server admins shouldn't really be expected to know that.


How to pass variable to a views template? I have this in my template.php:

function mytheme_preprocess_views_view(&$vars) {
$vars['test'] = 'Filtertest';
}

And this in my views-view-responsive-grid--taxonomy-term.tpl.php:

<?php print $test; ?>

... this does not work though. The template is called and works but my $test variable does not get printed.

What am I missing here? Any help is greatly appreciated.

Replace this, with your function

public static function mytheme_preprocess_views_view(&$vars) {
  $vars['test'] = 'Filtertest';
  return $vars['test'] ;
}

Then use this short code on your twig view:

{{ test }}

or if wanna use it in something.php in your views:

dump(test )


Custom Entity with a uid property We seem to be experiencing a very unexpected problem.

We have created a custom entity called feature and it has a uid property. The schema is as follows:

$schema['feature'] = array(
  'fields' => array(
    'fid' => array(
      'description' => 'feature id',
      'type' => 'serial',
      'not null' => TRUE,
    ),
    'bundle' => array(
      'description' => 'bundle name',
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
    ),
    'nid' => array(
      'description' => 'Node ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'tid' => array(
      'description' => 'Taxonomy Term ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'uid' => array(
      'description' => 'User ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'created' => array(
      'description' => 'created timestamp',
      'type' => 'int',
      'not null' => TRUE,
    )
  ),
  'unique keys' => array(
    'primary key' => array('fid'),
    'nid-tid-uid' => array('nid', 'tid'),
  )
);

An entity is then picked up with

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'feature')
  ->entityCondition('bundle', 'disabled')
  ->propertyCondition('tid', $tid)
  ->propertyCondition('nid', $nid)
  ->addMetaData('account', user_load(1));
$result = $query->execute();

if (isset($result['feature'])) {
  $features = entity_load('feature', array(reset($result['feature'])->fid));
  $feature =  reset($features); // $feature here as the wrong uid
}

However, no matter what permutation I try, the uid is always set to 1.

The database has the correct information - so the data is being stored correctly.

The entity has views integration and pulling the data in through views works correctly as well.

Outputting the $feature always gives a uid = 1.

I even have traced through the EntityAPIController with little luck.

I tried loading an unrelated entity (Field Collection Item). This entity does not have a uid field. However, after entity_load it seems that a uid property is set.

Does this mean that having a uid property on an entity is just not possible? There does not seem to be any documentation to suggest that this is the case though.

I know that I can just rename it to aid or something else but am curious as to the cause here.

Thanks...

I left it overnight, and by the following day, the issue was gone.... :-/


Add fields to feeds importer I want to import the fields "alt", "title" and the custom field "copyright_notice" via feeds using the following code:

function budg_eu_projects_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {

    $info = field_info_field($name);

    if ($info['type'] == 'file') {
      $targets[$name . ':alt'] = array(
        'name' => t('@label: Alt', array('@label' => $instance['label'])),
        'callback' => 'budg_eu_projects_set_target',
        'description' => t('The alt tag of the @label field.', array('@label' => $instance['label'])),
        'real_target' => $name,
      );
      $targets[$name . ':title'] = array(
        'name' => t('@label: Title', array('@label' => $instance['label'])),
        'callback' => 'budg_eu_projects_set_target',
        'description' => t('The title of the @label field.', array('@label' => $instance['label'])),
        'real_target' => $name,
      );
      $targets[$name . ':copyright_notice'] = array(
        'name' => t('@label: Copyright Notice', array('@label' => $instance['label'])),
        'callback' => 'budg_eu_projects_set_target',
        'description' => t('The title of the @label field.', array('@label' => $instance['label'])),
        'real_target' => $name,
      );
    }
  }

  return $targets;
}

As a callback function I use

/**
 * Callback for mapping file fields.
 */
function budg_eu_projects_set_target(FeedsSource $source, $entity, $target, array $values) {

  list($field_name, $sub_field) = explode(':', $target . ':uri');
  $info = field_info_field($field_name);

  // Populate entity.
  $field = isset($entity->$field_name) ? $entity->$field_name : array(LANGUAGE_NONE => array());
  $delta = 0;

  foreach ($values as $v) {
    if ($info['cardinality'] == $delta) {
      break;
    }

    if (!isset($field[LANGUAGE_NONE][$delta])) {
      $field[LANGUAGE_NONE][$delta] = array();
    }

    $field[LANGUAGE_NONE][$delta][$sub_field] = $v;

    $delta++;
  }

  $entity->$field_name = $field;
}

I managed to add the fields as a mapping target but the data of the fields are not saved. What is missing?

Thanks
Rainer

AFAICT the code you've posted will populate the entity with the values from the CSV file - but nothing's set up to persist those values. The Field API itself can persist values it knows about. Look at file_field_schema()

/**
 * Implements hook_field_schema().
 */
function file_field_schema($field) {
  return array(
    'columns' => array(
      'fid' => array(
        'description' => 'The {file_managed}.fid being referenced in this field.',
        ...
      ),
      'display' => array(
        'description' => 'Flag to control whether this file should be displayed when viewing content.',
        ...
      ),
      'description' => array(
        'description' => 'A description of the file.',
        ...
      ),
    ),
    ...
  );
}

Through this, the Field API knows to store the file ID, whether or not to show the file when viewing content, and a description of the file. Image field is very close to file field, and shares mostly the same code. And looking at image_field_schema() you can see where the title and alt fields come from.

/**
 * Implements hook_field_schema().
 */
function image_field_schema($field) {
  return array(
    'columns' => array(
      'fid' => array(
        'description' => 'The {file_managed}.fid being referenced in this field.',
        ...
      ),
      'alt' => array(
        'description' => "Alternative image text, for the image's 'alt' attribute.",
        ...
      ),
      'title' => array(
        'description' => "Image title text, for the image's 'title' attribute.",
        ...
      ),
      'width' => array(
        'description' => 'The width of the image in pixels.',
        ...
      ),
      'height' => array(
        'description' => 'The height of the image in pixels.',
        ...
      ),
    ),
    ...
  );
}

I think the right way forwards depends on your data model. In the example below there are two nodes with file fields, each referring to the same file. Note that they can have different alt and title fields even though they're referring to the same file.

Node 1:
  file_field:
    fid: 1
    alt: A beautiful beach
    title: Wish you were here?

Node 2:
  file_field:
    fid: 1
    alt: Great swimming
    title: Fun for all the family

The alternative I suggested in a comment was to add the fields to the entity itself.

File 1:
  alt: A beautiful beach
  title: Wish you were here?

Node 1:
  file_field:
    fid: 1

Node 2:
  file_field:
    fid: 1

This means the alt and title will always be the same for a given file. It's obviously for you to decide which model meets your needs more appropriately. If you want to store the data per-field (the first example) you have two choices:

Use an existing field and alter its schema with hook_schema_alter() - a bit painful as there's no hook_field_schema_alter(). Only do this if conceptually every instance of this field should have that extra data.
(I'd prefer this personally) Create a new field that stores the extra columns you're interested in. Image field is the perfect place to look for inspiration, because its functionality's based on file field and it has extra columns.

If you want to store the data per file entity, then you can use fieldable files and I'm fairly sure you should be able to set everything up through the feeds UI. (IE no need for the feeds code above.)


Is it possible to restore a deleted node? While revisions are kept and it is easy to get back to a previous revision of a node, I was wondering if it is possible to restore a node that has really been deleted by a user?

If you have a database backup (which you should ;) you can restore an old copy of the site and retrieve it that way.

Drupal does give users quite a clear warning that deleting a node is final, and there is a confirmation dialog.


Run "git" on remote server with drush alias I would like to launch git commands, on my production server, from my pc.
The document root of the production application is a clone of the git repository.

On prod, on sites/all/drush/drushrc.php I've add this line:

<?php

// Drush aliases
$options['shell-aliases']['git-status'] = '!git status';

If I login on production and I execute "git status", everything works.

If I try to execute, from my pc "drush @mysite.prod git-status" I obtain:

fatal: Not a git repository (or any of the parent directories): .git
Command git status failed.

Note that if I try to run "drush @mysite.local git-status", works (and my local copy is like the production copy, the document root is the clone of git repository).

What's wrong?
Document root directory declared on my alias is right (other commons drush commands work) and is a checkout of git repository.

Thanks.

This works just fine for me on both the 6.x and master branches of Drush, and on the 6.2.0 release.  So, your first step would be to try with the latest versions, and see if it works.  If that doesn't fix your problem, try running your command again using the -v flag to get more verbose output.  You will see something like this:

$ drush -v @mysite.prod git-status
Loaded alias @server.xxxxxxxxxxx from file                              [notice]
/home/ga/local/config/drush-aliases/server.aliases.drushrc.php
Loaded alias @mysite.prod from file                                     [notice]
/home/ga/local/config/drush-aliases/mysite.aliases.drushrc.php
Include /home/ga/local/drupal/drush_extensions                          [notice]
Include /home/ga/.drush                                                 [notice]
Calling proc_open(ssh -o PasswordAuthentication=no webuser@myserver.com 'cd /srv/www/myserver.com/htdocs && git status');
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../xxxxx.txt
nothing added to commit but untracked files present (use "git add" to track)
Command dispatch complete                                               [notice]

Try running the command inside of "proc_open(...)" from the shell, and see if it behaves the same way.  Adjust the ssh options until it works right.  Then, set $options['ssh-options'] to adjust.

NOTE:

If you want to do something like this without defining a shell alias, the following should also work:

drush @mysite.prod ssh git status


how to display unique records between two table by using db_select query in drupal The following two tables contained reg_no field. how to get unique reg_no records of the student_master table

for example

student_master table

reg_no

MA1001

MA1002

semester_appear table

reg_no

MA1001

but I want to get output only MA1002. how to get the output by using following code

Table : **Student Master**

$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$query->orderBy('reg_no','ASC') ;
$results = $query->execute();

Table : semester_appear

$sem_query = db_select('semester_appear');
$sem_query->fields('semester_appear', array('reg_no','batch_year','month','year','subject_code','sub_serial_no','semester_appear'));
$sem_query->distinct();
$sem_query->condition('year',$year,'=') AND $sem_query->condition('reg_no',$reg1,'=') AND $sem_query->condition('semester_appear',$semester,'=') AND $sem_query->condition('month',$month,'=') AND $sem_query->condition('marks_updated',$no,'=') AND $sem_query->condition('batch_year',$batch,'=') ;
$subject_results = $sem_query->execute();

I have found that the easiest way to do complex MySQL queries (including JOIN, which is what you're after here) is to use db_query():
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7

And the MySQL docs explain the JOIN syntax quite nicely:
http://dev.mysql.com/doc/refman/5.0/en/join.html


.htaccess www. redirect in Dev Desktop Possible stupid question but worth a punt...

My local OS X setup uses Acquia Dev Desktop. I recently changed a remote site's .htaccess file to redirect all no www. URLs to their www. equivalents (done my uncommenting the relevant 2 lines already in Drupal 7 core .htaccess). Pulling this change down to my local setup now means that my local dev version can no longer be navigated to.

Running cron and clearing all caches via Drush doesn't seem to help in any way.

Do I have to use a different .htaccess file for local and remote setups or am I missing something here?

Yes, you need to use a separate .htaccess file for your local version of the site.

It often makes sense to sync just the sites/all and/or sites/default folders (minus settings.php of course) of a Drupal site, so you can avoid this sort of problem without even having to think about it; unless you're hacking at core of course, which isn't recommended anyway :)


How can I load a theme template to render $submitted I'm trying to replace the output of $submitted in my nodes. I have found how to replace the value which is fine. The problem I'm facing is how to load a template file properly.

function pod_preprocess_node(&$vars) {
  $vars['submitted'] =  t('!datetime ', array(
    '!datetime' => include_once(__DIR__.'/system/submitted.tpl.php')
  ));
}

As you can see above, I've just included a template file and in there I can use $vars but this is clearly sub optimal. What I'd like to do is just load a template file from my theme which has some sensibly named variables in.

I've looked at hook_theme() which now allows me to call theme('pod_submitted', $vars) but I don't know how to make pod_submitted() include the right file etc.

I assume that somewhere I need to do the following

$vars['theme_hook_suggestions'][] = 'system__submitted';

But I'm not sure how my template function relates to/knows which template to call.

Well, what you're looking for is hook_theme. With hook_theme you can declare new theme implementations, which can be either functions or templates. I'll stick with templates for this answer. Just define it in YOURTHEME's template.php file:

function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'YTsubmitted' => array(
      'template' => 'YTsubmitted',
      'variables' => array('whom' => NULL, 'when' => NULL),
    ),
  )
};

I'm calling the theme hook YTsubmitted and the template file  YTsubmitted. Those names don't need to be the same, but I'm prefixing to avoid collisions. Now, whenever you call theme('YTsubmitted'), Drupal will look for YTsubmitted.tpl.php in your theme and use it for rendering. You can pass variables to it when calling, just like theme('YTsubmitted', array('whom' => 'Jake the dog')). Variables will default to values set when defining the theme hook in hook_theme (NULL in our example). But you can also preprocess variables:

function YOURTHEME_preprocess_ytsubmitted(&$vars, $hook) {
  $vars['extra'] = 'Mathematical!';
}

And now you can use it in your template file (YTsubmitted.tpl.php):

Submitted by <?php print $whom ?> right after <?php print $when ?>. <?php print $extra ?>!

That's precisely how Drupal sets several of the templates and its variables. For instance, node.tpl.php will print the $submitted variable, which can be redefined in your template.php file:

function YOURTHEME_preprocess_node(&$vars, $hook) {
  $vars['submitted'] = theme('YTsubmitted', array('whom' => 'Finn the human'));
}

AAAaaand you're done.


The user-profile.tpl.php file won´t be recognized in my Drupal 7 installation I´ve created a file user-profile.tpl.php in a Drupal 7 installation. I´ve updated the site from Drupal 6.
I have old core profile fields and I´ve installed the new profile2 module.

I´ve inserted that user-profile file into my theme folder and flushed cache.
I want the profile to show all the core profile fields and the new profile 2 fields.

The thing is that it won´t show any field at all. It just shows the user picture.

After a lot of trying and error, I´ve tried deleting all the content inside user-profile.tpl.php file, and adding into it just "hello world". It won´t be printed out. And the profile picture is still there.

So, how do I get the file to be recognized? Should I set something at my template.tpl.php file?

Thanks for your help!!

Rosamunda

You could try adding your content in the user profile template preprocess function instead.

e.g, in template.php:

/**
 * Implements hook_preprocess_user_profile
 */
function THEMENAME_preprocess_user_profile(&$variables) {
  // Fetch relevant user account
  $account = $variables['elements']['#account'];
  // Add content to user profile render array
  $variables['user_profile'][] = array(
    '#type' => 'markup',
    '#markup' => 'Hello world'
  );
}

After adding a new preprocess function, clear theme registry cache, e.g at Admin > Performance > Clear all caches


Drupal commerce display VAT exclusive unit price & subtotal for line item in cart and order I has a VAT tax for my products. It's a B2B site so we only show Tax exclusive price to customers. Even in cart and order. The VAT only show in the cart & order bottom just as the Drupal commerce original one.

My problem is I can not find a way to show the VAT exclusive price in the cart views. There is no option for that. The line item unit price field 'formatted amount' is showing VAT included price. 'formatted amount with components' is showing a price table like this:

Subtotal    $16.50 AUD
GST $1.65 AUD
Unit price  $18.15 AUD

That's not what I want. How can I only show the the price exclude the VAT tax?

Finally I find this module: Commerce price by components

This is perfect for my requirement.

  Extension to Drupal commerce that provides a price formatter to enable/disable price components such as discounts or taxes when
  displaying prices. This gives the admin absolute control over which
  components should be displayed and which shouldn't. It also provides
  two Views handlers to display/hide price components in cart totals and
  order totals. Additionally it has basic rules support that gives to
  the commerce administrators the ability to do conditions using price
  components such as discounts or taxes and react accordingly.

  Example use case

  If you want to customize your cart or checkout views, you may want to
  display prices with taxes and without discounts (or viceversa) in your
  line items but the total amount should be displayed. Then you enable
  this module and choose at formatter level (both display fields and
  views) which components you want to hide or display.


How can translations 'inherit' CCK values of the node in the default language I've got a CCK content type called 'projects' with about 10 fields, including an ImageField that allows for multiple images.

There are two languages defined for the site: English (the default), and Chinese.

The projects have been created in English by the client.

Now, they want to add translations for all the projects into Chinese. So, I've:

enabled content translation
created a new 'project' node (e.g., node/234) and populated just the title and body fields (all the other values are the same between both nodes)
gone back to the original English node and added node/234 as the translation

The problem of course is that when I go into the Chinese translation for the page, the field values for the original node aren't there, so at the moment, the site editors would have to re-add the values all over again.

Is there a module or Drupal setting for addressing this issue, or would it be better to, say, create a module to run a query that populates the fields in Chinese translations with the values from its sister English node? I'm not adverse to writing such a module, but if there's a solution already, of course that would be better.

I've found a solution that works for my needs. There's probably a better way:

Modules used: Views Bulk Operations, Node Clone, Views Bonus Pack, Language Assign, Feeds

Assumptions: you have a CSV file or MySQL database with translations of your pages in another language. It's not necessarily to have this - it just makes things faster.

Install the Node Clone module and Views Bulk Operations (VBO) module. Add this patch to expose the Clone feature to VBO.
Clone the nodes you need in VBO. This will append 'Clone of' to the title of each cloned node.
Set the language of the new nodes, again using VBO and Language Assign.
Install the Views Bonus Pack to get CSV export functionality. Create a View that uses the CSV Feed style, and add the title field and any other fields you need translated. Add a filter that displays only fields where the title starts with 'Clone'.
Export the nodes using the View created in the previous step.
Now, you can either manually add your translations to the CSV file by replacing them with the relevant translations, or you can use your new CSV as a reference file to add the right node ids to your original CSV with the translations. Basically, at the end of it, you have a file like this:

-->

| Node ID | Original Title | Chinese Title  | Body         | Some other field |
| 234     | Hey You        | ????           | Blah, blah   | Blah ...         |

Now, you can install the Feeds module, override the default CSV import, changing only the mapping and content type to use. Map the field 'Node ID' to the node ID (or the original title to the node title), and change the Update options to 'Update node.'
Go to http://yoursite.com/import. Do your import. I did, and now I'm happier.


How to use Open Atrium 2 for document managment In the past I have used Open Atrium 1 as an intranet site making use of the document management system.

I can't work out how to do something similar in OA2. From the documentation I have found:

  News section - for document management, wikis, or articles

So I have created a News section. It looks like I can create a Document Page and add attachments to it. Do I no longer have the options to create files and folders. Just document pages and attachments?

The 2.30 version of Open Atrium supports folders out-of-the-box through the oa_folders module.

On earlier versions I have used a customized news section type and calling it Folders or Filesharing. With a clear workflow established with the people working on it, you can then have each document page being a folder, where all space members can add or remove further documents. It was obviously a limited solution, but made the purpose. Now we have a better OA world :)


View does not display results when added as a block to a region UPDATE 2: I'm not sure if this is relevant but when click 'demonstrate block regions' the only region it displays is content

UPDATE: I have just discovered that the block displays just fine when added to the content region. However when added to any other region such as the left sidebar or any custom region it does not display at all

I currently have a view that displays the results just fine in the view preview. It also works when I create a basic page and embed it like so:

<?php print views_embed_view('mobile_slide_menu','block');?>

However when I add this view to a region it displays no results. However I know that it's trying to display something because I see this in my source.

<div class="region region-slide-menu">

</div>

My info file that is defining the regions looks like this

;regions
regions[main_menu] = Main Menu
regions[header] = Header
regions[content] = Content
regions[help] = Help
regions[slide_menu] = Slide Menu
regions[footer] = Footer
regions[sidebar_first] = Left Sidebar
regions[sidebar_second] = Right Sidebar

and I'm calling the region like this

<?php print render($page['slide_menu']);?>

I'm using Drupal 7 and this is a custom theme I've built. I've cleared the cache multiple times.

Verify which of the blocks you have enabled for the theme you're using. To do so, navigate to admin/structure/block. Somewhere your "block created with views" should be listed there. If it is within "Disabled" (near the bottom), then you need to indicate there in which region (like sidebar 1st, sidebar 2nd  or something similar?) you want that block to be displayed.

From what you seem to experience, it seems that hardly any block is enabled (most seem to be disabled).

PS: just to be sure, try to clear the cache ... it doesn't hurt, but sometimes that is what is required ...


How to create block with unapproved comments for dashboard? I have a question similar to this one: I'd like to add a block with an overview of unapproved comments on nodes to my dashboard and simply have the possibility to publish them (via a link or button).

How can I do that?

If you need a simple solution, such as a link for approving a comment (no bulk operations), you can achieve this simply with Views.

Add a new field to your view of comments and select 'Comment: Approve link'. This will provide a link for approving the comment.


Global redirect edit link I am using the global redirect module. This makes /node/1 goes to my path auto /node/clean-title. If I goto /node/clean-title/edit I get a 404 error. If I go to /node/1/edit. How can I get it so that /node/clean-title/edit works. I would like this to happen on all my nodes automatically.

You want the Subpath Alias module.

  For example, if node/1 is aliased to
  content/alias, this module rewrites
  the link to the node edit page
  node/1/edit to use the aliased URL
  content/alias/edit instead.


Why are there so many attempts by an anonymous user to access /wp-login.php? I looked at /admin/reports/dblog today. There were five request in two minutes by an anonymous user to view /wp-login.php. These requests have been happening for an hour at least and continue 2-3 times per minute.

What are the possible explanations for this strange behavior?
What can/should I do about it, if anything?

As kiamlaluno said:

  It's just bots scanning for exploits. You don't need to do anything,
  except serving a faster 404 response for those pages, as described in
  drupal.stackexchange.com/a/152732/199.


How to reverse order of pulldown Views Exposed Filter showing taxonomy terms reference field In Views 3 D7, I have a view with an exposed filter pulldown that is based on a taxonomy vocabulary called Versions. The filter pulldown shows the versions in the order of the vocabulary (so 1.0, 2.0, 3.0) and I need it to show them in the reverse order (3.0, 2.0, 1.0).

I have tried using Better Exposed Filters to render the filter, but I haven't seen any option for sorting order. I also tried using the default Drupal filter and again no sorting order.

I tried using the Entity Reference solution in this SE post, but the problem is that I cannot then use autocomplete widget to create new Versions in the node/add form, so I'm locked (I think) into using term reference. Searched around SE and google for quite some time but no solution yet. Any help would be appreciated!

You should give Entity Reference a go. You don't need to use the autocomplete widget. The standard dropdown list is sufficent. Just create a entitiy reference, type "taxonomy term", select your vocabulary, set to sort by "A property of the base table of the entity" and select "name" and "descending". This should work...

If you need to add new terms on node creation, you could try Entity Connect module. The module will allow you to dynamically create and edit some entity types (e.g. taxonomy terms) which should be referenced into an Entity reference field.


Show text in a page as popup I have some text in my page. and a read more link. When i click on the link, it should open the text in a pop up window. Is there any module to do this? i need to just open the text in pop up not some URL /Html Page.

Check out the Popup module, which may be useful.


Commerce invoice checkout I have enabled the Pay pal module as a checkout option but I need to add a new option for the customer to request an invoice. I realize I need to modify some rules but it seems that the first item I need is a Payment method which the customer can choose that will fire off the Billy invoice. I have looked everywhere but cannot seem to find a suitable method. Should I use the Exmaple paymnet method and try to modify this?

Cheers
/bo

You can use Commerce Custom Offline Payments to handle this.


Pass argument to custom access callback Is there a way to specify an argument to pass to a custom access callback, specifically an argument that isn't part of the path? Like in Drupal 7 you could do this:

function mymodule_menu() {
  $items['abc/$val'] = array(
    'page callback' => 'mymodule_abc_view',
    'access callback' => 'mymodule_abcdef_access',
    'access arguments' => array(1, 'test1'),
  );
  $items['def/$val'] = array(
    'page callback' => 'mymodule_def_view',
    'access callback' => 'mymodule_abcdef_access',
    'access arguments' => array(1, 'test2'),
  );
  return $items;
}

function mymodule_abc_access($val, $type) {
  return ($val['some_prop'] == $type);
}

So in Drupal 8 I would have this in mymodule.routing.yml:

mymodule.abc:
  path: 'abc/{val}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::abc'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\MyModuleController::abcDefAccess'

mymodule.def:
  path: 'def/{val}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::def'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\MyModuleController::abcDefAccess'

And in MyModuleController:

public function abcDefAccess($val, $type) {
  return AccessResult::allowedIf($val->someProp == $type);
}

But is there any way to pass 'test1' or 'test2' as $type? Otherwise I guess I would just have to make a separate access function for each type.

Your route:

regportal_user.orders:
  path: '/user/{user}/orders'
  defaults:
    _entity_view: 'user.orders'
    _title: 'Управление заказами'
  requirements:
    _custom_access: '\Drupal\regportal_user\Controller\RegportalUserController::accessOwnOrders'

Your controller:

  /**
   * Checks access for a regportal_user.orders route.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function accessOwnOrders(AccountInterface $account, $user) {
    if ($account->id() == $user) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }


Can the overlay be used as a popup? In Drupal 6 there was the Modal Frame API which made it to Drupal 7 core. However, I'm not sure how leverage the Overlay independent of being an administration screen. Is there any information about this?

Well, actually yes - overlay might be used too if needed. I have just done a quick write-up on this: http://zgadzaj.com/how-to-open-standard-content-pages-in-drupal-7s-administrative-overlay


How to share a menu across more website I've got a main website where it's possible to create and change menu items and I need to share this menu with other websites and programmatically(once per week or once per day) the other websites will import and override the menu.

This is very useful when a company has got more websites and wants to use the same footer menu for all its websites.

Do I need to use just Feeds and Rules to achieve it?
Is it possible to achieve it without adding the main website db menu in settings.php in all the other websites?

Thanks in advance

I think the idea of using a feed is an attractive one. I don't think there's any way to push a menu definition out as a feed using existing modules, though.

I'd write a very simple module to provide a single callback that would fetch the menu definition and theme it as xml or json (easier). That could then be fetched at intervals by your other sites.


Count Unique Visits to the Drupal Site Is there any way I can count unique visits to my Drupal Site. I have a customized reporting module for the Drupal within which I want to put the unique visits to the site based on date.

I am using this query:-

SELECT
  n.title, n.nid, a.timestamp AS visited,
  COUNT(*) AS times
FROM
  {node_view_count} a, {node} n where a.nid = n.nid AND a.uid = :uid AND n.nid <> 2120
GROUP BY
  n.title
ORDER BY
  times desc,
array(':uid'=>$_GET['uid'])) -> fetchAll();

Do you think there is any way?

Thanks.

Try the Visitors module to either use it or help you with your code. It provides many features concerning visitors info and among them is the "unique visitor" feature you are interested in. A similar approach would be also the Counter module.


How to create a different page.tpl.php for different page, if pathauto is active? I am new in drupal 7. I have created a page about us. My url is look like:

http://domain_name/content/about-us

Now I want a different page.tpl.php for this particular page.

Please help how to do this?

Thanks

Prabeen

It is all outlined on the Drupal 7 Template (Theme Hook) Suggestions page.
eg. page--node--1.tpl.php


Prevent a date from happening in the past I have a CCK field that is a date. I want to prevent people entering a date that has happend in the past. I know you can set Years back and forward and I have set this to -0:+2 but this just limits the calendar. Any ideas what I can do?

Drupal's Form API allows you to add your own validation functions to a form. There is an example for a date field validation function in this forum topic. Documentation is here.


When I upload an image in drupal 8 the imagestyles are not shown for the first time My settings are,

allow_insecure_derivatives: true
suppress_itok_output: false

Editing the itok token for the image src works at the browser level.

Does anyone know what causes the issue and a fix for it?

Notes :

When I hit CTRL+SHIFT+R in the browser the imagestyle images reappear. So the issues seems to be image is not present for the first time and browser is caching it.
The actual image can be accessed even for the first time without any issues. The issue is only with the image style images.
When I look at the actual image in the files folder, I see that there is an additional image with _0 attached to it. So looks like when the image is uploaded for the first time, it is assuming there is a duplicate and creating a new image. But still not sure why it would cause this issue.

We had similar issue in our project might be same please check this link.

https://www.drupal.org/node/2195311


How to create relationships between Taxonomy vocabularies? I'm trying to build a site with similar content conventions to Craigslist. The problem is, I don't really know a good way to create multiple vocabulary relationships in drupal. Here's the end result I need:

Vocabs:
Locations
Categories (contains 'Goods' and 'Services')
Status

Content Type:
Item

  Relationships:

  User has many Items
  User has one Location
  Location has many Users
  Location has all Categories
  Item has many Categories
  Item has one Location

The end result is having all Locations be easy to navigate, with Items being appropriately displayed, in multiple Categories, but restricted to Locations. Users should also be redirected to their respective locations based on their assigned Location and should be able to create Items without having to manually stipulate the Location they are already in.

Does that make sense? Can this be done easily in Drupal?

This can all be done with Drupal's built in taxonomy module and the User Terms module.

Create a node type for Items.
Any Item a user creates is automatically tied to them by them being the author.
Create a taxonomy for Locations and assign it to Items and Users.
Create a taxonomy for Categories, assign it to Items, make it multi selectable.

You can then use Views to create all the different listings pages and blocks.


How to get 'base theme' information about a theme? In an admin settings form in a custom module, I need to determine what base themes a specific theme uses (the default theme, not the current theme). If I know the child theme's name, how do I obtain the names of the 'base themes' that child theme uses (if any)?

You can get the details of a theme by using ThemeHandler::listInfo().

$child_theme = 'bartik';

$base_theme = \Drupal::service('theme_handler')->listInfo()[$child_theme]->base_theme;

$base_themes = \Drupal::service('theme_handler')->listInfo()[$child_theme]->base_themes;


Dynamic Block not showing My block is not showing in the blocks menu for some reason and im sure everything is correct on it, am I missing something on it?

.info file

; $Id: loans_zillow.info,v 1.0.0.0 2011/02/09 10:11:15 Jeremy Exp $
name = "Custom Zllow Module"
version = "1.0 Beta"
description = "A custom module from zillow's api"
core = "7.x"
package = "Custom Modules"

.module file

   function zillow_block_info(){
        $blocks['zillow_block'] = array(
            'info' => t('Zillow Block'),
        );
        return $blocks;
    }

    function zillow_block_view($delta = ''){
        $block = array();
        switch ($delta){
            case 'zillow_block';
            $block['subject'] = t('Zillow Block');
            $block['content'] = zillow_content();
            break;
        }
        return $block;
    }

    function zillow_content(){
        return'

this is a test

        ';
    }

Your code works fine for me so I'd check the following:

Make sure the module's installed and enabled.
Make sure the module is definitely named zillow (the module file should be called zillow.module, info file zillow.info, etc).
Make sure you've cleared Drupal's caches.

I realise these might be obvious solutions but as I say the code works for me so I can only guess your hooks are not being called for one of the reasons above.


How can I export my translation changes? I am using Core Module Locale in Drupal 7. What is the easiest way to export just my language changes? How do I find out which strings have been modified?

With locale module, you have an export tab here : admin/config/regional/translate/export. Or through the menu : Configuration > Regional and language > Export.

On a fresh installation, active the locale module and go to the import tab : admin/config/regional/translate/import. Or through the menu : Configuration > Regional and language > Import.


How can I e-mail the content of a view to myself with Rules? I'm using Drupal 7, Views 3.5, and Rules 2.2.  I have a view that provides a page accessible only to admin users on my site, and once a week I would like to e-mail the content of that page to myself.

I know how to use Rules Scheduler to set this action up to occur weekly.  What I don't know is how to get the page provided by the view as a value that can be input into the body of the e-mail sent via Rules.

If it was a node, I could use Fetch entity to pull it in by ID, but since it's provided by a view, there is no such ID (that I know of) to speak of...

You can use php code in the body of emails sent using Rules, so ultimately anything can be included. The easiest method, however, would be to use the Insert View module.