Populate a file field on edit form I need to populate the file field with a value from the database (when editing a database row).

This is the code for the file field.

$form['file'] = array(
'#type' => 'file',
'#title' => t('Image'),
'#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
);

The variable $icon contains the value (e.g. icon.png).

In Drupal 7 I made this work with:

  '#type'         => 'managed_file',
  '#description'  => t('Icon file may be a jpg, bmp, gif or png format.'),
  '#default_value' => $default_icon,

How can I do this in Drupal 6?

I ended up using this

if ($form_state['storage']['file'] != '0') {
  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_is_image' => array(),
  ));

  // If the file passed validation:
  if (isset($file->filename)) {
    // Move the file, into the Drupal file system
    if (file_move($file, $file->filename)) {
      // Update the new file location in the database.
      drupal_write_record('files', $file, 'fid');
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }

  $file = $form_state['storage']['file'];
  // We are done with the file, remove it from storage.
  unset($form_state['storage']['file']);
  // Make the storage of the file permanent
  file_set_status($file, FILE_STATUS_PERMANENT);
}

$fid = $file->fid;
$icon = $file->filename;

if (!isset($fid)) {
  $fid = $form['fid']['#value'];
}

if (!isset($icon)) {
  $icon = $form['icon']['#value'];
}

$id = $form['id']['#value'];
$url = $form['url']['#value'];
$title = $form['title']['#value'];


Using an admin account as the sender for an action rule instead of site:current-user I am using a reaction rule that triggers, when a new user is registered. This rule sends a private message to a role ( service-role ).

The sender of the message is the actual logged in user - in this case the user that was just created, the new user.

I want the sender to be the admin but I have no change to select the admin the the data-selection field. How can I archive any other user that the actual logged in user?

I was able to select the wanted sender User by typing in the USER ID when the form is in direct input mode. To get to this "direct input mode", use the button "switch to direct input mode", as shown here:

After doing so, the form will look like so:

So in the end, the result of doing so is that if you read your private messages, then the sender is not the new user anymore, but the user you selected by ID manually (as shown in the above form).


Invalidate Internal Page Cache at certain times in a day for anonymous users Let say I have a webshop open from 9am to 11am (data coming from config).
When the shop is closed, I would like to display a message (shop closed) and when the shop is open, my commerce product should be available. (only for 'lunch' bundle)

I have tried to update the following code: https://cornel.co/article/drupal8/page-cache-cookies-or-anything-available-http-request

Here is my try (edited with a comment from 4k4:

protected function getCacheId(Request $request)
{
    if (! isset($this->cid)) {
        $cid_parts = [
            $request->getSchemeAndHttpHost() . $request->getRequestUri(),
            $request->getRequestFormat(NULL)
        ];
        // Only cache by State of Store for some path
        if (strpos($request->getPathInfo(), '/lunches/') != false) {
            $store_state = get_store_state();
            $cid_parts[] = $store_state['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
        }
        $this->cid = implode(':', $cid_parts);
    }
    return $this->cid;
}

As stated by 4k4, I must create a new context which will bubble up and will invalidate the Internal Cache page.

Here is the code of

class StateStoreCacheContext implements CacheContextInterface

stored in mymodule/src/CacheContext/StateStoreCacheContext.php

public function getContext()
{
    $storeState=get_store_state();
    return $storeState['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
}

And here is mys service declaration:

services:
   cache_context.state_store_context:
    class: Drupal\mymodule\CacheContext\StateStoreCacheContext
    arguments: []
    tags:
      - { name: cache.context }

And here is the way I add my context to my page (in mythem_preprocess_node(&$vars))

$vars['#cache']['contexts'][] = 'state_store_context';

Unfortunately, my page cache is not invalidate for anonymous users (but it is ok for logged-in users)

You have to add a cache context as well. See both answers in this topic:

How do I create a cache context in Drupal 8 that varies on user/node field data?

You add a variation to the CID of the Internal Page Cache and a custom cache context to the node, so that it can bubble up to all elements which are dynamically cached. The difference is, CIDs can't bubble up, contexts can, and so vary all render elements no matter how deep they are nested.


How do I restrict a user from edit his/her own profile I have some custom fields added to the user profile. some of these fields are filled and synced autimatically from an LDAP account and others only admins can fill.
I want to keep these aditional fields on the profile page but don't want to let the user itself modify these.
how can I restrict a user from edit his/her own profile?

You can either hide them from the form on the Manage Form tab, or use a form alter hook to set #access to FALSE if they don't fit a certain role.

You can also try the Field Permissions module.


Should I ignore the vendor directory in git for Drupal 8? I'm finally trying to get on board with using Drupal 8 and want to know if I should ignore the vendor directory in git with .gitignore. I would assume not, but I've seen a few example .gitignore files that do.

Thanks!

There isn't really a right or wrong answer, it will come down to your situation. Composer themselves have pretty strong feelings that yes, you should ignore it, and in an ideal world that's definitely what you should do, but it's not always that straightforward.

It depends mainly on your hosting and deployment process. If, for example, you're on Pantheon, and don't wish to implement a complicated upstream workflow, involving a dialogue with their technical staff, you're forced to commit all dependencies to the repo. There's no Composer sitting at the other end waiting to run when your code is pushed, if you don't push those files up yourself, they're not there, and things will break.

Similarly if you're on shared hosting and don't have a CI workflow, you're probably going to be forced into lugging all the files around with you in one way or another.

Basically if it fits into your development/deployment workflow to be able to exclude those files, it's a good idea to (for the reasons listed in the link above).

If it doesn't, committing them to the repo is absolutely fine.


How can I send an email to the previous comment author when a user places a new comment? I want to get the Email address of last comment's author. Actually, I want to send email by creating a rule  when new comment posted and this email will go to the user who commented on node before this new comment.

There are two situations and they might be a bit hard to combine. Drupal has a concept of threading comments, where the last comment is not necessarily the last in line. Like this:

- Comment 1
  - Comment 3 (reply to comment 1)
- Comment 2

Who should get the mail? The poster of comment 2 (the last comment author), or user 1? Or both? Also note that you can disable threading comments on the content type settings page.

In order to send a mail to the author of Comment 1, you can create a Rule on After Saving New Comments. Use the Send mail action and for the to: field you can use the token [comment:parent:author:mail]. (The mail of the author of the comment above this one.)

If you want to send a mail to the author of comment 2, your rule gets a bit more complicated. The initial action need to be Before Saving New Comments (so last comment is actually the last comment before yours).
For the first action choose Add a variable, the type is List of comments and you choose the value to be comment:node:comments. This variable holds all comments on the node.
Now you need to find a way to keep removing items from this list and send an email to the last one.

Below is based on experience and not tested, but I guess you can add a loop and loop over the items in your newly created variable. Then, in the loop Add a variable to contain a comment entity and set it with the current item in the loop. This will redefine this variable for every comment in the list and in the end this variable will hold the last comment.
Then below (not in) the loop, add your mail action and use the author of your newly created variable.

If you want to send a mail to all commenters, place the mail action within the loop (you can omit the comment variable in this case).

Update

This can also cause the author of comment 3 to get a mail triggered by comment 4:

- Comment 1
  - Comment 3 (reply to comment 1)
- Comment 2
- Comment 4

If you want to have more control, you'll need to create a Rules Component and call that component from the loop. Within the component you can add conditions to check if the comment has parents and skip the variable assignment based on that.


How to edit markup on existing pages using version 4 of the CKeditor library in Drupal 6? I installed/enabled CKeditor version 4 (from its download page) to use it in a Drupal 6 site. It's working fairly well with one exception: editing markup on existing pages doesn't work.

What happens is, that old pages won't accept the changes. It's baffling: the code is correct and it shows up in the source, but it's not rendering on the page for nodes that were created before I installed CKeditor 4. For example, I have a line with a line break at the end of it, but the line breaks aren't showing up.

But for new pages, the line break works just fine. It's only the old nodes where it's not showing up.

And if I uninstalled CKeditor version 4 and go back to CKeditor version 3, the issue disappears.

Any ideas or recommendations?

CKEditor Version 4.x is known to have 'some' issues, at least when used in DRupal. The issue you described in the question here is probably one of them. And it doesn't matter if you use the CKEditor 'module', or the WYSIWYG 'module' (in combination with the CKEditor 'JS library'). Because for both modules these issues exist.

In my experience, going back to CKEditor 3.6.x version (or never upgrading from 3.x to 4.x) has always been the best "compromise", since in the 3.x versions these issues seem to not exist.


reverse output of list in the view Is there a way to reverse order of the outputed list:

These items were being added as Global:Contextual links in the View, but order is wrong. Instead of going and replacing in each view (lets say that there are 100 views), what would be the quickest way of reversing order and making it like :

Manage display
Clone
Access Control
Delete
Edit

Thanks

You have to implement the hook_menu_alter and adjust the links weight property to your will. Here is a sample code that changes the node's default contextual links by placing the delete link over the edit link:

/**
 * Implements hook_menu_alter().
 */
function foo_menu_alter(&$items) {
  $items['node/%node/delete']['weight'] = 0;
  $items['node/%node/edit']['weight'] = 1;
}

Keep in mind that the smallest the weight of a link the more will flow on top, negative numbers may also be used.


How to create an image gallery in Drupal 7 I would like to create image galleries in my Drupal 7 site. Ideally the gallery should be easy to create and themable. What is the best way to do this?

It seems like Taxonomy, Colorbox, Views, and the Image field in D7 would be the best way to do it.

Create a taxonomy for gallery
Create a content type for image
Create a View to display the gallery taxonomy
Create a View to display the images in the gallery taxonomy term

I say that is the best approach because it gives you the most flexibility, and will only take you about 30 minutes to set up. Anything else for a gallery (in my experience) tends to be overkill unless you're an actual photo sharing website.


Programmatically add items to the menu - not hook_menu We're redesigning our site and getting rid of the sidebar. The main reason for the sidebar to exist was to hold Organic Menus (og_menu), which we have hundreds of groups, each with 2 or 3 menus. I want to move OG menus to the main menu.

What I would like to do is when a user visits a particular OG

load the menus for that OG (trivial)
programmatically make the menu's name the top level links linked to # (Trivial - we use bootstrap)
add the menu's links below those top level links (this is where it gets tricky)
and append them to the main menu as the last to links (no clue)

So the top level would look like this only when the user hit the group

Home Communities Forum Group-Menu-1 Group-Menu-2

Home, communities and forum are always there the group menus are appended when they're in that group. I don't need code I just need direction on which parts of the API will facilitate this.

I solved this by just appending my links to the menu tree with hook_preprocess_menu_tree

<?php

function my_module_preprocess_menu_tree(&$vars) {

  if($vars['theme_hook_original'] != 'menu_tree__primary') {
    return;
  }

  $node = menu_get_object();

  //Check to see if this is a group node or group content and return the group_node
  $group_node = my_module_check_for_group_node($node);

  if($group_node) {

    global $user;

    $vars['tree'] = str_replace('last leaf', 'leaf', $vars['tree']);

    $result = db_query('SELECT menu_name FROM og_menu WHERE gid = :nid ORDER By weight', array(':nid' => $group_node->nid));

    $menus = $result->fetchAll();

    foreach($menus as $menu) {
      $tree = menu_tree($menu->menu_name);

      if(!empty($tree)) {
        // render the organic group menu as HTML
        $tree = drupal_render($tree);

        $tree = str_replace('menu nav', 'dropdown-menu', $tree);

        $menu_array = menu_load($menu->menu_name);

        //format
 and top-level  for bootstrap
        $li = '
'.$menu_array['title'].''.$tree.'
';

        $vars['tree'] .= $li;
      }
    }

    $vars['tree'] .= $li;
 }
 ?>


Filter webform submissions by access I have a Drupal website which uses webforms and a custom module to manage the access in their submissions using hook_webform_submission_access.

While successfully restricting the access of a webform submission to a user, though, when they view the "Results" tab (or the "Table) the access filter isn't triggered as these tables are generated by Views.

How can I add a filter to the default "Webform submissions" view in order not to show the ones that the user has no access on?

PS: I know I can use hook_views_pre_render and unset the rows from the results, but I believe a filter would be a better and more elegant solution.

You can use Views PHP module.
This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
Enable this module and add a filter PHP filter which you can select from views filter Global Category once you install above module.
Add php code for filter condition as per your requirement.


Relationship in View I need to have two content type: "book" and "article".
Then I want to make a view that shows the title of the book (which is in the content type book) and the titles of each article (found in the content type article).  Which field should I add to the content type "article" to make sure it is plugged into a certain book? And how do I set the View?

Although your question seems a bit less detailed than it should be, I assume that you need some way to connect a node type (article) to another node type (book). For this you can use References module or Entity References will be even better.

You can add an entity reference field to book content type. Then, when you create a book, you can select relevant articles. If you want to have two-way relationship (book <--> article) then you can also use this module: drupal.org/project/cer
A good addition can be this module also: http://drupal.org/project/inline_entity_form which allows you to create or select your articles when you create a book.

Then in your view, you can show book's titles as fields.
Add a relationship with your entity refrence field.
Add a field "title" but select relationship you just added.
Group the results by first field (title only)


restrict user access to sub domain if assigned to another sub domain I have a site using the domain access module. I created 2 sub domains. agent1.example.com for agent1 and agent2.example.com for agent2. However, I can login to agent1.example.com with agent2 login info. I only want agent1 to login to agent1.example.com and agent2 to only be able to login to agent2.example.com.

The reason why I am using domain access instead of multi site is because I am sharing training videos, documents, and corporate documents across all sites. However, each agent will have their own page where they can track clients and sales statistics, so I want only them to see it.

What is the best way to go about this, or is there a better module for this? Or is there a way to share content across multi-site domains?

Thanks,
  cquigs

the Domain Bonus module can help you solve this problem.

  The Domain Bonus is group of modules that extend functionality of Domain Access module.

check the "Domain Bonus: Login restrict" sub module


How to orderBy joined table after ordered main in db_select I have 3 joined tables - The query search some string on main table then join other by entity_id. I want to orderBy records in order first second third tables result, but no success now. At this time I have order by only for main table.

My query:

$query = db_select('field_data_field_cg_w', 'w');

$query -> join('field_data_field_cg_h', 'h', 'w.entity_id = h.entity_id');
$query -> fields('h', array('entity_id', 'field_cg_h_value'));

$query -> join('field_data_field_cg_g', 'g', 'w.entity_id = g.entity_id');
$query -> fields('g', array('entity_id', 'field_cg_g_value'));

$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  -> condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  -> orderBy('w.field_cg_w_value', 'ASC');

$records = $query->execute();

EDIT:
The result (last part of query) after Clive's answer:

$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  -> condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  -> orderBy('w.field_cg_w_value', 'ASC')
  -> orderBy('h.field_cg_h_value', 'ASC')
  -> orderBy('g.field_cg_g_value', 'ASC');

Not sure I understand but you're not limited to a single orderby() in a SelectQuery so you would just add another one with the correct alias, e.g.

$query -> fields('w', array('entity_id', 'field_cg_w_value'))
  ->condition('w.field_cg_w_value', $options['string'] . '%', 'LIKE')
  ->orderBy('w.field_cg_w_value', 'ASC')
  ->orderBy('g.entity_id', 'DESC');


hook_menu parameter can contain a forward slash I've built a custom module to get cloudinary images and it works great. However, a bug has cropped up. You can navigate to /cloudinary/resource/public_id and it gets the image with public_id. On cloudinary there is now the ability to specify folders, so a public id could be something like "unitedstates/public_id". This is wrecking my hook_menu:

function cloudinary_menu() {

    ...

    $items['cloudinary/resource/%'] = array(
        'access callback' => TRUE,
        'page callback'  => 'get_resource',
        'page arguments' => array(2)
    );
...

Is there any way to specify that anything after /% should be passed?

Additional arguments are still sent to page callback functions.

You might try doing a check for additional arguments:

function get_resource($id) {
  $args = func_get_args();
  if (count($args) > 1) {
    $id = end($args);
  }
  /** rest of your code **/
}

This way if the public id was "unitedstates/public_id", func_get_args() would return two items, the second one being "public_id" which would be set as the $id if there is more than one argument. Note this will always set the last argument as $id if there is more than one.


Should I use a separate content type? In drupal 6 I have a content type with a lot of fields, voting, referenced nodes (as answers), etc. Now I would like to create a very similar content type - same behaviour and everything, there are only 2-3 fields that are different, but everything else is the same. Now comes the question: Should I create a separate content type, setup everything, use separate voting, etc? Or is there a way to somehow 'inherit' everything and change only 2-3 fields that need to be changed?

If you are going to do this often, or expect changes that require these two types to be in sync in the future, you might investigate the http://drupal.org/project/features module, which packages stuff up like this.  But, if it's a one off thing, I'd just go and create a new content type and reuse the existing fields plus the new/different ones in the second content type.  If you don't want to type everything in again, you should be able to use the CCK export feature and then just change the name and type of the result and import it, which if all goes well, will create the second type for you identically to the first.  Then just add the new/different fields manually.


What's meaning of %contact in this menu path? $items['admin/structure/contact/edit/%contact'] = array(
    'title' => 'Edit contact category',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('contact_category_edit_form', 4),
    'access arguments' => array('administer contact forms'),
    'file' => 'contact.admin.inc',
);

How does it get the path admin/structure/contact/edit/%contact and what does it mean by %contact?

All requests on admin/structure/contact/edit/[anything] will be handled by a Drupal form callback, contact_category_edit_form() in contact.admin.in` which returns a form array.

%contact means this parameter will be passed to contact_load() and the result will be pass to contact_category_edit_form() as first argument.

See hook_menu().

  Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule_abc' part defines the prefix for a load function, which here would be named
  mymodule_abc_load().


How to creat different user type in drupal? I want to create two different type of users for example internal and external users. For internal users need to be authenticate against different database. Any suggestions?

Unless you wish to write a custom module with direct access to the second database, with its own login system, the only way this is going to work is with direct manipulation of the drupal database, renaming tables, and using 'Create View ...' to give you access to the information. The amount of work, maintenance problems, and security implications would be horrendous.

If the number of 'internal' users is fairly static, my suggestion would be to use the User Import module, and give them all a role of 'Internal', using the user permissions to control their abilities on the site. Any new Internal users could be added manually.


How to organize webforms on (admin/content/webform) into groups Goal: I want to be able to organize the list of webforms on the admin/content/webform page, which is in a View to my understanding, in groups. Either via visual groups (using some header or box) or add a filter to the page so that I can specifically look up a term ID that is associated with one or multiple webforms (like you can on the admin/content page).

So for example: if I had several webforms about housing, I would like to be able to create the header 'Housing' and have associated webforms underneath. Or be able to select the Vocab or TID associated with one or multiple webforms and filter the results.

I'm a very new user to Drupal (couple months experience on the job only). I've spent the last ~4 days searching the internet to find info to help me and have found some promising things but haven't gotten anything to work. Many things are over my head.

The best two things I've tried are the following:

1) I've tried editing the Webform View. I've tried adding a TID field but that's not listed as an option to add. My plan was to add a Contextual Filter for TIDs.

2) I've tried adding a Term Reference field and Node Reference field to a Webform. This seemed promising until I realized they became Select List options on the actual webform presented to the user. Obviously this will not do what I want to do on the developer side of things.

I've heard about creating custom admin pages with views but I was hoping for a simpler way to accomplish this. If that is the only way to do so, so be it.

I'm using Webforms 7.x-4.4 fyi.

Thanks for any help! Sorry this is long and probably newbish.

I solved my own question.

Ended up creating a new Administration View of type content for only webforms. I then added the field 'Content: Term Group' which I added to the Webform Content type which is a term reference. I should mention I already created a new Taxonomy Vocabulary and gave that vocabulary three children taxonomy terms. From then it was as simple as noticing that 'Term reference' showed up when I hit Edit on a specific Webform so I can select one of the taxonomies. Then I changed the Format Setting 'Grouping field Nr.1' to 'Term Group' and thats it! Now my custom link (/admin/content/webform-groups) page shows all the webforms separated into separate boxes with their respective Term ID name above.


What controls render order? I have a loop populating multiple render arrays, and my output is not appearing as expected.

      $count = 0;
      foreach ($result as $row) {
      //do stuff

      if ($is_a_link_list) {
         //do more stuff

        $id = 'link_list_a' . $count;
        $content[$id] = array(
         //render array - link list
        );

      } else {

        $id = 'promo_list_a' . $count;
        $content[$id] = array(
            //render array - title
        );
        $id = 'promo_list_b' . $count;
        $content[$id] = array(
            //render array - body
        );

      }
      $count++;
    }

So in a given result set I'd expect:

---promo list title
   promo list body

---link list
   =item1
   =item2
   =item3

(more results)

What I'm getting:

---promo list title
   promo list body

---link list
   =item1
   =item2
   =item3

   promo list body
---promo list title

---promo list title

---link list
   =item1
   =item2
   =item3

   promo list body

---link list
   =item1
   =item2
   =item3

So does the key of the render array matter? (Other than needing to be unique)

Looking at the markup output it's apparent that I need to render my render arrays as list items; I think this means a nested render array?

HTML source:

The order of the output for a render array is determined by the #weight attributes of it's contents. To reorder elements in a render array, set the #weight attribute of the target elements, using smaller values for elements that should appear earlier. Then set the #sorted attribute of the parent element to FALSE, this will make Drupal resort the elements of the render array before generating the output HTML. You can see an example of the technique in the Render Example module included in the Drupal Examples module. The relevant code is

$page['sidebar_first'] = array_reverse($page['sidebar_first']);
foreach (element_children($page['sidebar_first']) as $element) {
  // Reverse the weights if they exist.
  if (!empty($page['sidebar_first'][$element]['#weight'])) {
    $page['sidebar_first'][$element]['#weight'] *= -1;
  }
}
$page['sidebar_first']['#sorted'] = FALSE;

Now when Drupal goes to render the content, it will first be sorted according to #weight. Also note that elements which do not specify a #weight attribute are assigned a weight of 0 during sorting, so they will appear in the output in the order in which they are defined in the render array.


How to redirect my content type form after submitting in module How to redirect my content type form after submitting in module.

Code:

function message_proposal_form_alter( & $form, & $form_state, $form_id) {
  if ($form['#id'] == "article-node-form") {
    $form['submit'][] = 'my_callback_function';

  }
}

And

function my_callback_function($form, $form_state) {
  unset($_GET['destination']);
  $form_state['redirect'] = 'node/add/article';
}

You can use Node Save Redirect module.

  This module provides a method of specifying a location to take the user after saving a piece of content.
  A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are:

Default - Default behaviour

Return to Edit page after saving

Return to content overview page (assuming the user has access permissions

Re-redirect to another location. (any valid drupal path)

Or you may try to add submit function to 'Save' button

function mymodule_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node_form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_node_form_redirect_submit';
  }
}

function mymodule_node_form_redirect_submit ($form, &$form_state) {
  $form_state['redirect'] = 'node/add/article';
}


login block without a "log in" button I want to create a very minimal login block and thus wouldn't like to have the "log in" button at all. I would like to have only the username and password fields, and log on by hitting "enter".

I have added display:none CSS property to the button, but this will stop form from being submitted. What else could be done ?

The jquery approach to achieve this one which worked for me (drupal 7) is the following code

$("#edit-pass").keypress(function(event) {
  if ( event.which == 13 ) {
    $('#edit-submit').click();
   }

});

$("#edit-name").keypress(function(event) {
  if ( event.which == 13 ) {
    $('#edit-submit').click();
}});

#edit-name and #edit-pass are my two login fields.


How to get term ID from translated term name? I have a custom argument validator for Views, which expects a term name input and outputs the tid for the query. This works great in English, but I'm not sure what to do for translations. Is there any way to search for a term id from the translated term name?

Here's my code:

public function validateArgument($argument) {

  if(strpos($argument, '-')){
      $argument = str_replace('-', ' ', $argument);
  }
  $term = taxonomy_term_load_multiple_by_name($argument);
  $termId = key($term);
  $this->argument->argument = $termId;

  return TRUE;

}

A suggestion :

$my_translated_term_name = 'astuce';

$query = \Drupal::database()->select('taxonomy_term_field_data', 'td');
$query->addField('td', 'tid');
$query->condition('td.name', $my_translated_term_name);
// For better performance, define the vocabulary where to search.
// $query->condition('td.vid', $vid);
$term = $query->execute();

$tid = $term->fetchField();


Custom Body of Webform email handler missing text area When selecting default, I have the html appearing.  Selecting twig will work as well.  Selecting Custom Body changes to a blank area with no way to enter code.  This happens on both lamp and live site. see image

At jrockowitz suggestion I found the issue, in case someone else has same issue,
ckeditor could not find the plugin.js file and related files.  I moved them as below and it works.
was: ckeditor.link/ with a folder called link and plugin.js
now: ckeditor.link/ with folders dialogs, icons, images, lang and plugin.js file


Adding a form to the admin menu Ive followed 3 tutorials and I cant seem to crack this. My goal is to create a form in the admin section to store some information.

I have used the following to create the form and call it from a url but I seem to be missing something

    function read_more_news_admin() {
  $form = array();
   //link field
      $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
      );
      $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und',
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
          'title' => variable_get('link_title', ''),
          'url' => variable_get('link_url', ''),
        ),
      );
  return system_settings_form($form);
}

function read_more_news_menu() {
  $items = array();
  $items['admin/settings/readmorenews'] = array(
    'title' => 'Read More News Module Settings',
    'description' => 'Set read more news outgoing link here',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('read_more_news_admin'),
    'access arguments' => array('administer readmorenews settings'),
    'type' => MENU_NORMAL_ITEM,
   );
  return $items;
}

Any help would be appreciated

try this:

function read_more_news_menu() {
    $items = array();
    $items['admin/settings/readmorenews'] = array(
        'title' => 'Read More News Module Settings',
        'description' => 'Set read more news outgoing link here',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('read_more_news_admin_form'),
        'access arguments' => array('administer readmorenews settings'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
function read_more_news_admin_form($form, &$form_state) {
    $form = array();
    $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
    );
    $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und',
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
            'title' => variable_get('link_title', ''),
            'url' => variable_get('link_url', ''),
        ),
    );
    return system_settings_form($form);
}

Or check this url: https://www.drupal.org/node/1111260

function read_more_news_permission() {
  return array(
    'administer my module' => array(
      'title' => t('administer readmorenews settings'),
      'description' => t('Administer read more news settings.'),
    ),
  );
}


Grouping content by Years (For eg Archive 2014-2015 or Archive 2014-16) I want to group my content type to group by years in views, for example Archive 2014-2015 or Archive 2014-16. How can I get this groupings?

Archive 2013-2014
-COntent 1
-Content 2
-Content 3

Archive 2015-2016
-COntent 1
-Content 2
-Content 3

The key challenge you'll face here is that neither Views nor Date modules provide aggregation options for date-based fields.

This can be solved by using the Views Date Format SQL module. It adds a nice little check-box that allows you to group dates by a custom formatted string, as shown in this example also:

In the above example, the custom date format is set to "M Y" (which translates to Oct 2015 for example), and the box for "Use SQL to format Date" was checked. This is the only configuration needed.


Installing/Enabling Custom Webform Hander I am very new to Drupal development though I am an experienced developer.  I created a custom Webform Handler following these tutorials and postings:
These for what files to create and where:
Create a custom webform handler in Drupal 8
Create a Webform Handler that sends a notification to Slack
Add a custom submission handler to a form
This post for the code to redirect a user to another webform upon form submission:
Page redirect in custom WebformHandlerBase
I have looked at everything and everything looks correct.  Here's what's in the YAML file modules\custom\redirect_to_ccbilling\redirect_to_ccbilling.info.yml:
name: 'Redirect to CC Billing'
description: 'Provides a custom webform handler for the "submit an event" webform so it will redirect to another webform node'
core_version_requirement: ^8.8
Core: 8.x
package: Custom
type: module

Here's what's in the modules\custom\redirect_to_ccbilling\src\Plugin\WebformHandler\RedirectToCCBillingWebformHandler.php:
<?php
namespace Drupal\redirect_to_ccbilling\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\src\WebformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @RedirectToCCBilling(
 *   id = "Redirect to CC Billing",
 *   label = @Translation("Redirect to CC Billing"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Redirect user to the credit card billing page."),
 *   cardinality =
 *       \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results =
 *    \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

 class RedirectToCCBillingWebformHandler extends WebformHandlerBase {
 /**
  * {@inheritdoc}
  */
    public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

       $form_id = 'webform_submission_' . $webform_submission->getWebform()->id() . '_form';
       if($form_id == 'webform_submission_xxx_form') {
         $values = $webform_submission->getData();
         /* Take the action based on the Webform submission values */
       }
    }

    public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
       $form_id = 'webform_submission_' . $webform_submission->getWebform()->id() . '_form';
       if($form_id == 'webform_submission_xxx_form')
       {
          if(based_on_some_condition) {
          /* Here 12 is the node id where i wanted to redirect to */
          $form_state->setRedirect('entity.node.canonical',['node' => 1764]);
       }
    }
}
?>

I went into the Extend menu and under Custom section I selected the Redirect to CC Billing module/handler and clicked Install at the bottom of the page.  However, when I go back to my webform >> setting >> emails / handlers >> +add handler all I see is this:

I don't know what I am missing for my custom handler to not be appearing in the list of handlers.

A few things in addition to what @4k4 commented:

Please replace your annotation plugin reference with @WebformHandler

Use lower case / snake case names for your Webform Handler ID eg. redirect_to_ccbilling

Ensure correct directory structure where the plugin discovery will look for Webform Handler classes. This should be /modules/custom/redirect_to_ccbilling/src/Plugin/WebformHandler/RedirectToCCBillingWebformHandler.php

Ensure that your module is enabled. Either via drush en redirect_to_ccbilling -y or by enabling it on the Extend module page.

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "redirect_to_ccbilling",
 *   label = @Translation("Redirect to CC Billing"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Redirect user to the credit card billing page."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class RedirectToCCBillingWebformHandler extends WebformHandlerBase {


Using db_select to only get the latest nodes with a certain field value I have extending a query function for a D2D migration.  The nodes have a field on them for a certain type of ID.  In the old D6 site the the field did not have to be unique, but in the new D7 site the field does have to be unique.

I want to use db_select so that I only get the newest nodes in the content_type_nodetype table if there are multiple nodes with the same value for that id field.

Sample table data:

content_type_nodetype
____________________________
| nid | field_someid_value |
|==========================|
| 1   | 12345              |
| 2   | 12346              |
| 3   | 12347              |
| 4   | 12345              |

node
____________________________
| nid | created            |
|==========================|
| 1   | 1292780734         |
| 2   | 1292780735         |
| 3   | 1292780736         |
| 4   | 1292780737         |

Given that data, the query I want should only return nid 2,3, and 4 as the value for field_someid_value for nodes 1 and 4 are the same, but the created timestamp in the node table for nid 4 is later than the timestamp for 1.

You might try something like :

$query = db_select('node', 'n');
$query->join('content_type_nodetype', 'ct', 'ct.nid = n.nid');
$query->groupBy('field_someid_value');
$query->addExpression('MAX(n.nid)', 'nid');

The 'nid' order must follow the 'created' order so you won't need to order the results. Just taking the biggest nid for each field_someid_value should do the job.


Convert path alias to ID How can I get the ID of a taxonomy term with only a path alias, using PHP?

I have a vocabulary with some taxonomy terms with a path alias like [vocabulary]/[term] (e.g. car/model) and I have repeated model terms. (So I think that using titles is not an option.)

I created a view with a path (car/%); if I want to make another view with an extra argument and car/%/% as path, I can't get the content unless I use the taxonomy ID like car/123/1 instead of car/model/cat.

Is there a way to make this?

I solved the problem with this:

e.g. i have the path alias car/ilx-0 and i can get the tid easily, but what if i want to pass only the ilx-0 to another path view, like: products/ilx-0, the path alias doesn't match anymore so it's not easy to get the tid, to achieve that i used the following code on products/% view:

    <?php
    $pa=drupal_get_normal_path('car/'. arg(1, request_uri())); /* get the ilx-0 from products/ilx-0 and transform to taxonomy/term/tid */
    list($t1, $t2, $t3) = explode("/", $pa); /* Explode taxonomy/term/tid */
    /* $t1 = taxonomy */
    /* $t2 = term */
    return $t3; /* tid, return this value to get tid and pass to context filter*/
    ?>


Displaying multiple price for products I'm trying to create two selling price for each products. One is retail and another is wholesale price. For that I have two price fields in my product variation (commerce_price and wholesale price). But when I add a product it was displaying only commerce_price. I want to display both prices. I have enabled both price fields in its display settings also.

Here is the snapshot how it was looking now

Can anyone tell me how can I achieve this?

I'm guessing you're using commerce kickstart and/or you've got Commerce Extra Price Formatters installed, it has an extension that provides the feature you're displaying, RRPP and your price.

Check out your display options, the second price won't appear automatically until you make it so. Go to admin/structure/types/manage/[your-product-machine-name]/display and verify that your price is being displayed there:

Then click in the link for the settings of the variation type display if you're in kickstart or go to admin/commerce/config/product-variation-types and edit the display for your variation type.

If you're not in kickstart, the url for this same screen would be admin/commerce/products/types

Change the price formatter to Formatted price or whatever other fits for your needs.


Problem with escaped characters in attributes The default theme_image() is implemented as

function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

drupal_attributes() is implemented as

function drupal_attributes(array $attributes = array()) {
  foreach ($attributes as $attribute => &$data) {
    $data = implode(' ', (array) $data);
    $data = $attribute . '="' . check_plain($data) . '"';
  }
  return $attributes ? ' ' . implode(' ', $attributes) : '';
}

and check_plain() as

function check_plain($text) {
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

Since htmlspecialchars() is being called with ENT_QUOTES, single quotes in my title and alt text on the image are being escaped as &#039; and double quotes as &#quot;, so hovers look weird.

Is there an acceptable, safe, secure way to handle this situation?

Make sure you aren't check_plain()ing the value before calling it, eg, don't do:

... theme('image', array('path' => 'test.jpg', 'alt' => check_plain($foo));

or otherwise use a $value that has been processed by any 'safe' filters.


Search on other fields of content type I created a content type called "Automobile" and that has the following fields: "Model," "Manufacturer," and "Year." When I go to "Dashboard > Content > Find Content," the search does not offer me controls to "find all automobiles between the year 1990 and 1995 with the model Caravan."  How do I configure Drupal to allow such queries?

You have to create a view if you want this control.    Like this

This will give you a page with the exposed filters you asked for @ www.mysite.com/automobile.


Trouble getting a drupal 7 view template to render for a machine readable block i'm using drupal 7. I have created a content type called Title and content navigation.

I have setup a template override in /sites/all/themes/themename/templates/views/title-and-content-navigation/block/views-view-fields--title-and-content-navigation.tpl.php which works correctly for all of the displays which are blocks.

I have one of the displays for this view which has a machine readable name of block_8. I am trying to have a separate template file for this but I cannot work out what I need to name the file. I have tried many suggestions from SO and I can't get this to work. I have been flushing all caches. What to name the template files is very confusing.

Thanks in advance

Click on "Theme: Information" under "Advanced" on the right hand side of the View edit page.

All the available template suggestions for the View and its displays are listed in the resulting modal.


OpenLayers Locator proximity search(content) and map display within tab I got correct result when i based on  search with mile and distance.

Output displayed openlayer content views and map .

I need to displayed result like tab view that List and Map both are tab titles

 Click list -> displayed  ** Content **
 Click Map  -> displayed  ** Map **

Anyway I Find Out Solution.
Create a two pages like Page 1 and Page 2.

Setting Menu Tab to both pages

1. Menu Tab: List in PAGE SETTINGS
2. Menu Tab: Map in PAGE SETTINGS

Change CSS setting in view-filter.


is there anyway to populate nodes when type a custom content type value using node reference in drupal 7 is there anyway to populate nodes when type a custom content type value using node reference in drupal 7 ?

node refernce populate nodes when we start typing the title of the nodes . is there any option in drupal 7 that we type custom field and it populate the related nodes as it is working with the title.

Thanks

You can select a View in Content Settings in "VIEWS - NODES THAT CAN BE REFERENCED".

Let that View return whatever field values you want to return.


Installed D7 with Minimal profile and root user do not have any role set to it. How to create a locked role for root? Now I can create only simple role which can be easily edited and deleted. I need a role for root user (user ID 1) for some other modules that requires selecting a role.

Now installing minimal profile of Drupal my root user is roleless. Don't know how to call it.

In overall I need something that the root user would be undeletable/uneditable by any other admin who has power to edit users and permissions and roles.

Navigate to /admin/config/people/accounts#edit-admin-role and select from the list which role should be treated as "Admin role".


Download development releases of modules with Drush Make How do I get a development release of a module in the .make file of my installation profile?

I am writing this now to get the development release of better_exposed_filters.

projects[better_exposed_filters][version] = "3.0-beta3+31-dev"

When I run the .make file I get the following message:

  Could not locate better_exposed_filters version 7.x-3.0-beta3+31-dev, will try to download latest recommended or supported release.

I tried generating a Drush make file with http://drushmake.me/, and the generated file contained the following lines.

projects[jquery_ui][version] = 1.x-dev
projects[jquery_ui][type] = "module"
projects[libraries][version] = 2.1
projects[libraries][type] = "module"
projects[xmlsitemap][version] = 2.0-rc2
projects[xmlsitemap][type] = "module"

I think that in your case you should use the following lines.

projects[better_exposed_filters][version] = 3.x-dev
projects[better_exposed_filters][type] = "module"

That would select the development snapshot for 3.x; in the case you want to select the 7.x-3.0-beta3 version, then you should use the following lines.

projects[better_exposed_filters][version] = 3.0-beta3
projects[better_exposed_filters][type] = "module"

The make file needs to contain the following line, which select Drupal 7 as Drupal version to use. This alters the version used for the modules; for example, the following line used with the latter lines I shown, would pick-up version 7.3.0-beta3 of the Better Exposed Filters module.

projects[drupal][version] = 7


Altering the views Sorting Criteria, to display first ISSET fields Ia am working on a view that displays search results for nodes of a certain content type. In this Content Type there is a field "photo". Some of the nodes have a photo, some of them not. Is it possible to display (in the search results), first the nodes that have that field filled and at the bottom the nodes where the field photo is not set?

I tried to achieve it with custom sorting in the PHP field, using a snippet that i found here : https://drupal.org/node/727418#comment-3827246

$query->orderby = "CASE WHEN myFieldName IS NULL THEN 0 END, myFieldName ASC"; }

but it didn't work. Any ideas?

Why not order by quantity of elements in photo field, or delta ?


Gating/Redirecting anonymous user back to an origin page after logging in/registration I have a use case where I need to redirect a user visiting a page, let's say sprockets/order when a user clicks on an "order" link. We take them to a page with a login field (not user/login, but something with that form). Once they log in, we need to redirect them to that page, or for that matter, any origin page they click from to the login page.

I've looked into a couple of modules, right now Login Destination is the one i'm experimenting with, with no real success, even when its routing is configured to fire from this origin page. I'll keep experimenting with it, but I can't imagine its the only option at hand.

The question ultimately is, with the logic below, is there an approach I can take with how I send users to this specialized login page, and have them return to the origin?

The logic I have for this is as follows:

/**
 * Implements hook_menu()
 */
function hook_sprocket_menu() {
  $items['order/%order_id'] = array(
    "title" => t("Order Sprocket"),
    "page callback" => "example_order_sprocket",
    "page arguments" => array(1),
    'access arguments' => array('interact with orders'),
    "type" => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Routes the order call based on click
 */
function example_order_sprocket($orderid) {
  global $user;

  if(user_is_anonymous()) {
    drupal_goto("custom/user/login"); //The custom login/reg page
  } else {
    //Continue with Order logic here
  }
}

You can have destination parameter in url. Something like below.

drupal_goto('custom/user/login', array('query' => array('destination' => current_path())));


Is that possible to single sign-on with completely different domains? we have multilingual Drupal 7 site.

  Swedish Domain : www.swedish.com

  English Domain : www.english.com

admin/config/regional/language looks like screenshot.

No Domain access is used. I have tried https://www.drupal.org/project/sso_multi_domain but seems there need sub-domains.

Please suggest is there way we can make login working with separate domains which are pointing to same site folder, same database etc

Thanks!

Have you tried the Domain module? I've looked into it a bit, and seems to do what you need (though I myself have not set up my site yet with it, so I'm not positive). According to the documentation:

  The module allows you to share users, content, and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

https://www.drupal.org/project/domain


Calendar widget translate problem on Drupal 7 I am experiencing issues with the translation of the Date/calendar Widget for Drupal 7 and I wonder if there is a solution for this problem without mixing with the source code for the date/calendar module, or if maybe I am missing some point here.

Here are the initials for the week days in the little calendar in English:

M - Monday
T - Tuesday
W - Wednesday
T - Thursday
F - Friday
S - Saturday
S - Sunday

In Portuguese, the same week days are:

S - Segunda-feira
T - Terça-feira
Q - Quarta-feira
Q - Quinta-feira
S - Sexta-feira
S - Sábado
D - Domingo

The problem is that when I translate the 'T' (Thursday) to 'Q' (corresponding to "Quinta-feira"), both days starting with a 'T' in English are translated as 'Q' in Portuguese. Both Tuesday and Thursday are shown with a 'Q' on top, and that of course is plain wrong for displaying the calendar in Portuguese.

Is there some built-in localization/translation feature for the calendar that doesn't use the Drupal translation tool that does not seem to work in this case?

Thank you.

If you by date widget means the JS popup, then that part is not actually translatable in Drupal. Instead you need to activate a load a language js file for the jQuery plugin which will translate the widget for you. If those translations are wrong, you should file a bug report with the jQuery team.

I searched the data module and couldn't find the text strings that you mention above. Drupal 7 allows modules when creating translatable strings to provide a context. I see that the date module does that several places:

t($date->format('F'), array(), array('context' => 'Long month name', 'langcode' => $langcode));

Doing this will create an extra translatable strings. An example use would be:

t('Order', array('context' => 'the order of items');
t('Order', array('context' => 'an e-commerce order');

The word is the same but the meaning is different, by doing the above it will allow translators to translate the strings differently. If a Drupal module provides the text strings for your widget, they will need to do something similar: fx

 t('T', array('context' => 'Tuesday');
 t('T', array('context' => 'Thursday');

If the module haven't done this, your best bet is to submit a patch for the module and explain why they need to do this. This is generally a good practice to do when you create translatable string that aren't unique.


Cannot Unflag a User Programmatically This is all programmatic: in a module.

I have a flag that I can set successfully, but I cannot unset/unflag. I do not know why, as the code seems so similar.

The flag is set in a _submit function of a form:

  // Enable the global user object
  global $user;

  //Flag the user as having MyExample credit
  // Invoke the Flag API to set the flagging. This also saves the flagging entity.
  $flag = flag_get_flag('MyExample_credited');
  $flag->flag('flag', $user->uid);

I can detect this flag successfully in other functions using this code:

if ($flag->is_flagged($user->uid)) {

However, unflagging is not working. Here is the code:

  // Enable the global user object
  global $user;

  $markup .= 'Removing credit...
';
  //Unflag whether the user has MyExample credit
  $flag = flag_get_flag('MyExample_credited');
  $markup .= 'Flag status:' . $flag->is_flagged($user->uid).'
';
  $flag->flag('unflag', $user->uid);
  $markup .= 'Flag status:' . $flag->is_flagged($user->uid).'
';

This produces the following output:

  Removing credit...

  Flag status:1

  Flag status:1

Testing the flag on other pages also confirms that it has not been unflagged.

Why could this be? Nothing in any of the error logs. Is it to do with how I have declared the flag, perhaps?

function MyExample_flag_default_flags() {
  $flags = array();
  $flags['MyExample_credited'] = array (
    'entity_type' => 'user',
    'title' => 'MyExample Credit',
    'global' => 1,
    'types' =>   array (),
    'flag_short' => 'Give credit',
    'flag_long' => 'Give this user a MyExample credit',
    'flag_message' => 'Credit given.',
    'unflag_short' => 'Remove credit',
    'unflag_long' => 'Remove a MyExample credit for this user',
    'unflag_message' => 'Credit removed.',
    'unflag_denied_text' => 'You cannot remove this credit.',
    'link_type' => 'toggle',
    'weight' => 0,
    'show_in_links' => array (
      'full' => 0,
      'heartbeat_user' => 0,
      'token' => 0,
    ),
    'show_as_field' => 0,
    'show_on_form' => 0,
    'access_author' => '',
    'show_contextual_link' => 0,
    'show_on_profile' => 0,
    'access_uid' => '',
    'module' => 'MyExample',
    'locked' => array (
      'global' => 'global',
      'status' => 'status',
    ),
    'status' => true,
    'api_version' => 3,
  );
  return $flags;
}

Could it be a permission issue?
Maybe set the "skip_permission_check" at true, as said in documentation here:
https://www.drupal.org/node/1748148#flagging


How can I add a field to a view that is calculated using other fields? How can I add a new field to a view that is calculated using other fields?

Is there a way native to Views to accomplish this?

If the original view returns the row: X | Y | Z

And I have a function calculating new data: $new = do_something(X, Y, Z);

How can I include $new as a fourth column to resulting in: X | Y | Z | $new

I have looked into using a views template to accomplish this, but I'm curious as to whether there is a better way to do this using Views hooks or another module.

What templates, hooks or modules would be best suited to accomplish this?

You could create your own views field handler in a custom module.
Implement  hook_views_api and hook_views_data_alter(&$data) than you can write your own field handler.


Using Drupal Commerce Product Reference Field, missing products I've followed instructions here: https://drupalwatchdog.com/volume-1/issue-1/building-drupal-commerce-product-display

When I create my Product Display, the list of products to choose from is missing most options, as can be seen here:

I have many more products under "Dips" added, but they aren't showing up. Any ideas why?

Check the setting of this field. It looks like it is set to 10. Just make it blank and it should allow for all of the products to be shown.


Google Analytics Module: Sub Domains I am using a Drupal Multiple Site (several sites running on 1 Drupal installation). Each site is part of a subdomain.

For example:

mysite.com
store.mysite.com
blog.mysite.com

Each site has its own separate database. Do I set up Google Analytics on just the main site or on all the sites?

In this post, it says you need to set it up on all the sites. However, it also says you need to  "show the ".domain setting" in footer". I can't find this setting anywhere in the UI.

You will need to install the module on each site using the same UA# (assuming these should all be tracked under the same account).

All you need to do is select One domain with multiple subdomains for everything to track properly.


Any idea why view->field is empty when executing a view returning user emails? We are using Business Rules to execute a view (users) that returns a list of email addresses. It works fine when rule is triggered by admin, but does not work when triggered by other users. In debugging it I found the following:

as both users the view returns the correct result rows, ie. $view->result is identical for both users.
as admin the view object contains a list of the fields which business_rules uses, ie. $fields = $view->field is an array keyed on 'mail';
as any other user $view->field is empty UNLESS I turn on administer users permissions for that user's role!

I am thinking that in views a permission to view the mail field is being checked when the 'fields' are populated into the view object. But, oddly enough that permission does not effect the view result as mentioned in #1.
Any thoughts on how to debug this further?

If anyone else sees this it is because view does a checkAccess before adding the field during preExecute. Since it is the mail field there is no other way to allow access to that field unless you give administer users. But, there is a patch coming out that introduces a mail field access permission.
https://drupal.org/project/drupal/issues/2799049
With patch and permission set everything works.


Custom submission handler doesn't save the node I have two form submission buttons: the normal one and one added via hook_form_alter.

I'm currently using the normal default one as a save button which updates the node content as normal.

The second one which is called submit does the same thing, but will be changing a checkbox via $form_state prior to saving the node content.

The code I'm using is the following one:

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

  if ($form_id == 'example_node_form') {

    //dpm($form);
    $form['actions']['finishbutton'] = [
      '#type'   => 'submit',
      '#value'  => t('Submit'),
      '#submit' => array_merge($form['actions']['submit']['#submit'], ['custom_submit']),
      '#weight' => 99,
    ];
  }
}

function custom_submit($form, &$form_state) {

  drupal_set_message(t('This works, but shows up after the node submit message'));

  // Shows after the node save message.
  dpm($form_state);

  // Doesn't update.
  $form_state['values']['field_nomination_submitted'][LANGUAGE_NONE][0]['value'] = 1;
}

My submission works, but the custom handler appears to be firing after the standard submission handler. Do I need to switch the array_merge order? Do I need to break this into separate functions? Do I potentially need to add a submit function inside of custom_submit?

Use [] syntax instead of Array() and switch the order ... that should work.

Credits: Shawn Matthews.


Correct way of upgrading with huge data I have a Drupal 6 site that contains hundred of thousands of node and bunch of custom and contributed modules. My problem now is how can I upgrade this correctly in Drupal 7. I tried to steps presented in DrupalCon Denver which is a good steps for me, but I have a problem in converting the data when running update.php which stops the process.

Is there any good way to handle this case?

Option 1:

Inventory your 3rd party modules as well as your custom modules. Identify those modules that has a Drupal 7 version or if it's included in Drupal 7 core.
Update the Drupal 6 core.
Update the contrib modules and themes.
Disable contrib modules.
When everything is up-to-date and contrib modules are disabled, run update.php. This process will take time depending on how big is your database.
Enable your modules and start fixing some API that is not supported by Drupal 7. Use coder module to assist you.
Check, check, check.

Option 2:

Build from scratch.
Use migrate module to migrate you Drupal 6 db to Drupal 7.


how to alter only one set of specific forms? Consider I have 3 content type. The problem is that if I use form alter in a module , when I use:

drupal_set_message(t($form_id), 'status', FALSE);

in the mentioned hook, it shows me different set of form-IDs as message on showing each node add/edit form.

For example if I go to node type A add/edit form, drupal_set_message shows:

A_node_form

if I go to node type B add/edit form, drupal_set_message shows:

A_node_form
B_node_form

if I go to node type C add/edit form, drupal_set_message shows:

A_node_form
B_node_form
C_node_form

Showing them means that I can not really make an specific effect for each content type add/edit form by form_alter.

Note: I use OG module and B and C are the content types and A is the group type.

How should I solve it?

In the case you need, so you can easily use control flow in your hook_form_alter

You know that the hook runs everytime a form is willing to be rendered, so you can easily do something like

hook_form_alter(&$form, &$form_state, $form_id){

if($form_id == 'A_node_form'){...}//alter form A

if($form_id == 'B_node_form'){...}//alter form B

if($form_id == 'C_node_form'){...}//alter form C

}


How can I check the value of an aggregated field without direct access to Solr? I'm using Search API Solr on Pantheon (which means I don't have direct access to the Solr backend), and I've set up an aggregated field in the UI.  This aggregated field is a Fulltext aggregation of a boolean field and a Countries module field, but it isn't working as I am expecting.

Search API Views allows the indexed fields to be displayed, but it does not display the values of aggregated fields.  I can filter by the value of the aggregated field, but since I don't know what the values look like in the aggregated field, I'm at a loss about what to input. So I need to check the value of the aggregated field somehow, but there appears to be no way to do this through any of the module UIs.

What I tried

I have tried running dpm() on the $view object through a views template, but as far as I can tell the aggregated fields are not stored there; they are queried on the Solr server, so Views doesn't touch them directly.

As an alternate approach, I went to the search index config page (/admin/config/search/search_api/server/MYINDEX/edit) and selected Retrieve result data from Solr, but that didn't give me the values of the fields, either.

There is a way to do this in Views.

Go to the search index config page (/admin/config/search/search_api/server/MYINDEX/edit) and selected Retrieve result data from Solr.  Then clear all caches a few times to be sure they are really clear.

After that, you can go back to the view and add the aggregated fields as Fields to the display.


Drupal 7: Views RSS module - fields not showing up So I wanted to create a custom RSS feed for my site and was told that I could use the views fields capability with this module: Views RSS. I downloaded and installed and followed the steps explained here for the basic usage. And also took a look at the minimal instructions given at the module's doc

The problem is I end up with; the fields getting picked up by the page display but the feed display returns the default with title and body fields only (regardless of other fields). Also the XML is not outputted correctly and the link. It's as if the Views RSS is not there or is not doing anything.

I have no idea why it is not working...I am think if the steps I followed aren't correct and when I try to follow what is described here I run into the same error and have no idea how the person who posted that solved it.

First think first: On a RSS feed you can't have as many <xml_tags> as you want. It's fixed-predefined for web concurrency.

Now a quick and dirty tutorial:

Enable Views RSS, Views RSS: Core Elements, Views RSS: DC Elements
Add new view without create a page or a block
Add a Display Feed
Format-> from RSS Feed to RSS feed- Fields
Fields->Add the basic fields (It will display nothing!)
Format->Settings->Item elements : core Map the fields to RSS elements (do the same for Item elements : dc)
Feed settings->Path: give a path
Save..
Browse the URL, for debug (and not fancy Chrome/Firefox styling) CURL example.com/rss


Click on a day to create an event I'm wondering whether it is possible to simply click on a Drupal calendar tile (month view) and be automatically taken to the page for creating an event. The only thing I've found that comes close to this is the event calendar module, specifically the In-place Add/Edit/View of events in pop-up functionality. However I need more control over this and want it to use my own content type for creation.

My colleague, who creates many calendar events, wanted this functionality to save time.

If you have custom module you can implement hook_views_pre_render(). It will allow you to change the views title before rendering.

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
    $title  = drupal_get_title();
    drupal_set_title(l($title,"node/add/event"));
  }
}

Not exactly but close to what you need.


Drupal and Require.js not playing nice - double load of jQuery I’ve been given a design library from a large cooperate client built utilizing Bootstrap 3 and Require.js. It’s very robust and well-built with the various scripts using Require.js to load jQuery. Problem is, Drupal has already loaded jQuery and the double load is causing some items to fail. If I remove all the Require.js calls, Drupal jQuery stuff works great. If I remove the base Drupal jQuery file, all the stuff using the Require.js stuff works great. Here’ are options I have considered:

Stop jQuery from loading with Drupal, use require to load jQuery on
every page - I haven’t tried this yet, but it just seems wrong. I
think I can remove jQuery with hook_library_alter() in my theme?
Wondering if anyone has tried this… My front end and admin screens
actually use 2 different themes, so I think I'd have to modify both.
Stop jQuery from loading with Require.js – I tried this and none of
the other libraries that are loaded with require.js can find query
if it’s not loaded with  Require.js, so I don’t think this option
works. This is my first time using require.js so maybe there is some
fun fix for this I haven't figured out?
Add all libraries to the site with Drupal – This seems like a lot of
messy work as I would have to remove all the require.js dependencies
in the library, and there is an expectation that we not modify the
library/framework so implementing new releases is easy.

Any other recommendations?

I would try option 1. Require JS is pretty demanding in terms of getting all the dependencies right, so unless you want to debug that I'd load the Require JS version.

The place to look is: https://www.drupal.org/node/756722 where all this is explained.

Basically I think you should (for D7) define the Require JS stuff as a library using hook_library like so:

function hook_library() {
      $libraries['vertical-tabs'] = array(
        'title' => 'MY_STUFF',
        'version' => '1.0',
        'js' => array(
          'PATH/require_stuff.js' => array(),
        ),
        'css' => array(
          'PATH/bootstrap_stuff.js' => array(),
        ),
      );
      return $libraries;
    }

And on hook_init add it like so:

drupal_add_library('system', 'vertical-tabs');

And replace the core version of Jquery with hook_js_alter:

function hook_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/jquery.js'; // Swap out jQuery to use your version.
}

I wouldn't worry too much about sticking with the Drupal version of Jquery as it is very common to use the jquery_update module to replace it anyway.


How to change theme colors based on time of day for Adaptivetheme (or other theme that allows user-selectable colors)? I'm using a custom subtheme of the Pixture Reloaded subtheme of Adaptivetheme.  I want to change the theme colors based on the hour of the day.  (I want a "day" theme and a "night" theme.)

I know that I can do this with the Themekey module, which allows you to specify rules for which theme to use.  You can make a rule based on the time of day and have two different themes, but then I will have to maintain two entirely separate themes.  Since all I want to change is the colors, taking this approach would be a maintenance nightmare.

Pixture Reloaded uses the Color module to allow users to select the colors, so I don't understand how to easily override it.

One thing I noticed is that there are a number of pre-defined color schemes.  For my purposes, it would be sufficient to have a way to automatically use one pre-defined scheme during the day, and another at night.

How can I do this without creating (and maintaining) a copy of my original theme?

Place the following code into your theme's template.php file.

/**
* Implements template_preprocess_html().
*/
function YOUR_THEME_preprocess_html(&$vars) {
  // Day / night background theming.
  $hour = date('G');
  $theme = 'day';
  if ($hour <= 6) {
    $theme = 'night';
  }
  elseif ($hour >= 6 && $hour <= 18) {
    $theme = 'day';
  }
  elseif ($hour >= 18) {
    $theme = 'night';
  }
  $vars['classes_array'][] = $theme;
}

Now your <body> tag should have the CSS class 'day' or 'night' depending on the current server time.

An example CSS code would look like:

body.day {
  background: #fff;
  color: #000;
}
body.night {
  background: #000;
  color: #fff;
}

for more info check this tutorial.


How to make a "term reference" > "taxonomy vocab" display alphabetically in a content type? Hello I have a content type that has a field type > term reference using the "Check Boxes/radios buttons" widget.

When adding content using that content type the checkboxes (which are of course being populated by a taxonomy) arn't being displayed in alphabetical order which will be difficult for my client to use. I've tried setting the taxomony to alphabetical but that doesn't seem to have any effect on its display within the content type.

Help appreciated :)

Change the order (weight) of the terms within the vocabulary to be alphabetical.

I've just tried this and it works in D7.23 using a 'Term Reference' field. To test this I ordered terms into non-alphabetical, saved the vocabulary, then created a node. Terms were in the order I'd specified. I then 'reset to alphabetical', saved the vocabulary and created a node. Terms were now in alphabetical order.

I found your question title confusing as it talks about terms reference but then the question itself mentions node reference. Please edit the question and clarify.


Cant show Commerce Products in View on Taxonomy Term page My Commerce Products (not Product Displays) have a term reference field. On a taxonomy term page I want to show all the products tagged with that term.

If I create a view to show prodcuts (which I would attach as a block), I cant seem to use the term ID from the contextual filters to limit the results.

If I create a view of terms, then I cant find the relationship and fields to show the products.

Am I missing something or is this how Commerce Products work? Are they not available in Views the same way that nodes with the same term field would be?

This isn't an official source, but it might help you.

Don't attach a block on your taxonomy page. Instead, create the View as a page and set the URL (under path) to override the the taxonomy term page (e.g. taxonomy/term/%).

Under contextual filter use : Content: Has taxonomy term ID

For the filters, use the settings in the screen shot (in the screenshot, my taxonomy terms belong to a vocabulary called Shop Categories).

Hope that helps!


Simplenews send mail when specific content is created Required: Simplenews module in drupal7.

I have a content type student on my site. The student can be from department: Engineering, Management,....

What I want to do is whenever I add a student who is from engineering, a mail is sent automatically to subscribed users. I read about the simplenews module and already tried to send some mails which were received successfully.

What I can't do and am not finding information about is how to 'link' the term engineering in department to newsletter and then send a mail.

One reasonably straightforward way of doing that is with the Rules module.

Assuming there's only a few recipients, not hundreds...

You can use a "Send email" action to conditionally send an email to specified recipients.

Here's some example Rules that can be imported.

1. Basic "Send email" rule

{ "rules_send_email_notification_engineering" : {
    "LABEL" : "Send email notification (engineering)",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Mail" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_department" } },
          { "data_is" : { "data" : [ "node:field-department" ], "value" : "engineering" } }
        ]
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "example@example.com,example2@example.com",
          "subject" : "New student record created [engineering]",
          "message" : "Sample message"
        }
      }
    ]
  }
}

You could also use the "Send mail to all users of a role" action in Rules to send to all users assigned to the "Engineering department" role, if such a role existed.

Update:

2. Create and send a simplenews newsletter with Rules

Here's how to create and send a newsletter with Rules:

{ "rules_send_email_notification_engineering" : {
    "LABEL" : "Send email notification (engineering)",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Mail" ],
    "REQUIRES" : [ "rules", "simplenews_rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_department" } },
          { "data_is" : { "data" : [ "node:field-department" ], "value" : "engineering" } }
        ]
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "simplenews",
            "param_title" : "New engineering student record created.",
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "entity-created:status" ], "value" : "1" } },
      { "entity_save" : { "data" : [ "entity-created" ] } },
      { "simplenews_rules_action_send" : { "node" : [ "entity-created" ] } }
    ]
  }
}

You can set other field values on the newsletter node as required with the data_set action.


Data in field_revision with Create new revision unchecked The field_data_myfield and field_revision_myfield have the same row entries (D7 fields). All of my content types have the "Create new revision" unchecked. Is this how it's suppose to work? If yes, two questions 1) is this okay for scalability and 2) how do I stop drupal from renaming the files with _0 even when the original is deleted -- I read that this is because revision is on. If it's not suppose to work this way, how do I fix it.

I'm using mysql.

To clarify the end goal, I don't want the entire field deleted, I would like the fields not to track data revisions. Currently if field_body is updated, it also tracks it in field_revision body. Ideally, drupal would only save the update in field_body, and field_revision_body would be left empty. The content type is marked to not track revisions.

Is this how it's suppose to work?

It depends on which storage backend you use. The default sql backend works this way.

It shouldn't effect speed (much) but will instead effect data storage which usually isn't a problem.
Drupal will not completely delete a field, but instead mark it as deleted. If you want to completely delete it, you need to delete it from the field_config and field_config_instance tables.


How do I enable PHPUnit testing for a sandbox project on drupal.org? This questions is specifically about my sandbox project. I have PHPUnit running on other full projects that I maintain.

I have created a sandbox project, fully uploaded to drupal.org, for 8.x and 9.x testing. But there is no "Automated testing" tab on the project page, like there is with full projects. What has to be done to enable testing on drupal.org?

The project has a composer.json, .info.yml and drupalci.yml. My phpunit tests run locally. Everything looks fine. I have searched drupal.org docs https://www.drupal.org/node/1011196 and it does not say that phpunit testing is not available for sandbox projects.

Given the following comment I found on Can enable tests for sandbox projects, testing is disabled on sandbox projects, which means you cannot enable automatic tests on sandbox projects.

  From pift_project_visibility():

if (!empty($node->field_project_has_releases[LANGUAGE_NONE][0]['value'])) {
// Ensure user has the 'access project testing tab' permission
if (user_access('access pift project testing tab')) {
  return TRUE;
}

  }

  So as long as the releases piece is taken care of, the 'enable' checkbox should never appear (and thus users will not be able to enable testing).

The issue has been created in the project that handles the automatic testing for projects hosted on drupal.org. The comment says that the automatic tests are enabled for the projects with enabled releases. Sandbox projects don't have releases enabled, so also the automatic tests are disabled.

As Drupal.org Git administrator I can confirm that none of the sandbox projects has the Automated testing tab, which I instead see on full projects. (It's not a matter of permissions, as my role on Drupal.org allows me to set automatic tests for any project.)

To answer How did you enable automated testing on this sandbox project? that project has automatic tests enabled because it's a full project, despite the project name. I can say that because the path alias automatically set for a sandbox project is similar to https://www.drupal.org/sandbox/grayside/1876908, the path alias for the #Heading module. Furthermore, a sandbox project has a Promote tab as in the following screenshot.

For the other project, this is what I see.


Alter default value for field settings (allowed_formats) Please how can I alter the default field settings whenever a new field is added?

NB I am not asking how to set the default whenever a new entity is added.  This is about changing the pre-populated values on the page "Administration->Structure->Content types->XXX->Manage fields->Add field when a field is added"

NB This question is for D8.  In D7 the answer is to use hook_field_info_alter.

Specifically I am using the module allowed_formats, and I would like every new text_with_summary or text_long field to have defaults of:

Allowed formats = "Basic HTML" only
Form display settings "Hide the help link About text formats." and "Hide text format guidelines." enabled.

The defaults need to work even if the new field is created in code.  In particular it's important to work for the Body field that is created automatically on a new content type.

I'm struggling because looking at the code, the defaults come from the public static function TextWithSummaryItem::defaultFieldSettings and there doesn't seem to be any hook.

Thanks to @Berdir and @4k4 who helped me out several times - I just followed their ideas, tested and wrote up the answers.

This first hook alters the field settings.  I've included a second example for image settings.

/**
 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
 */
function MYMODULE_field_config_create(FieldConfigInterface $field) {
  if ($field->isSyncing()) return;

  switch ($field->getType()) {
    case 'image':
      $field->setSettings(['file_directory' => 'images', 'max_resolution' => '1080x1080']);
      break;

    case 'text_with_summary':
    case 'text_long':
      $field->setThirdPartySetting('allowed_formats', 'basic_html', 'basic_html');
      break;
  }
}

This second hook alters the form display settings.  The array_diff_key command is used to determine which fields are new.

/**
 * Implements hook_ENTITY_TYPE_presave().
 *
 * Override field form display defaults used when a field is added to a content type.
 */
function MYMODULE_entity_form_display_presave(EntityFormDisplay $display) {
  $fields = $display->getComponents();
  $origFields = (isset($display->original)) ? $display->original->getComponents() : [];
  foreach (array_diff_key($fields, $origFields) as $newField => $settings) {
    switch ($settings['type']) {
      case 'text_textarea_with_summary':
      case 'text_textarea':
        $settings['third_party_settings']['allowed_formats'] = ['hide_help' => '1', 'hide_guidelines' => '1'];
        $display->setComponent($newField, $settings);
        break;
    }
  }
}


Passing multivaluearray from php to javascript after ajax call The passing of the array works only one time. After an ajax call the new array is not passed to drupalSetting only the 1st array will displayed multiple times in the console. I tried it with a static test array, with a dynamic array, with json_encode() and such other things.

My PHP script:

$form['#attached']['drupalSettings']['variable'] = $vars;

devel:

Array (
    [0] => Array (
            [0] => val1
            [1] => val2
            [2] => val3
        )
    [1] => Array (
            [0] => val1
            [1] => val2
            [2] => val3
        )
....
)

My jQuery script:

(function($, Drupal, drupalSettings) {
    Drupal.behaviors.vShop = {
        attach: function (context, settings) {

            var loadVar = function(event, request, settings) {
                var varArr = drupalSettings.variable;
                console.log(varArr);
            };

            $( document ).ready(loadVar);
            $( document ).ajaxComplete(loadVar);
        }
    };
})(jQuery, Drupal, drupalSettings);

console:

Object { 0: {…}, 1: […] }

I think the main issue is that the drupalSettings.variable don't get the new array from the form after the ajax call.The attached values in the form are changed correctly.

I searched on the wrong position, after i found:
http://www.thecarneyeffect.co.uk/drupal-8-ajax
I got the solution here
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21SettingsCommand.php/class/SettingsCommand/8.2.x

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\SettingsCommand;

function ajaxCallback(array &$form, FormStateInterface $form_state) {

    $form_state->setRebuild();

    $myValue = $form_state->getValue('myValue');

    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new SettingsCommand([
       'variable' => $myValue,
    ], TRUE));

  return $ajax_response;
}


Multilanguage setup breaking View results layouts Background:

We're trying to setup multilanguage options on our site (to allow English/Welsh options). We're using the Internationalization module primarily, with the language detection set to URL.

The problem:

The static content pages work fine, but when a page containing views is translated it seems to break the order and div styling of the Views results.

Any ideas what might be causing this (e.g. have I missed a setting in the Block/View somewhere to apply a div style to the translated version of the page)?

E.g. see below - in pic 2, the results are wrongly shown single column rather than in a 4 column grid, and are displayed before the rest of the main content rather than after):

Comparison of default (www.../resources) and translated (www.../cy/resources) page layouts

Turns out this was due to an error in the logic of a custom template not taking in to account variable languages.


How to embed a block (with title) in a template file? I've created some blocks (not related to any other module, just through the "add block" option) and I am attempting to call them in the correct places in my homepage template.

I found the following code:

$block = module_invoke('block', 'block', 'view', '1'); //where 1 is block delta
print $block['content'];

But this only allows me to display the block content. Is there a way to get the block title too? I did find some people using $block['title'] or $block['subject'] but my $block array only seems to have the content in and nothing else.

Apologies if this is a common question but I couldn't seem to find an answer for the life of me!

http://drupal.org/node/26502 - A nice write up on displaying a block using code. There are a couple of examples toward the bottom that show displaying the entire block (including the subject).

One in particular you could try, using Drupal's theme() function:

<?php
    $block = (object) module_invoke('[target_module]', 'block', 'view', "[target_block_ID]");
    print theme('block', $block);
?>


Getting logged out all the time This has been happening since first started using drupal a year ago and I see others having same problem with no real answer beyond cache.

If you reload it will log you back in but that is no good for users, they will just be confused and frustrated by it and it would seem stupid to put a warning "please keep refreshing your page if you are logged out".

I remember at one stage being told you need to decide between www or no www to stop this from happening but that never really worked, only sometimes.

There must be a logical explanation and definitive way to stop it, surely?

I would imagine that if your users can just refresh the page to become logged back in, that they're almost certainly not being logged out in the first place. Far more likely that they're being served a cached version of the page.

Consider this situation:

User visits home page as an unauthenticated user
Cache headers tell the browser to keep that page for at least x minutes before refreshing
User visits the login page and authenticates.
User re-visits the home page
The browser cache kicks in, and the user is shown the cached version of the home page they saw the first time round
User refreshes the page - the browser cache is cleared, and they now see the index page as an auth'd user

  There must be a logical explanation and definitive way to stop it, surely?

Absolutely there will be - but you need to identify which part of your setup is responsible for the problem. As described above, it's probably a caching issue, so that's where you debugging should concentrate. I've seen this sort of behaviour more often when a reverse proxy is in front of Drupal, so if you have one enabled, start debugging that first.

If you're not comfortable debugging caching issues in that manner, you'll really need to hire someone who is to do the job. It's not something you can do half-heartedly, or without a reasonable knowledge of caching in general (not just in Drupal). If you happen to have a Pantheon account, ask them about it - they plugged the same bug in their Varnish config some time back (I have no idea how though, didn't ask).

I'm not sure that any more specific advice can be really be given, without having access to the server. I'm by no means a caching ninja though, so maybe someone else will be able to offer a specific part of config you can change, test you can do, etc.


Get Link value in Media entity We have a Media type called Documents that has a Link field called field_link. We need to obtain the URL (external or internal) from the field so that we can use to wrap block elements inside of a  tag in our twig templates. All works fine when the link is an external URL, but when linking to an internal page, the following code does not work in our mymodule_preprocess_media hook.

How can I obtain both the internal and external link within the field_link field inside of the mymodule_preprocess_media hook?

This is what we have tried, but only works for external links.

function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  $link = $media_entity->get('field_link')->first();

  // This works for external, but not internal
  $link_value = $link->getUrl()->getUri();

  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}

media--document.html.twig

{{ name }}

When using ksm($link->getUrl()), we find that the uri value is NULL when the link is internal.

Goals:

Get the internal link (absolute) using hook_preprocess_media
Get the external link using hook_preprocess_media

Try the following:

/**
 * Implements hook_preprocess_media().
 */
function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  /**
   * @note: in case your field not multiple, otherwise loop through the field.
   */
  $link = $media_entity->get('field_link')->first();
  if ($link->isExternal()) {
    //- External.
    $link_value = $link->getValue()['uri'];
  }
  else {
    //- internal.
    $link_value = $link->getUrl()->toString();
  }
  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}


How to delete system menu links I want to remove the "My Account" and "Log out" menu links, as I've incorporated those into other parts of the page.

Now, I'm a Drupal novice so if I'm making rookie mistakes here go easy!

What I've tried is something like this in my module.install file

function mymodule_enable()
{
    menu_link_delete(null, 'user');
    menu_link_delete(null, 'user/logout');
}

Now - that doesn't work as those two menu links are 'system' links. I tried to brute force this by creating a variant of menu_link_delete which forces deletion, by passing "true" to the $force parameter of _menu_delete_item...

function force_menu_link_delete($mlid, $path = NULL) {
    if (isset($mlid)) {
        _menu_delete_item(db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc(), true);
    } else {
        $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $path));
        foreach ($result as $link) {
            _menu_delete_item($link, true);
        }
    }
}

When my module is enabled, that does successfully delete the relevant rows of the menu_link table, but by the time the Drupal has finished working its magic they have reappeared in the table!

The reason of course is that the user_menu() hook goes and reestablishes them. I wondered if removing them with a menu_alter hook would work...

function mymodule_menu_alter(&$items) {
    unset($items['user']);
    unset($items['user/logout']);
}

Sure enough, they disappear, but so does the actual capability to logout!

So - I'm going about this the wrong way. I'm guessing I shouldn't try to delete the menu links themselves, but somehow prevent my theme from displaying them.

Pointers are very welcome....

Not sure if this is the correct approach, but it worked - I used a menu_alter hook to move the menu items to a different menu.

function mymodule_menu_alter(&$items) {
    $items['user']['menu_name'] = 'unused-menu';
    $items['user/logout']['menu_name'] = 'unused-menu';
}


How to handle large taxonomy Have a page on website where exposed filter is hierarchical taxonomy (Country/City). Works fine with few terms, just for test. Page loadtime is 1.5ms, choosing terms goes in blink.

Now i imported all Europe countries and cities, around 5000 terms. Page loadtime is 21s.
Choosing first term (parent/UK) took 8 seconds. Choosing 2nd term (child/London) took 8 seconds.
I am using views exposed filter http://drupal.org/sandbox/ser_house/1832320.

I am aware that this module is far from done but from what i found out reading about taxonomy is that Drupal handles large taxonomies very bad.

All countries and cities will be around 20.000-30.000 terms and i except several users using the filter at same time which is not an option with loadspeed so high.

Any help how to handle this (maybe another module?) would be greatly appriciated.

If still relevant, you can try out Taxonomy Edge.

It has optimizations for taxonomies in general, and also implements views filter/arguments for taxonomies.


Pre-process node type for each node and print within region.html.twig template I'm trying to figure out how I can check the node type/content type for each node using pre-process and print it on a region template (region.html.twig)

It seems to be returning NULL

function iom_preprocess_node(&$variables) {
    $node = $variables["node"];
    $variables['content_type'] = load($node->bundle())->label();
}

{{ content_type }}

You need to use preprocess region:

function iom_preprocess_region(&$variables) {
    $node = $variables["node"];
    $variables['content_type'] = $node->getType();
}

Clear/flush cache after adding it.


Adding a new content type programmatically in .install file or .module file? There are 2 different ways to create a new content type programmatically.

First one, which I also use, is to create it in your custom module's .install file in hook_install() using node_type_save() and attaching the fields also in hook_install() with field_create_field() and field_create_instance() .
The second one, which in Node Example module is used, is to create it in your custom module's .module file using hook_node_info() and creating and attaching the field instances in hook_node_type_insert()

I am preferring the first method, since my feelings say that is better to maintain (i.e. adding/updating new fields via hook_update_N()) and it suits better in .install file. But, I keep myself asking why it is done other way in Node Example module.

Does anyone know the CONs and PROs of using both methods to create a new content type in code?

Some hooks, like hook_delete are only called on the module that defines the node's content type. If you save content type to a database using node_type_save(), it might not be recognized as "defined by module" - it acts as content types created by user. Unless, of course, you will set $info['module'] to point at your module - in that case created entries should work the same way.