hook_menu not producing expected tab structure, problem? I'm trying to create a tabbed menu system with hook_menu() following the hook documentation and Clive's answer. I am using the following code.

/**
 * Implements hook_menu().
 */
function newforms_menu() {
  $items = array();
  $items['admin/config/content/newforms'] = array(
    'title' => 'NewForms',
    'description' => 'Configure web forms via drag and drop.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newforms_administration_settings'),
    'access arguments' => array('administer newforms module'),
    'file' => 'newforms.admin.inc',
  );

  $items['admin/config/content/newforms/list'] = array(
    'title' => 'Forms',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/config/content/newforms/components'] = array(
    'title' => 'Components',
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array('newforms_components_list'),
  );

  return $items;
}

I would expect this to produce two tabs, labeled 'Forms' and 'Components', but it does not. I see no tabs.  On admin/config/content/newforms/list, I get the same page as admin/config/content/newforms; on admin/config/content/newforms/components, I get "You are not authorized to access this page."

I've cleared cache and ran cron, disabled the module, uninstalled it, reinstalled it, cleared cache, and ran cron; I get the same results.
Both callback argument form functions are defined in newforms.admin.inc.

Do you have any idea as to what is going on here?

So this works:

/**
 * Implements hook_menu().
 */
function newforms_menu() {
  $items = array();
  $items['admin/config/content/newforms'] = array(
    'title' => 'NewForms',
    'description' => 'Configure web forms via drag and drop.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newforms_administration_settings'),
    'access arguments' => array('administer newforms module'),
    'file' => 'newforms.admin.inc',
  );

  $items['admin/config/content/newforms/list'] = array(
    'title' => 'Forms',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/config/content/newforms/components'] = array(
    'title' => 'Components',
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array('newforms_components_list'),
    'access arguments' => array('administer newforms module'),
  );

  return $items;
}

I think there were two things happening.  I have two theories.  One was that Drupal essentially saw two identical tabs and said "this is dumb I'm not doing this" and didn't render the components tab.  The other theory is that as soon as Drupal saw a different page argument for the second tab (components), it demanded an access arguments specification.  I'm not sure which is true, if both are true, or if both are wrong, but this works.

The moral of the story is that things in hook_menu don't inherit the way you expect them to sometimes.

EDIT:

This is straight from the hook_menu documentation.

// Make "Foo settings" appear on the admin Config page
$items['admin/config/system/foo'] = array(
  'title' => 'Foo settings',
  'type' => MENU_NORMAL_ITEM,
  // Page callback, etc. need to be added here.
);
// Make "Tab 1" the main tab on the "Foo settings" page
$items['admin/config/system/foo/tab1'] = array(
  'title' => 'Tab 1',
  'type' => MENU_DEFAULT_LOCAL_TASK,
  // Access callback, page callback, and theme callback will be inherited
  // from 'admin/config/system/foo', if not specified here to override.
);
// Make an additional tab called "Tab 2" on "Foo settings"
$items['admin/config/system/foo/tab2'] = array(
  'title' => 'Tab 2',
  'type' => MENU_LOCAL_TASK,
  // Page callback and theme callback will be inherited from
  // 'admin/config/system/foo', if not specified here to override.
  // Need to add access callback or access arguments.
);

The second to last line is what tripped me up.  For every MENU_LOCAL_TASK you must add an access callback/access argument.  Mystery solved.


Incorrect Drupal 8 Breadcrumbs I'm trying to add the page title to the breadcrumbs for each page, unfortunately my breadcrumbs are not updating with current page title. All sibling pages in the menu show the same breadcrumbs.

For example, all these pages will show the same breadcrumbs:

Home > About Us > Our Team
Home > About Us > Our Mission
Home > About Us > Another Page

Whatever page you visit first, you will get the breadcrumbs for that page on all of the above pages. So if you visit the "Our Team" page first, you will get the "Our Team" breadcrumbs on the "Our Mission" and "Another Page" pages as well. The same happens for 2nd level pages.

So if you visit

Home > About Us

You will get the About Us breadcrumbs on

Home > Services

However, you will not get the Home > About Us> Our Team breadcrumbs on

Home > Services > Service A

I have this code in my .theme file:

function themename_preprocess_breadcrumb(&$variables){
   if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
       $variables['breadcrumb'][] = array(
                 'text' => $node->getTitle(),
                     'url' => $node->URL()
                   );
   }
}

And this for my breadcrumbs template:

{% if breadcrumb %}

{{ 'Breadcrumb'|t }}

    {% for item in breadcrumb %}

        {% if item.url %}
          {{ item.text }}
        {% else %}
          {{ item.text }}
        {% endif %}

    {% endfor %}

{% endif %}

I'm guessing it's some sort of caching issue, as it seems to happen per-session (different users will get stuck with different breadcrumbs depending on which pages they visit first).

Anyone know why this may be happening?

I ran into the same issue

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

function my_theme_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    /** @var \Drupal\node\NodeInterface $node */
    $variables['breadcrumb'][] = [
      'text' => $node->getTitle(),
      'url' => $node->toUrl(),
    ];
    $variables['#cache']['contexts'][] = 'url';
    $variables['#cache']['contexts'][] = 'session';
    $variables['#cache']['contexts'][] = 'user';
  }
}

So:

$variables['#cache']['contexts'][] = 'session';
$variables['#cache']['contexts'][] = 'user';
$variables['#cache']['contexts'][] = 'url';

did the trick for me.


Drush does not download modules correctly Drush says it downloads a module successfully but instead of putting it in sites/all/modules it puts it in the current directory:
$ drush dl module_filter
Project module_filter (7.x-2.0-alpha2) downloaded to                 [success]
/drupal/module_filter.
The folder doesn't exist, but if you run the command again the following happens:
$ drush dl module_filter
Install location drupal/module_filter already exists. Do you want to overwrite it? (y/n):

drush version 7.x

Drush will put downloaded modules in the current directory if it cannot bootstrap a Drupal site.  Run drush status to determine whether or not the Drupal site you think you are operating on is recognized by Drush.  You might need to use the --uri option to specify the name of the folder that contains the settings.php file, or set up a Drush alias file.


Alter label with token I am trying to build a questionnaire that simply replaces (alters) the label of a list field. I am doing so by replacing a token from views (embed) and implementing hook_form_alter() in a separate module.
How can I save that value and write it to the database?
I am using an Entity form and a list-field.
This is the snippet I am struggling with, found on Store token replacement values in the database rather than tokens themselves.
function question_to_label_node_presave($node) {
  if ($node->type == 'page') {
    $replaced_text =  token_replace($node->field_question['und'][0]['value']);
    $node->field_question['und'][0]['value'] = $replaced_text;
  }
}

I am currently trying to run this in a custom module, but I cannot find the right content type for the Entity form. I am using the Devel module to find the right array value.

I´ve solved it by using a token, and placed that token (from a view) in a hidden field in that form - thus saving that value.

The same token generated from views - I used to alter the label for that question with "hook_alter_form".

A kind of non programmatically way of solving the problem.


How to update all hyperlinks which are in the content Hello I am using book_copy module for creating a new version of the book so i have copied a book which is having more than 1000 pages with the book copy module.
Now the new book copy has all working links but for the new book i needed the new urls.
like for previous book it was content/2012 now i needed content/2013 which i have done with pathauto but problem is that while copying a book it takes url for pages as content/2013 but in the page there are hyperlinks which are not updated and pointing to old book pages.
 So let me know if any module for fixing this issue o/w i need to go on each link and update it which is really a difficult task.

Export the database, run a find and replace over the dumped sql and re-import it.

e.g.:

#1 mysqldump ... > output.sql
#2 copy output.sql to output_mangled.sql as a backup
#3 perl -pi -e 's/content\/2012/content\/2013/' output.sql
#4 cat output.sql | mysql ...

Replacing ... with authentication and database specification parameters.

To be safer, make the regular expression in the replacement step more specific.


View Rewrite results Inline CSS for Newletter I am trying to send a HTML newsletter with the simplenews plugin using views.
The mailing of HTML via the plugin works flawlessly (after tinkering). I included a View via the Twig Tweak plugin inside the corresponding twig template.
My main problem is very similar to this but for Drupal 8. HTML mails require (as far as I know) inline CSS to be displayed correctly in the majority of mail clients. As I use a View, inline CSS get stripped away ("sanititzed" for security I guess).

Is there any possibility for me to use Views with inline CSS as in Drupal 8 I couldn't find the correct line of code to disable this "sanitisation"?

I've been looking into this problem myself for several days, and my conclusion after going through the views code is that views is absolutely dead-set on sanitizing certain data (specifically twig template fields for custom field rewriting) not even writing your own templates can fix that.

Ultimately, my work around for this was to use Display Suite to build a custom display for my node type (which lets me use tokens in custom display suite fields) and then telling views setting up views to output Display Suite content instead of Fields.


Remove entities programmatically from view results before pager is generated I want to remove certain entities from the view results (Views core module), before the view's pager is generated.

By now I am doing it in hook_views_post_execute(). The problem here is, that the number of results on the view pages is different then. There should be 10 results per page and not 7, 8 or 6 etc.

I do not want to create a views filter, which would require manual interaction from the user inside the views interface in the webbrowser.

I have tried also hook_views_query_alter(). The problem here is, that my module's class methods are processing entity id's (node id's in particular). It might would work with the SQL NOT IN statement, but this is probably a problem for bigger site's and a huge performance impact. Since I need to iterate over all entity id's from the site and check access then.

My questions:

Is there any method inside the Views module, which allows me to
remove the entity id's from the view results or shall I really use
hook_views_query_alter()?
Also - if it comes to the hook_views_X
methods - isn't there any more elegant class method or event? Since
hooks are a mostly deprecated way in Drupal 8.

Thanks for your attention!

You need to alter the query in one way or another, that is the only way the pager can work.

Sounds like you are using nodes, then you can use the node access grant system. Basically, it allows you to "index" the access checks and assign attributes to the nodes, like the group they belong to. And then there is a second hook, that allows you to define what groups (or whatever it is in your case) the user has access to. This will then be combined into a query for you.

Be aware that this is one of the most complicated systems in Drupal, but if you can't do the access check directly as part of the query (like checking the value of a certain field), then this is the only way.


How to create new group for products in drupal commerce? I am using the Drupal Commerce module (in Drupal 7) for products.

I need to create different-different group like phone and shirts. And need to add parameters for phones.

Also I need variation by using taxonomy.

Please refer to the image below for more details:

Some more details:

I am using 2 attributes: Color and Memory, implemented as taxonomies (vocabularies). But they are not showing as a select list on the cart page.
Color is a vocabulary, with terms in it like black, silver and red.
I added Color on product type fields and checked 'attribute option'.
But still this widget not showing up on the cart page (it's only showing the selected value).

Or to phrase it in yet another way: I need attribute on cart page. I have added attribute by using taxonomy, but it's giving me only a link. Which means that when I select 'black', then it only shows 'black color' on the cart page (it does not show a 'select option').

I guess you need to create a new product type (since you want to add "parameters", which I assume are "fields") :

/admin/commerce/products/types/add

Then add fields to your new product type (picture, size, screen resolution for phones...), choose chich fields will be used as attributes (like size for shirts), then create products using this new product type, then create a new product display (which is a regular node with a multiple product reference field) for this product type and reference your products with the product reference field on the product display. You can also use an existing product display to display all your types of product (in this case you have to allow the product display's product reference field to reference products of the new product type first).

Note that if you have several attribute fields, you need to create as many products as there is possible combinations. Say you have 3 sizes (S, M, L) and 2 colors (red, blue), you need to create 6 products :

S blue
S red
M blue
M red
L blue
L red

You may consider using Commerce Product Option or similar module for your use case.

It can be confusing at first, but the Drupal Commerce way of dealing with products is really effective.

Good luck

EDIT

To make a field act as an attribute on your add to cart form (i.e shirt sizes : a drop down with XS, S...), you need to define a field on your product type (see my URL), then on the manage field form (admin/commerce/products/types/your_product_type_machine_name/fields/your_field_machine_name), you need to check the checkbox "Enable this field to function as an attribute field on Add to Cart forms".

Then you create your product, one with size S, one with size M, one with size L (so you have 3 products, one per size), on your product display you set up references to the 3 product variations (S, M, L), and there it is, on your product display page you'll find a drop down allowing to choose the size in the add to cart form. When selecting a size, the node fields are refreshed with AJAX (you can see it as an AJAX product selector).

This system allows you to have different SKUs and prices for each variations. Typically, everything that needs to be different across products variations (SKU obviously, but maybe price, maybe the product picture) needs to be represented by a field on the product (each product has its own field value). Everything that is the same across product variations can be represented by a field on the product display (which is common to several products.

See here for official doc.

Hope it helps and sorry for my english, not my first language.


Display content type in a tab of user profile I have created content type "Bloggers", with few fields -

first name
last name
picture

Now i want to add this content type to user profile, so only admin can change information about user. I want to see a tab called Blogger Bio near VIEW, EDIT etc...
Basically i want to add (content type)Bloggers information to each user with a certain role and see this information in a tab in user profile and also edit this information.

It sounds to me like you are trying to re-create what is essentially a combination of Profile2 and Field Permissions

Profile 2

  Designed to be the successor of the core profile module, which is
  deprecated for Drupal 7. In contrast to the deprecated module this
  module provides a new, fieldable 'profile' entity - leverage the power
  of fields!

Field Permissions

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


Module for Integrating jQuery UI Multiselect Widget I am using the jQuery multiselect widget on another non-Drupal project and I would love to be able to use it with CCK in Drupal 7. I have found this module for CCK multiselect but it is not exactly what I want. I realize I could try to write something, but I was curious if anyone has used the above with Drupal before or if there is a module out there I'm missing.

Not quite what you are requesting but thinking that chosen might be a good alternative to what your searching for.


Get field value in an entity form validation In an entityform "form_alter" function I have $form_state with all the info inside I need.
I could "hard-code" the language, but this is a multi language site...
The information needed is at: $form_state['values']['field_myone']['en'][0]['value']

I'm aware of field_get_items or entity_metadata_wrapper, but I can't get either one to work.

This doesn't give me a wrapper back:

$wrap = entity_metadata_wrapper('entity_form', $form_state);

And this one doesn't work either:

$val = field_get_items('entityform', $form_state, 'field_myone');

Any help out there?

Thanks!

I am also interested. Please post the answer if you solved.

This code:

$node = node_load($form_state['node']->nid;);
$node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

solves in case you are editing a previously saved node (and the nid is then existing).


Display the exclude dates on a node I have a Drupal 7 site with a content type called Weekly Repeating Event, and events of this type repeat at the same time and day each week.  I use a custom template file to display this node type by printing the fields, e.g.

print render($content['field_event_date'])

I understand how to use display types and how to make the repeat rule display, but for the life of me I cannot figure out how to display ONLY the dates that we list as "Exclude Dates."

I want the node to have a heading that says "No Meetings on the Following Dates" and to display any future dates from NOW (date the node was viewed) that the group is not meeting.

I can't figure out how to create a view of this, nor can I figure out how to make this happen within the template file.

All help appreciated.

What about doing this using views.

You can create a view that lists all nodes of your event type, and then add a filter that sorts on the excluded field.

If you are not familiar with views in D7 there is a great guide here.

I hope it helps you out.


How to show a list of users based on taxonomy? I want show a list of users by selecting taxonomy.
and also I wanted to add taxonomy field in users profile/registration form and I did this with  profile_taxonomy module.

Suppose I have different taxonomy like "Technology","Eduaction","Stocks" then by clicking on any of this I want the list of users who had selected the same taxonomy.
I can get the list by visiting user profile and then by clicking on taxonomy i can get the same list. but i want to make seperate page for it where the list of taxonomy vocabulary is shown.
Please suggest solution.
I am extremely new to Drupal and also I am not a PHP programmer.
I am using Drupal 6

First a little clarification of term meanings.  Taxonomy is a module that manages groups of terms gathered in Vocabularies.  You have probably created a vocabulary with the terms you listed in it.

To make your list you will use Views.  I am using D7 and V3, so I cannot give you a button by button instructions, but they are similar.

Add a new view.
Define the settings for fields and add a field for the User:name.  To do this in D7 you must add a relationship to the content author to expose the User Name field.  I don't think this is needed in D6.
Delete the node title field.
Set the path to a unique URL such as Group-Type/%/users.
Create an argument to filter the URL input '%' by a taxonomy term ID based upon the vocabulary you are using for the selection terms.

When you enter a URL such as Group-type/stocks/users, The view should be used to generate a list of Users with that term.

A cautionary thought:  I have not used D6 version of Views so I don't know its idiosyncrasies.  You may have to use the term id (tid) for 'stocks' since Drupal has changed a URL from an alias to a tid by the time the URL is passed to the argument section of the module.


Changing Menu Path to node/edit Is it posible to make a copy of primary menu with changed paths?

For example instead of node/56, I need to rewrite the path to node/56/edit.
The purpose of this is to have the new menu in my Admin Panel, so the site administrator can click on a link to go directly to node edit page.

Ok, I've got it. I'm using:

Menu Node API -- to manage relationships between node ids and menu items;
and Menu Node Views -- to make View of type 'Menu tree'

I then made a new view with these settings (called primary_link_in_admin):

Filter - Menu: Menu name = primary-links (or whatever you need)
Sort criteria - Menu: Weight asc
Fields -

Menu: Link path  - Exclude from display
Menu: Link title  - with overridden values - Output this field as a link → Link path: [link_path]/edit

So I have my Primary Menu in the admin section of the site and a site administrator is able to click on any menu link and goes directly to node/edit on that node. In that way I have very clean Admin section of my Drupal site....(perfect for small - brochure type sites)

That's why I love Drupal and it's community :)


D7 RSS Feeds - Omitting Content Fields I created a view with an RSS feed on my D7 site. From the XML feed I'd like to remove the author who created the node displayed in my view and the creation date. I've searched everywhere and tried everything, but I can't seem to remove these two fields from my feed.

I only have permissions to work in views so if you have a solution using Views 3 I'd be most appreciative.

Thank you!

You can specify under "Manage Display" how the content you want to feed will look in the "RSS" (or any other) viewmode. By default, you only have the body (or any additional fields) available. To have more control over what's displayed in which viewmode, you can use the Display Suite module. This module allows you (among many other features) to use another layout for this content. By enabling a layout on the viewmode you like, you also get additional fields like for example the Author and the Post date which you then can enable or disable.


Where are backups stored? I have used https://github.com/drupal-composer/drupal-project to install a new website. I have now updated the core with the same information on the above link.

I was wondering where the backups are stored and how to use the "git diff" because I don't now where the old vs new files are located on my server (ie: .htaccess and robots.txt).

The guide you are referring to assumes that you will be tracking your website as a git project. This is the best way to develop locally before deploying on the server.

The workflow for that is to use composer create-project, then initializing the git repository and adding everything. The default .gitignore should ensure that the installed code isn't added. However, the scaffolding files like index.php and autoload.php are. Once that is done, you can deploy the site on any server by cloning the repository and running composer install.

When the guide says that after updating you should

  Run git diff to determine if any of the scaffolding files have changed. Review the files for any changes and restore any customizations to .htaccess or robots.txt.

it means that updating may have replaced these files, and you may need to re-add custom changes and then commit the new files to git.

composer doesn't create any "backups" when overwriting the scaffolding files - this is why it is important to track the scaffolding files in git, especially if you have custom modifications.


Features code changes overriding automatically I have a panels page in Features but as soon as i change the Features code, it automatically overrides the DB, this means that i don't get to see the "Overridden" state grey button, but always the normal "Default" state is shown and the changes are automatically shown on the web page.

The features should not change automatically the code, but only after i choose to override them.

Any ideas why this is happening?

I thought that was an UUID problem, but after removing the UUID module, the issue still persists.

No, this is how Features work. If your feature is in Default state, code change will cause direct effect on the components (there are some exceptions when clear cache is required). This is actually one of the biggest points and benefits of features, you can easily deploy updated code without any further required action.

Maybe there is a problem with your workflow, you should create you features on you Dev environment (configurations etc), then export them and deploy to Stage/Prod. It is not a good practice to directly change the configuration of components on Stage/Prod environments, you should always do your changes on Dev, then recreate the feature and deploy.


How to show forums even if you don't have access? This is a follow up to this question.

I now know how to modify which forums are shown using the MYMODULE_preprocess_forum_list hook. But I have another scenario I can't figure out.

When you create a forum taxonomy term, you can use Forum Access module to set which users can access which forums. I have:

a board called "premium"
a role called "premium

Only premium members can access this board and this works great. But I still want the premium board to show on the forum landing page. When the user clicks on it, it must tell them they don't have access.

A workaround would be to simply give users access to those forums. Then the forum will display. Then write some other hook or chunk of code that actually stops the user when he clicks through to those pages. But it really feels to me like this should just be setting somewhere.

Am I missing something, or is my suggested solution the best route to go?

UPDATE

My problem could be solved if I could add another option to the screen below that says: "View Posts in this Forum"

Then i can specifically allow them to see the posts, but not actually click through to them.

Implementing custom permissions in Drupal 8:

https://www.aram.cz/article/custom-permissions-drupal-8

You should be able to use static permissions, which are configured in a YAML file in your custom module. From the article:

  To declare static permisisons, you need to create a file in the root directory of your custom module and name it YOUR_MODULE.permissions.yml.

'sample permission 1':
  title: 'First level permission'
  description: 'Gives first level permission to the users.'

'sample permission 2':
  title: 'Second level permission'
  description: 'Gives second level permission to the users.'

'sample permission 3':
  title: 'Third level permission'
  description: 'Gives third level permission to the users.'
  restrict access: true

Then you can check for that permission in PHP code like so:

if (\Drupal::currentUser()->hasPermission('sample permission 1')) {
  // The "sample permission 1" has been granted to the current user.
}
else {
  // The "sample permission 1" has NOT been granted to the current user.
}

I'm not sure exactly how you'll use this technique in your situation to allow users to see only a summary of forum post titles without the ability to click through and see the individual forum posts, but hopefully it will set you on the right track.


Add new tags to Chosen Widget or Display All on Autocomplete Deluxe Trying to find a combination of the features provided by the Autocomplete Deluxe widget and the Chosen module.

They're both great in their own right, but I either need Autocomplete Deluxe to display all options when you click the field (like it does in Chosen) or be able to add new terms to a Chosen field (like you can with Autocomplete Deluxe).

Chosen documentation implies it has this functionality, but I haven't been able to work out how to do it from a select list. And Autocomplete Deluxe, which should be pretty basic, I can't figure for the life of me how to trigger the drop-down to show.

Has anyone been able to do this successfully?

For Autocomplete Deluxe, there looks like there's a bug in the code.

Update line 287 of the js file autocomplete_deluxe.js to include a question mark, as shown in the third last line of this block of code:

Drupal.autocomplete_deluxe.SingleWidget.prototype.setup = function() {
  var jqObject = this.jqObject;
  var parent = jqObject.parent();

  parent.mousedown(function() {
    if (parent.hasClass('autocomplete-deluxe-single-open')) {
      jqObject.autocomplete('close');
    } else {
      jqObject.autocomplete('search','?');
    }
  });
};

Also update the maximum results shown in line 30 of the module by changing to $limit = 0 (the default of 10 overrides whatever you have set for the field):

function autocomplete_deluxe_taxonomy_callback($field_name, $tags_typed = '', $limit = 0) {


how to set date_info->granularity Is there anywhere in the administrators area can I set $vars['view']->date_info->granularity ?

With the recent updates to Drupal 7.32 the date format of the calendar module heading has changed from [month][year] to [day],[month][day number],[year] which looks silly.

I assume granularity has changed from 'month' to 'day', but I can't find where to change it back.

Is this associated with the fixed bug number 355058?

Here is the quick workaround for the issue:
STEP 1: Edit modules/date/date_views/theme/theme.inc and go find line 165.
Change these two lines:
$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

To these two lines:
$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

Note: the only difference is one underscore character added to each line.
Upload the changed file back to your web server.
STEP 2: Go to (YOUR_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.
Before:

After:


Allow user to translate specific field? I have a content type called profile where a user can enter data and thereby create an own profile. Now, most of the profile fields are numeric but two of them are text areas. As my site is in German and English the user should be able to translate these two text area fields (the Input not the Label) but no other fields.

Does somebody know if there's a way to grant translation access to users for specific fields?

Entity translation will do the trick :). That module allows you to point out certain fields to be translated without translation the entire node.

https://www.drupal.org/node/1280632 shows you some use cases and examples on how to configure the module.


How do I write NULL values to the database using drupal_write_record? I'm using drupal_write_record to update records in the database in Drupal 6, but it appears to skip null values entered into my integer fields and just leave the old value. I've also tried the string "NULL" with no success. Regular integer values work fine.

$record = array(
  'id' => ##my_id##,
  'int_field' => null
);
drupal_write_record('my_table_name', $record, array('id'));

How can I change 'int_field' back to NULL from an existing value?

does this patch suite your needs? http://drupal.org/node/227677#comment-4302522


Drupal's attach behaviours : react on all newly loaded content? I've got two different modules which in many ways work together. One of the things they work together on is that module A loads content via AJAX, and module B needs to attach event listeners to the content loaded.

However, it appears that when content is loaded via AJAX by module A, only the 'attach' function of Drupal.behaviours.a gets invoked, and not the 'attach' function of Drupal.behaviours.b. Both functions gets invoked on page load, but not on subsequent AJAX content loading.

// This runs every time module A loads new content.
Drupal.behaviors.a = {
  attach: function(context, settings) {
    alert('a:attach');
  }
}

// This only runs on page load, but never when module A loads new content.
Drupal.behaviors.b = {
  attach: function(context, settings) {
    alert('b:attach');
  }
}

How do i make the 'attach' function of Drupal.behaviours.b run every time any module loads new content?

This, from the comments in misc/drupal.js, explains how it's supposed to work:

Drupal.attachBehaviors is added below to the jQuery ready event and so
runs on initial page load. Developers implementing AHAH/Ajax in their
solutions should also call this function after new page content has been
loaded, feeding in an element to be processed, in order to attach all
behaviors to the new content.


Custom page containing list of nodes separated by content type and date like an Archive How can I create a custom page containing list of nodes separated by content type and date like an Archive?

I think it requires pagination too. So is there any module for this purpose (Drupal 6)?


Can't access template page--node--1.tpl.php by its path I'm trying to access template page--node--1.tpl.php through /node/1 but seeing 'The requested page "/node/1" could not be found.'

What can I do with this to access this template?

I'm using Drupal 7 and the template is in theme/templates folder.

If you're getting a 404 for the path "node/1" then that node doesn't exist, so the template will not be run for it. A template file will only be applied to a path that actually exists.

You just need to get the nid of an existing node and replace the id in the template file name with that, e.g.

page--node--2.tpl.php

where a node with a nid of 2 actually exists in the database.

Don't forget to clear Drupal's caches anytime you add/remove a template file so the theme registry gets updated.


PHP version changes and Drupal versions issues i have installed drupal 7.1 on PHP Version 5.2.17 .....now the server people is going to upgrade the php/mysql to a higher version like 5.3.3 ..is there any problem to the current drupal 7.1 websites running ?

Please advice me.

It's impossible to say whether your specific setup, with your specific site, will or will not have problems after a PHP upgrade. You'll need to set up a test environment that mirrors your live server as much as possible - and test it. It's unlikely, but you may have contrib modules installed that rely on PHP 5.2, so you need to check your specific installation.

From my own experience, before I upgraded to 5.4 some months back I was running many, many Drupal sites on 5.3 (though not versions as old as 5.3.3, that's pretty old these days). In over a year on dev/test/live I've never seen a single Drupal problem that was caused by the PHP version.

On another note, you really need to update your version of Drupal. We're currently on 7.22 and there have been a lot of security/bug fixes since the release you have installed.

You might also want to have a look at the PHP5.3 compatibility group, there's more detailed information there.


JSON:API How to retrieve multiple values in a CONTAINS condition? I'm using JSON:API module (in core since v8.7), and works well for a simple query like:

  Retrieve all articles with title that contains "MyKeyValue" or subtitle that contains "MyKeyValue"

That, translated in jsonapi query, is:

fields[node--article]=title,field_subtitle
filter[or-group][group][conjunction]=OR
filter[status][value]=1
filter[title-filter][condition][path]=title
filter[title-filter][condition][operator]=CONTAINS
filter[title-filter][condition][value]=MyKeyValue
filter[title-filter][condition][memberOf]=or-group
filter[subtitle-filter][condition][path]=field_subtitle
filter[subtitle-filter][condition][operator]=CONTAINS
filter[subtitle-filter][condition][value]=MyKeyValue
filter[subtitle-filter][condition][memberOf]=or-group

But HOW to manage multivalues within the CONTAINS condition? I mean: how to accomplish a query like:

  Retrieve all articles with title that contains ("MyKeyValue" AND "AnotherKeyValue") or subtitle that contains ("MyKeyValue" AND "AnotherKeyValue")

I tried to pass multiple values in this way:

...
filter[title-filter][condition][operator]=CONTAINS
filter[title-filter][condition][value][]=MyKeyValue
filter[title-filter][condition][value][]=AnotherKeyValue
...
filter[subtitle-filter][condition][operator]=CONTAINS
filter[subtitle-filter][condition][value][]=MyKeyValue
filter[subtitle-filter][condition][value][]=AnotherKeyValue
...

But does not work.

filter[profileStatusFilter][condition]
[path]=first_field&filter[profileStatusFilter2][condition]
[path]=second_field&filter[profileStatusFilter][condition]
[operator]=CONTAINS&filter[profileStatusFilter2][condition]
[operator]=CONTAINS&filter[profileStatusFilter][condition]
[value]=first_value&filter[profileStatusFilter2][condition]
[value]=second_value&filter[profileStatusFilter][condition][memberOf]=billing-
group&filter[profileStatusFilter2][condition][memberOf]=billing-group

Just change field name and values if you want change the custom name also here its profile status filter.


Import/Export of Panelized Nodes I'm using Panelizer to panelize nodes of a specific content. This content type is used so that content editors on the website can easily edit (with the help of Panels IPE) the content of pages which all have unique custom layouts (ie. different sets of panels panes at different positions).

To ease deployments, I"m looking for a way export panelized nodes from the development (local) site to the validation and production sites in a non-interactive fashion. Import/Export of nodes themselves is not the issue here, there is several solutions. But, AFAIK, none of them handle the panelizer part. The solutions to use will likely depend on the exact how to export/import the panelizer part of the panelized nodes and how it can be integrated in an automated workflow.

So far, for a panelized $node, I've found the following

// Export the panelized entity information
ctools_export_crud_export('panelizer_entity', $node->panelizer['page_manager']);
// Export the panel display of the entity
ctools_export_crud_export('panels_diplay', $node->panelizer['page_manager']->display);

You can do that by using uuid_features the dev version (dev+36)
 and you may need Panelizer (dev) there are some patches there that will solve problems for you.

Also you can try deploy module, though I didn't use it, but it looks like it will become a more promising solution.


Specify which theme to use when rendering a page with drupal_render_page() I'm looking to send out a node as an HTML email. I have the code working except for one part.

I'm using drupal_render_page() to render the page's content so it's ready for an HTML email. I thought I'd use a custom theme for this (to take advantage of Drupal's theming layer).

However, I can't seem to figure out how I would specify a specific theme to use. Every time I run it it runs the current theme.

I'm not sure if this make a difference or not, but I'm using the Batch API to generate/send the emails.

I've tried changing the $theme and $theme_key globals in the batch callback, however that didn't seem to change anything.

I've also tried something like this in hook_custom_theme():

if (arg(0) == 'batch' && $_REQUEST['op'] == 'do') {
  return 'email';
}

However, this also doesn't seem to change anything and still renders the email using the "seven" theme.

I've also tried using hook_batch_alter(), however changing the theme changes it for the batch process, (I still want the batch to process in the seven theme, I just want the email to be rendered in a different theme).

Thanks!

I discovered that menu_get_custom_theme() only uses a custom theme if the menu does NOT have a "theme callback". In the case of the batch process, it does have a theme callback: _system_batch_theme().

To specify what theme to use when rendering a batch process, I had to use hook_menu_alter() to change the theme callback to my own.

function MYMODULE_menu_alter(&$items) {

  $items['batch']['theme callback'] = 'MYMODULE_batch_theme';

}

Then I just needed to add a conditional

function MYMODULE_batch_theme() {

  // Use a Custom Theme
  if ($_REQUEST['op'] == 'do') {
    return 'email';
  }
  else {
    return _system_batch_theme();
  }

}

This fixes the problem by specify the custom theme in the theme callback rather than in hook_custom_theme() (which is ignored when a theme callback is present).

Thanks!


What top tips you have for designing drupal themes? I would like to use a 960 grid system master theme to create my own custom Drupal 7 subtheme for generic audience.

What should I consider when designing professionally looking Drupal themes ?

What is the most important when designing with end user experience in mind ?

All you need is a consistent architecture and good planning. I think getting started on a HTML5 foundation is a good beginning. I suggest you build your project on a subtheme based on Omega or Fusion Theme kits.

Omega has a based on 960 grid system (12,18,24 columns, 20px gutter). It uses the zone/region relationship for a better block handling. Of course is a responsive theme, it starts mobile to desktop (not viceversa) which is very good.

You can even copy Omega subtheme page layout settings, alter it and save it under a new template with Delta module (created by Jake Strawn). Your settings can be then used in various context using the Context Module.

This is a good architecture to start with.

As a UX designer keep in mind Drupal is jQuery and jQuery UI ready, so learn to manipulate widgets via a module or a js (added in your info file).

Keep a consistent architecture and never mess with modules that are not necessary and only bloats your site.

In additional a good knowledge of Views module, contextual filters and relationships is a must.


How to change the markup for a field I'd like to change the output from the field formatter view from the Field API. I'd like a cleaner markup without unnecessary tags. What's the best way to clean up field formatter view output? Many thanks.

Ideally to change from this:

Visualisation:&nbsp;

to this:

Visualisation:&nbsp;

heres my hook_function_field_formatter_view function:

function mango_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

  $output[0] = array(
    '#theme' => 'container',
    '#attributes' => array(
      'class' => array('something'),
    ),
  );
  return $output;
}

If you want to change output of the field in a Views, use Semantic Views

You can also turn on the Theme Developer module, check which .tpl is used to display piece of content you want to change and then create this file in a way you want.

Another modules that provide similar functionalities are:

Quickest solution, just turn this module and forget about drupal's nested divs:

Fences

More complex, this lets you to set up fields markup - for views as well as full node:

Semantic CCK

The most complex, apart from fields markup, this lets you to set up columns, headers, footers etc. inside of full node view, as well some views integration:

Display Suite


Database updates after pulling in code updates for modules I've updated a bunch of modules in my local development environment and then committed the code changes using git.

On my test site, I've pulled the code and ran drush updb but it's showing that nothing needs to be updated and that the modules I updated are now current. In the past, every time I've performed updates, I was under the assumption that there was a database updating component to it and whenever I ran drush updb it would take the code that was just implemented with git and run the update. Not sure, why it's different this time, can someone explain? Am I missing a command? If there are no database updates needed, I can go on knowing the updates are truly complete?

If database updates aren't require for all module updates, can someone give an example of when updates do and do not touch the database?

Edit:
An example of one such update was to the address fields token or to the Google Static Maps module.

What makes you think that, for any of the updated modules, part of the actual updates included some database update to be performed? In other words: there are (plenty) of cases where, if you update some module, there are no related database updates that are included in such module update.

From "Writing .install files (Drupal 7.x)", within the parg "Module updates using hook_update_N":

  Updating your module, for example updating your schema, can be done using hook_update_N functions. The API page for this is at: function hook_update_N.

  Suppose you add a new column called 'newcol' to mytable1. First, be sure to update your schema structure in mymodule_schema() so that newly created tables get the new column. Then, add an update function to mymodule.install ...

Have a look at this part of an .install file about an update of the database for the Rules module, and which looks like so:

/**
 * Creates a flag that enables a permission for using components.
 */
function rules_update_7209() {
  // Create a access exposed flag column.
  db_add_field('rules_config', 'access_exposed', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Whether to use a permission to control access for using components.',
  ));
}

PS: It's fair to say that database updates are not required unless a change is made to the schema.


Varnish and page cache I have a question about using Varnish along with the Drupal page cache. I was wondering if using both of them is a bit redundant, since Varnish already caches pages for anonymous users?

Currently I have page cache off, page cache max-age zero and cache lifetime set to 10 minutes.

Am I reasoning this right or am I just missing something obvious?

Thanks.

As answered by @dicix, Drupal will not return the correct Cache-Control headers to Varnish without "Page Cache" being enabled in the Drupal Performance configuration.

The problem I ran into with having both the Drupal Page Cache and Varnish at the same time is that it potentially increases the delay before stale content is refreshed to a maximum of both TTLs. For example, having a max-age of 5min could result in the stale content sticking around and being served for up to 10 minutes (or 15 minutes if Varnish doesn't reset the cache-control header given to the browser to something less).

My solution was to set "Cache pages for anonymous users" to be on in the Drupal Performance settings with a reasonable "Expiration of cached pages" of 5min. I then added the following to my settings.php to prevent Drupal from actually caching any page content:

// Use the fake cache for pages since we are caching anonymous HTML with Varnish
if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
$conf['cache_class_cache_page'] = 'DrupalFakeCache';

The DrupalFakeCache just provides stubs that don't store anything or return anything.

Reference: Suppress caching (for development) or to use an external page cache


Putting a watermark on image using Imagecache Actions I would like to put a watermark on the images I'm uploading, but a bit differently than how imagecache does it. Since if a use imagecache for this task, the watermark is always on the image, I would like to put it below the image (t.i. if the height of the img is 500px, then the imagecache would keep it 500 + 40px for the watermark). Is there a way to do it?

Real life example: http://www.bildites.lv/images/5wbdmy4t3ezmtq3as8m.png right now it's like the image on the left, I would want it to be like the image on the right. Is there a way to do it? Keeping in mind I'm also scaling those images.

You can use Imagecache Actions module.

  Effects provided

  Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha
  transparency
  Overlays - Add photo-corners etc to the image
  Text overlay - add a short copyright notice to your image, using available system fonts
  Color-shifting - Colorize images. Also invert.
  Brighten/Darken
  Alpha blending - turn an image into a transparent mask, and back into a flat image against another color
  Canvas manipulation - add padding, either onto color or transparent backgrounds
  Background - Place your image onto another source background
  File Format switcher - If you need tranparency in JPGs : make them PNG. If your PNG thumbnails are 30K each, save them as JPGs. (This is
  distributed as part of the color-actions submodule)
  Rounded corners (transparent). With input from canaryMason, we can even set different radius for different corners, and round just one
  corner etc.
  Aspect Switcher new 2009-08 - lets you perform different actions or use different dimensions based on whether the image is 'landscape' or
  'portrait'
  Custom Actions - Execute your own PHP/GD code in the middle of an imagecache generation process. Requires some familiarity with imageAPI
  internals.

I have bolded the ones that would interest you.


Views Group By how to display only group headers with COUNT of rows I would like my view to display just one field and additionally group by this field. So, I set the following:

checked "Use Aggregation" in Advanced settings
added the field to FIELDS section
in FORMAT section set the Format->Settings to group by this field
in FIELDS section, in Field->Aggregation chose "Group fields
together"

As a result, I get the following output, assuming the field contains color values:

Blue
  Blue
  Blue
Red
  Red
  Red
  Red
Green
  Green

How to prevent displaying rows and only display group headers together with the COUNT of rows? Like this:

Blue (2)
Red (3)
Green (1)

I solved it. The problem with my View was that it was by default sorted by post date. Displaying the underlying SQL query showed that it selects the Post Date to be able to sort by it and that's why it displays each row.

So in this case, getting rid of detail rows means getting rid of the default sort. After that, the view displays only the Group Header row and one "Group By" row per group.

Blue
  Blue
Red
  Red
Green
  Green

To get rid of the Group Header row, hide it in CSS or in a relevant template tpl.php

In order to display the count, add the same field to the FIELDS section again, but this time with Aggregation Settings set to Count. It will look like this:

Blue
2
Red
3
Green
1

To add parenthesses, add Prefix and Suffix to the Field format. To display inline, check both fields in FORMAT->Field Settings->Display inline.


Entity reference field in a block So I have a custom content type where I use an entity reference to store a node and then display it a a teaser on a page.

I now want to achieve a similar thing with a block. I've create a basic block module where it outputs HTML, but now want to allow a user to configure it in admin.

I want to create a select list in the configuration where a user can choose a node of content type 'X' and it will save this preference. Then in the block module view I want to retrieve this value.

How would I go about this?

Something along the lines of Bean or Boxes would probably be your best options (assuming one of the many Node in block modules aren't good enough).

I've got more experience with Bean, so I'll give a general idea based on that.

Both modules allow blocks to be created as fieldable entities.  You should simply be able to add an entity reference field as one of the fields on your block and set it up to display in exactly the same way as you currently do with your node/entity reference combo.

Looking through the issue queue, these modules may merge at some point, but I couldn't see anything that says which one is better.  My personal preference is Bean.


Never show the term name if the user has no permission to view the term I use a vocabulary to freetag bookmarks I post to my site, and I want to hide all the terms (also most nodes; most or all, I don't care).

With TAC module I use following setting for a start:

global default: Show/Create/Delete: ignore   Show-term-checkbox: yes
myvoc default:  Show(node) : disallow;       Show-term-checkbox: no

I have also tried with:

global default: Show/Create/Delete: ignore   Show-term-checkbox: no

I just want to make Drupal show the "access denied" or similar page on /taxonomy/term/xxx. I know my site doesn't show a link with that URL, but I just want to be sure.

Is it possible? Or should I use a simpler module?

You could implement hook_menu_link_alter in a custom module and modify access to /taxonomy/term/xxx, if need be, by overriding the existing access callback with your own.

You will need to look at the menu router table to see exactly what menu item you want to alter.


How to add autocomplete filter to a views based on webform results? I have a views that lists webform results. There are some fields such as name, e-mail address, city etc comes from webform submission.
I want an exposed filter to filter the views based on city. This can be done and a search input appears at the top of the views but there is a problem: you should enter the full city name and then submit. There is no autocomplete or select list feature.
There is a module called Views Autocomplete Filters for this purpose but doesn't work with webform results data.
There was a sandbox project called Webform Selectable Filters before but doesn't exist now.
So, how to add an autocomplete exposed filter to a view that is based on webform results data?

I did this in my custom module :

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

  if($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if($view->name == 'your_view_name') {
     $form['data']['#autocomplete_path'] = 'example/autocomplete';
   }
  }
}

'#autocomplete_path' => 'example/autocomplete' defines an autocomplete callback for our textfield.

When user types something into our textfield, Drupal sends a request via this url to send data you input and to receive suggestions via json if there are any.

To make Drupal aware of this path, let’s add it to the menu system(hook_menu):

$items['example/autocomplete'] = array(
  'page callback' => '_module_name_autocomplete',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK
);

Now we need to create a _module_name_autocomplete function which will look for a suggestion and return it to the user.

function _module_name_autocomplete($string) {

  $matches = array();
  // Some fantasy DB table which holds cities
  $return = db_select('webform_submitted_data', 'w')
  ->fields('w')
  ->condition('w.cid', 'your_component_id', '=')
  ->condition('w.data', '%' . db_like($string) . '%', 'LIKE')
  ->execute();

  // add matches to $matches
  foreach ($return as $row) {
   $matches[$row->data] = check_plain($row->data);
  }

 // return for JS
 drupal_json_output($matches);
}


How to add script to ? I want to add a call for 2 external scripts in the page.tpl.php.

The scripts are:

 <script type="text/javascript" src="http://use.typekit.com/12345.js"></script>
 <script type="text/javascript">try{Typekit.load();}catch(e){}</script>

Now in D7 you can call them directly from page.tpl.php like

drupal_add_js()

right?

But I'm working on a D6 site right now.

So within mytheme directory I add to my template.php file

function mytheme_preprocess_page(&$vars, $hook) {
    drupal_set_html_head('<script type="text/javascript" src="http://use.typekit.com/12345.js"></script>');
    $vars['head'] = drupal_get_html_head();
  }

It doesn't work. The page no longer loads.

So the question is, How do I get both those scripts in the head? What should the code look like? I know the real answer is learn php, but in the meantime

You should concatenate $vars['head'] no replacing it:
Your code should be:

function mytheme_preprocess_page(&$vars, $hook) {
    drupal_set_html_head('<script type="text/javascript" src="http://use.typekit.com/12345.js"></script>');
    $vars['head'] .= drupal_get_html_head();
}

Notice the .= after $vars['head'].


Why block id is generating with encrypted id When I am creating one block view using Views in drupal7 it is creating perfectly but when I am seeing the id using firebug, I am seeing ecrypted id like below.

block-views-f4lsdfjiodfofsdfnsdkfbb6213e4c0fece99305

How can I remove or override this encrypted value in the id.

Views block deltas aren't encrypted, they just use an MD5 hash. The reasoning is thus:

  block.module has a delta length limit of 32, but our deltas can unfortunately be longer because view names can be 32 and display IDs can also be 32. So for very long deltas, change to md5 hashes.

That comes directly from the comments in views_block_info(), which then goes on to run this loop:

foreach ($keys as $delta) {
  if (strlen($delta) >= 32) {
    $hash = md5($delta);
    $hashes[$hash] = $delta;
    $items[$hash] = $items[$delta];
    unset($items[$delta]);
  }
}

Which, as the comments suggest, make sure that the delta is a maximum of 32 chars.

You can try implementing hook_block_info_alter() to implement your own naming convention (it might work, I haven't actually tried it). But the 32 char limitation imposed by the block module is set in stone at the database level so you'll have to take that into account.

If you do that you'll probably need to hook into some other parts of views as well, so that it knows how to process the new block deltas you've given.

As kiamlaluno points out in the comments, you could actually control this at a higher level by making sure that your view's name + display ID together don't exceed 32 characters.

I'm not sure exactly why you want to change this delta, but in my experience the most common reason is so that you can target a specific block with a template file.

Just in case that is your use case, this is a snippet I use in projects to level the playing field so-to-speak.

function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block']->module == 'views') {
    // Add some template suggestions that are a little easier to manage than
    // the default dom id added by views.
    $delta = $vars['block']->delta;

    $found = FALSE;
    if (strlen($delta) == 32) {
      $hashes = variable_get('views_block_hashes', array());
      if (!empty($hashes[$delta])) {
        $delta = $hashes[$delta];
      }
    }

    list($name, $display_id) = explode('-', $delta);
    $vars['theme_hook_suggestions'][] = 'block__views__' . $name .'__' . $display_id;
  }
}

This will let you create a file named like block--views--viewname--displayid, regardless of the delta length limit imposed by the block module


403 redirect loop on every page I'm not sure what is causing this, but every page of my Drupal site is throwing a 403 error redirect loop.

I was just working on the project this morning, and left and came back to it and can't figure out what has gone wrong.

If anyone could event point me toward a resource for figuring out what has gone wrong it would be a huge help.

Looks like you have wrongly configured 403 page, in order to change it back, you can override it by adding following on your settings.php

 $conf['site_403'] = '';


Change the product status after checkout_complete I have one 'select' field in product page it has value 'Open', 'Closed'.I want to changed to 'Closed' after completing the first order of this product.

There is one issue which someone answered for Drupal 7 and it is done by using 'Rules' module.
How I can change the value of a commerce product field after Completion process?

How I can do that using Hooks and without Rules module?

EDIT:
I feel we can use below hooks. But how we can find the product and change the custom field value of the product?

function hook_commerce_checkout_complete($order) {
  if($order->status == 'completed') {
  }
}

hook_commerce_checkout_complete

EDIT 2:

Got the solution for Order Complete event - https://medium.com/@sumanthkumarc/writing-event-subscriber-for-order-complete-event-in-drupal-8-commerce-2-x-196292330b1c. Now question is How I can modify the product custom field value?

public function orderCompleteHandler(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();
  $items = $order->getItems();
}

How can i get the product id from the order items and change the custom field(field_prodstat) value

You'll want to use the commerce hook_commerce_checkout_complete which runs after a order is complete (AKA paid for)

http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21checkout%21commerce_checkout.api.php/function/hook_commerce_checkout_complete/7

That provides the order and you'll just need to get the product ID from that $order variable, load it with product_load(), change the value you want and then save


Creating followups to Commerce Orders for each Line Item I had asked a question in another thread, and thought it might be helpful to create its own thread just in case it could be helpful to any other developers out there:

"I am trying to create a rule which follows up on existing orders of specific products. Each product has a different time interval for "follow up reminder", and my rule should trigger an email to be sent to a customer at a date which is calculated Order Creation Date + Follow Up Interval.

ie Order Creation + Value provided from Products in the order"

I wanted to share how I solved this problem: I created a rule which is dependent on an Order's Status being "Completed". This rule runs a custom PHP script which loads the Completed order Entity, retrieves each Line item and checks for its field called "Follow-up", which gives a time value in weeks


Change homepage template, depending on admin setting Problem: I have a content type called "Homepage" of which there is only one node instance (which is pointed to as the front page), that contains a bunch of editable fields so the client can update certain front page content in several places.

They want to be able to, now and then, change the front page to a slightly different layout to focus on a call to action. This will probably be an

extra content-editable text area
a driver image

That will take the place of an image on the front page. This image is output in node--homepage.tpl.php as you might expect.

My proposed solution:

Create two new fields in the Homepage content: driver text, driver image.
Create an admin page, or add to an existing admin form a button: "Driver mode". When this button is enabled,
Make the Homepage content type reference a new template that hides the old image and outputs the new fields.

Is it possible to do this - use a new template depending on some set variable, or should I have some logic in my node--homepage.tpl.php that conditionally outputs one bunch of HTML or another depending on the variable set in the admin? E.g. (rough code, ignore syntax/logic errors)

<?php

if (variable_get('driver_mode'))
{
   print render($content['field_driver_image']);
   print render($content['field_driver_text']);
}
else
{
   print render($content['field_homepage_image']);
}

?>

So basically, I'm asking what you think is a simple, clean and/or Drupal way to solve my problem above? Note that the code above is just a general example to support what I'm trying to achieve, no need to analyse it's correctness, I'm more interested in what your approach would be - should I perhaps be preprocessing the output in template.php depending on whether driver mode is on or off, so that I only output one variable, which produces the desired output depending on state?

My version is:

Create needed fields (driver image and driver text) for node type
Add checkbox field to the frontpage node type ('Driver mode')
Use template_preprocess_node(&$variables) or hook_node_view() to make some changes if checkbox field is checked


Taxonomy term not found using tid from term reference The users in my webapplication have a term reference suppliers.

I also have a content type transaction where I have the same term reference. Now I would like to hide the select list and set the default value programmatically. This is what I do now:

$form['field_supplier']['#type'] = 'hidden';
$user_suppliers = array();

foreach($user_selling->field_suppliers['und'] as $supplier)
{
    $user_suppliers[] = $supplier['tid'];
}

$firstsupplier = reset($user_suppliers);

$first_supplier = taxonomy_term_load($firstsupplier);

As you can see I loop through the tid's and save them in array. Afterwards I pick the first one (there's a reason I don't pick the first instead of looping through).

The $firstsupplier variable results 7 so what's not abnormal for a tid. But when I want to load the taxonomy term I get a response false... (he can't find it) .

I recently resetted my taxonomy vocabulary to alphabetical, could that be the reason? (I think not, because I tried it after saving them in a random order)

First, don't use 'und', you should be using LANGUAGE_NONE instead.

Your code works, so you might have a data inconsistency on your database, are you sure that the term id 7 really exists?

You can use entity api metadata wrappers to access easier to the field information, or if you're not  using Entity API module, the function field_get_items is a better way to access the information.

$user_suppliers = array();
$items = field_get_items('node', $user_selling, 'field_suppliers');

foreach($items as $item) {
    $user_suppliers[] = $item['tid'];
}

$firstsupplier = reset($user_suppliers);
$first_supplier = taxonomy_term_load($firstsupplier);


How do I push module update in a cached production environment? I don't manage to update Flag module in remote server, while it worked like a charm on local environment. The stage site is cached with Zend opcache, Apcu, Varnish and Redis. I suspected Opcache was faultier but no way to get it work.

The steps I did (local dev) :

drush up flag -y
drush cc all. Tested flag features, OK.
Commited & pushed files to stage on a flag branch

The steps then on remote server :

git checkout flag
Reset Opcache various times (thanks to this great Opcache GUI)
Saved database
Ran update.php, which returned

flag module
7300 - Rebuild the class registry due to classes moving files.
7301 - Rename {flag_content} table to {flagging} and {flags} table to {flag}.
7302 - Rename database columns on the {flag} table.
7303 - Rename database columns on the {flagging} table.
7304 - Rename database columns on the {flag_counts} table.
7305 - Convert flag roles to permissions.
7306 - Convert flag view modes settings.

Ran Apply pending updates, which retunred An unrecoverable error has occurred, Ajax error, http status 200, followed by 4 notices. These notices are known, but caused no update crash on local site.
if I go to the "error page", I'm sent back to Review updates page.

If I try to visit dblog, I have this fatal php error : Class 'flag_flag' not found in profiles/commons/modules/contrib/flag/flag.module on line 1948. But if I check the remote files, I can find that class in profiles/commons/modules/contrib/flag/includes/flag/flag_flag.inc .

I invalidated that file namely in Opcache and invalidate full Opcache. I also checked in varnish.vcl that update.php is in the list of bypassed URL.

Then after a while, Varnish finds backend server is not responding and boom : Error 503 Backend fetch failed, ending restarting php5-fpm...

To be honest, I understand about nothing anymore, "eating my hat" or "banging my head" or how would you say that ? Help really welcome !

Short answer : make extensive use of drush !

This was quite straightforward  and successful, though I'm still not really sure if I have to empty both opcache and Varnish. This would be a huge performance hint on production server. IMO the best would be to invalidate only the changed files in opcache and voilà ?

Steps I did (local dev) :

drush up flag -y
drush cc all
tested flag features, OK.
commited & pushed files to stage on a flag branch

The steps then on remote server :

git checkout flag
varnishadm -T 127.0.0.1:6082 -S /etc/varnish/secret (enter Varnish Cli)
varnish> ban req.http.host ~ dev.example.com && req.url ~ . (clear varnish cache)
reset Opcache with Opcache GUI
drush updb
drush rr (optional in that case since this was performed in flag_update_7300)


How do I fix the missing top 1/2 inch of the content box? I made a number of formatting changes to several basic pages using a Bootstrap-based premium theme. The changes accomplished what I wanted but I subsequently noticed that, when I visited the site as an anonymous user, the top roughly 1/2 inch of the content part of each page is not displayed. It's as if the top of the page is hidden behind the horizontal menu bar at the top of the page rather than appearing correctly a 1/2 inch down.

I backed out all the changes I could remember making but it's still broken. It displays correctly when logged in as either admin or an authenticated user. I don't know how to even begin troubleshooting this issue. Can anyone point me in the right direction?

The body class in the custom-media.css is defining margin-top: 90px for the fixed header, you will need to increase this to match the size of your header.

You may need to include media queries to account for reactive menu changes.

It probably works when you are logged in because either the admin toolbar is modifying the margin or there is a rule specifically for being logged in that assumes the toolbar but you don't have it enabled.


How to create a view for logged in user? In user account (/admin/config/people/accounts/fields) I have a field that references to an entity: company.

I have a node-type, dossier, with a field that references the same entity as in user account: company.

How can I make a view where the logged in user only sees the user's own dossiers?

I tried a lot of things but nothing works. Sometimes the view is empty, sometimes the logged in user sees all the dossiers of the website.

I added an extra reference field to dossiers which refers to an user. In the view: add relationship to the referenced field and make it mandatory. Now it works. The logged in user sees only his files.


Login in a different way For some reason i don't have access to user/login block and don't have a region content .
is there any way to login without them like drush,url ?

Reset the theme to bring back the content region with drush

drush vset theme_default 'bartik'

Then login at example.com/user/login


How to delay the execution of a rule for 5 minutes? I'm using the module "Facebook Autopost" to post Drupal content on Facebook. When a new node is created, a link to this node is posted on a Facebook page. Facebook's scraper picks up the link and tries to scrape this.

This is configured in a rule. Currently, it looks like this:
http://imgur.com/rtIiYLL

When a new node is created, the rule is executed. The link gets posted on the Facebook page, but the scraper seems to get a 404. It appears the rule is executed too fast, BEFORE the actual node is created.

Is there a way to delay the execution of the actions so the node is actually created already?

Is there a way to delay the execution of the actions so the node is
  actually created already?

Yes, you need to enable the Rules Shecheduler module (comes with rules).

Then Create a Rule Component that will do your action.

Then create a rule with action of schedule component. (set it to 5 mins)

For example, see Rules Conditions being evaluated after schedule time elapsed?

Attention:

  Be aware that the actual trigger will only happen the next time
  your Cron job runs. So if you say "after 5 mins", and the next Cron
  job runs in say about an hour, then it'll only be after about an hour.
  If that's not acceptable (as was the case in this question), then
  you'd have to run your cron job like every 5, 10 or 15 minutes.

So I suggest using Ultimate Cron, that way you can target, so that only your rule cron job runs every 5 or x mins, instead of running every single cron job.

In other words, it allows you to run different catagories/module cron jobs at different times. While you could run less crucial jobs, like Update Manager, only once a day (every 24 hours).


add form to /cart, commerce cart page Is there a way to add another form to the /cart page in drupal commerce? I have a need to show another view with operations on the cart page for stored shopping carts and quotes. I don't want to change the existing cart view, but add another view to that page.

Is there a way to make this into a panels page and still integrate with the rest of checkout? any suggestions?

The way I did it was I implemented my own menu item for 'cart' and embedded the cart view on the page where I wanted it, while implementing other things I needed on the page. Definitely not for the faint of heart, though.

In this approach, your page callback is building the elements to be rendered, so you could use views_embed_view with the appropriate args if needed, pass them as variables, and render your page template where you want them.

Note: this is for Drupal Commerce in Drupal 7.


Services 3 File upload, create/return image styles Ahoy all!

So, long story short, I'm uploading files to drupal through services from an angular app, and getting a response/url/etc no problem. My question is, how do I enable image styles to be created on REST upload from services? I'm receiving an empty response in the image_styles array. I am assuming it likely isn't something I need to add into the POST request, but happy to add POST request code if needed.

I am coming up a little short on my google-fu on this one, and any help appreciated!

the image created with the style when you request a page displaying that image_style So you have to call it in code.

The default generation method only creates images when they are requested by a user's browser.

image_style_url  Returns the URL for an image derivative given a style and image path

code sample :

// $file object from file_load($fid)
image_style_url('style name', $file->uri)


How do I render a custom form in page--front.tpl.php? I have a custom form with a button.

function mymodule_get_subscribed_form($form, $form_state) {
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

Now I want render this button on the front page. I've wrote this code in page--front.tpl.php.

print render(drupal_get_form('mymodule_get_subscribed_form'));

It doesn't work with Drupal 7.54, even after clearing the cache.

It might be because of variables being passed by reference. Try this instead:

$form = drupal_get_form('mymodule_get_subscribed_form');
print drupal_render($form);


Correct way to get field definitions for entity types I'm still pretty new to D8 so I'm getting to grips with the new way it deals with fields and the OOP way of doing it etc.
I've got a hook in my module which I'm trying to add a submit handler to different types of form submission (user registration, comment forms, webforms etc) and I'm trying to write something which will go through each of the admin added fields (eg, all fields that start with field_ ) and deal with each field type so that I can do something additional with it at the end
In pseudo terms
foreach ($fields as $field_name => $field) {
    if (substr($field_name, 0, 6) === "field_") {
      switch ( //field type ) {
        case 'boolean':
          // if it's a boolean, do this
          break;

        case 'entity_reference':
          // if it's an entity reference, do this
          break;

        default:
          // for everything else, do this

          break;
      }
    }
  }

But where my switch statement is, I'm basically having to check against the field definition to determine what type of field I'm checking against, because if I just check against the submit handler answers, it only gives me the response.
Currently I'm getting the definitions by doing this
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('entity_type', 'bundle');

Is that the best method to do it? When I tried to run dpm() on this for a custom comment form type, it just seems to kill my site, not like a requirement error, but it just seems to have a memory leak when I try to do it or something.

Think this is an OOP question... so the correct answer is to switch by the type of the instance. In PHP you do this with "instanceof", like here in MappingTest.php:
protected function filterNumericFields(&$fields) {
    foreach ($this->view->field as $id => $field) {
      if (!($field instanceof NumericField)) {
        unset($fields[$id]);
      }
    }
  }

Note: dpm is bad with nested objects... you should set up a debugger like xdebug.
Another Note: Each content entity has a getFieldDefinitions method:
   /**
   * {@inheritdoc}
   */
  public function getFieldDefinitions() {
    if (!isset($this->fieldDefinitions)) {
      $this->fieldDefinitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($this->entityTypeId, $this->bundle());
    }
    return $this->fieldDefinitions;
  }


Show commenter IP address to admins (Drupal 7 / AdaptiveTheme) Once upon a time, with an older version of AdaptiveTheme, I got this to work by patching templates/comment.tpl.php.  The patch I was looking looked something like:

-      print t('Submitted by !username on !datetime',
-      array('!username' => $author, '!datetime' => '<time datetime="' . $datetime . '">' . $created . '</time>'));
+      if ( function_exists('user_access') && user_access('administer site configuration') ) {
+          $authorstring = 'Submitted by !username on !datetime from !hostname';
+      }
+      else {
+          $authorstring = 'Submitted by !username on !datetime';
+      }
+      print t($authorstring,
+      array('!username' => $author, '!datetime' => '<time datetime="' . $datetime . '">' . $created . '</time>', '!hostname' => $comment->hostname));

That was for a much older version of AdaptiveTheme (7.x-1.x, I think).

Thanks to hints from Laryn, I now have a working patch that does what I need.  Here it is:

From 8c064aca6e2fd35da411473c5e50ce471d30d3cf Mon Sep 17 00:00:00 2001
From: Zed Pobre
Date: Tue, 4 Nov 2014 02:54:21 -0500
Subject: [PATCH] Administrators see submitter IP addresses in comments

---
 at_core/inc/preprocess.inc |   24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/at_core/inc/preprocess.inc b/at_core/inc/preprocess.inc
index ef50fda..ba9b45e 100755
--- a/at_core/inc/preprocess.inc
+++ b/at_core/inc/preprocess.inc
@@ -832,13 +832,23 @@ function adaptivetheme_preprocess_comment(&$vars) {

   $vars['datetime'] = format_date($vars['comment']->created, 'custom', 'Y-m-d\TH:i:s\Z'); // Generate the timestamp, PHP "c" format is wrong

-  $vars['submitted'] = t('Submitted by !username on !datetime',
-    array(
-      '!username' => $vars['author'],
-      '!datetime' => '' . $vars['created'] . '',
-    )
-  );
-
+  if ( function_exists('user_access') && user_access('administer site configuration') ) {
+    $vars['submitted'] = t('Submitted by !username on !datetime from !ipaddress',
+                           array(
+                             '!username' => $vars['author'],
+                             '!datetime' => '' . $vars['created'] . '',
+                             '!ipaddress' => ip_address(),
+                                )
+                          );
+  }
+  else {
+    $vars['submitted'] = t('Submitted by !username on !datetime',
+                           array(
+                             '!username' => $vars['author'],
+                             '!datetime' => '' . $vars['created'] . '',
+                                )
+                          );
+  }
   // Unpublished?
   $vars['unpublished'] = ''; // Initialize for backwards compatibility
   if ($vars['status'] === 'comment-unpublished') {
--
1.7.10.4

It looks like you're adding your code within the adaptivetheme_preprocess_node function but you should be working within the adaptivetheme_preprocess_comment function (a little further down the page).

Specifically the following could be modified with your code above as a starting point (starting at line 835 in preprocess.inc for AdaptiveTheme 3.2):

  $vars['submitted'] = t('Submitted by !username on !datetime',
array(
  '!username' => $vars['author'],
  '!datetime' => '<time datetime="' . $vars['datetime'] . '" pubdate="pubdate">' . $vars['created'] . '</time>',
)
);


How can I use exposed filter likes "views tree" in views of content? I want to add exposed filter that shows taxonomy parents and children to views, this view's type is content.
Clearly my goal isn't creating menu by taxonomy, my goal is creating exposed filter for content of views.

Like Below.

The Taxonomy Menu module looks like just what you're after.

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


How can I connect to a database? So I'm new to Drupal and am creating my first module. I can get the page to display html, but I'm not quite sure how to connect to the MySQL database. Here is my code:

<?php
// $Id$

/**
 * @News
 * First module
 *
 * Just a simple news module
 */

function news_main() {
    db_set_active('default');
    $query = mysql_query("SELECT * FROM news");
    while ($news = mysql_fetch_object($query)) {
        $output .= '
'.$news->title.'

'.$news->body.'

'.$news->date.'
';
    }
    return $output;
}

/**
 * Implements hook_menu().
 */
function news_menu() {
    $items = array();

    $items['news'] = array(
        'page callback' => 'news_main',
        'title' => 'News',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
     );

    return $items;
}
?>

I just get a blank page whenever I try to view it. I'm sure it's something simple, but I'm completely new to Drupal and it's API. I've looked through documentation for hours and couldn't figure it out.

So what's happening is you're querying a database that you're not connected to.

db_set_active('default');

...that makes the active database the Drupal default (the one it was installed on, usually).

$query = mysql_query("SELECT * FROM news");

...that doesn't actually do anything.  That is a MySQL Library function (i.e. not part of the Drupal API), so Drupal doesn't actually interact with it.

Now, depending on what you're trying to do here, it's not clear if you're trying to query a table that's part of the Drupal installation or if it's a secondary, external table in a database you're trying to connect to... however, based on the logic you're using I'm going to assume the table is in the Drupal database.

If news is a table in the default Drupal database, then what you want to use is db_query, and the API information for it is located here https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7.  You can read about interacting with the Drupal database through the Drupal API there.

Here's an example I pulled from the Migrate module:

$query = db_select('migrate_example_beer_topic', 'met')
         ->fields('met', array('style', 'details', 'style_parent', 'region','hoppiness'))
         // This sort assures that parents are saved before children.
         ->orderBy('style_parent', 'ASC');

Notice you don't actually have to specify the database you're connecting to, it just assumed 'default'.

In fact, for that matter, you should install the Migrate module and go through the examples that it has.  They come with the module, and will be accessible under sites/all/modules/migrate/migrate_example.


How can I lock out non-authenticated users from a whole taxonomy I have a taxonomy hooking together different content types, everything is working as expected. However, I never want non-Admins to see the taxonomy pages, just names or other related fields in views on other pages. How can hide all of this taxonomies pages from non-authenticated users?

Specific example:

Sales Contact (Node Type) - Sales contact name, address, phone, etc.
Products (Node Type) - All sorts of assorted Product Details
Sales Classifications (Taxonomy) - Types of contracts we have with Sales Contacts, and what products they cover.

Product pages and Sales Contact pages are public, but a Sales Classification page makes no sense to show end users. That said, on Product detail pages I'd like to show some of the Sales Classification fields to end users.

Taxonomy Access Control looked promising, but you can ether lock down the whole term (including related nodes) OR set it to do node permissions separately.

Any recommendations would be appreciated.

thanks

I ended up using Rabbit Hole, it seams to do everything I was looking for.  More details from the module's project page:

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


Views contextual filter to a number of product variations I am having real trouble with this and would appreciate any help.

I have a view block that needs to display all variations of a product that have the same sku with an increment at the end.

Example:

Product name is: 4 jembi avenue

This produces a url of /4jembiavenue

All product variation skus are based on this, so every product variation will now have sku

4jembiavenue0
4jembiavenue1
4jembiavenue2

so on so forth.

What I need is views to display ALL product variations in the view.

I can achieve this by using a filter and setting it to Contains: 4jembiavenue. However as I am intending to have many products displayed like this I do not want to do it like this as each new product would have to have a new block and a new view.

I can use a contextual filter to get the value (4jembiavenue) from the URL and it works fine, but of course it only displays 1 product variation where I am going to need up to 60.

So my question is this:

How can I use a contextual filter with a "contains" operator to find and display all of the product variations?

If you know of any other way I can achieve this I would gladly try this too.

Thanks in advance for any help!

You could try like. First include sku in your view and exclude it from display. Then write this code it would give u desired results.

function modulename_views_query_alter(&$view, &$query)
    {
    if($view->name=='yourname'){
        preg_match('/.*[^\d+]/',drupal_get_path_alias(),$match);
        $query->add_where(1,'commerce_product.sku','%'.$match[0].'%','LIKE');
    }
}


exposed filter views criteria I have a view that exposes a filter for user input to "search" a list of taxonomy.
My problem lies in sorting the results, which are by default alphabetically sorted.

The filter criteria takes user-inputted data from exposed form and uses the "contains" operator on a taxonomy vocabulary, thus returning (alphabetically) any taxonomy term names that contain the given input text. There is no sort criteria applied, thus defaulting to an alphabetically sorted list of taxonomy terms.

The exposed filter uses "contains" as the operator, but is it possible to show "starts with" operator results before or at the top of the alphabetical list of "contains" operator results.

I have tried using combined fields filter, but seem to only be able to combine fields, and not these operators such as contains, starts with, is equal to, ends with.

How might i implement a way to have my view display results that start with the given exposed filter (user) inputted value, then the results that contain the same given exposed filter input.

Combined fields filter seems to only allow multiple fields, not multiple operators or operators with && || and or type options.

Any advice is appreciated. Thanks in advance.

Well, that's obvious mister - filter criteria has nothing to do with results sorting. On your first screenshot, see "SORT CRITERIA" in the left bottom? you can setup sorting there by adding content field or fields to be sorted by.


drush omega-guard and missing or unreadable gemfiles My machine is running Archlinux and and I am new in drush and omega theme.
I have installed drush and then run bundle install to install the dependencies of my subtheme.
When I run drush omega-guard, I get some errors which says the file to import not found or unreadable, while I have installed those gems too.

[timmy@MyPC drupal-7.31]$ drush omega-guard
Which theme do you want to run Guard for?
 [0]  :  Cancel
 [1]  :  First (Subtheme of Omega) - My first theme.
 [2]  :  Ohm (Subtheme of Omega) - Omega based demonstration theme. Serves as a best-practice reference for the Omega documentation. Ohm
         will be constantly updated as best practice evolves so shouldnt be used in production.
 [3]  :  Omega - A powerful HTML5 base theme framework utilizing tools like Sass, Compass, Grunt, Bower, Ruby Version Manager, Bundler and
         more.
1
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
    error sass/first.no-query.scss (Line 3 of sass/first.styles.scss: File to import not found or unreadable: breakpoint.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
    error sass/first.normalize.scss (Line 8: File to import not found or unreadable: toolkit/border-box.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
    error sass/first.styles.scss (Line 3: File to import not found or unreadable: breakpoint.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
Compilation failed in 3 files.

07:11:22 - INFO - Guard::Compass is waiting to compile your stylesheets.
07:11:22 - INFO - LiveReload is waiting for a browser to connect.
07:11:22 - INFO - Guard is now watching at '/srv/http/drupal-7.31/sites/all/themes/first'
[1] guard(main)> help

Found the answer.
here is the solution:
https://www.drupal.org/node/2323235#comment-9069731


Custom module files written in Windows aren't being recognized when migrated to Linux I've developed several custom modules in my development environment. My current development environment is Drupal 8 in XAMPP running under Windows and I write the code in Netbeans. I'm getting close to production and I wanted to setup a development environment that mirrors production, so I setup Drupal in CentOS running in VirtualBox.

The problem is, is when I copied over my custom modules Drupal won't recognize them. They don't show up at all under Extend in the list of modules to install. I'm able to open and view the files in VIM and they don't look corrupted in any way. Also, If I create a module natively in CentOS it is recognized just fine. I'm reasonably confident permissions aren't the issue, I've tried setting everything to 777. I'm not 100% sure being written in Windows is the root cause however all the evidence points that way.

Is this a common problem? If so, what can I do to make Drupal recognize these files?

Thanks!

I believe I've figured it out. This issue may not be consider specific to Drupal but Drupal does seem to be a little more particular about files copied over from a Windows dev site.

To get the files to work I had to do two things and in this order:

Recursively convert all files in "/path" from Windows format to Linux format.

  find /path -type f -print0 | xargs -0 dos2unix

Even after doing step #1 Drupal didn't like the files. I ran this to build a new directories.

  rsync -r /input-path /output-path


Looking for a module to hit a tokenized URL when certain actions happen I'm working with an API from another software product. And the way to create/update records there is by hitting a specifically crafter URL.

Ex. https://sample.nodeurl.tld/save?xml&object=supporter&Email=mytest@email.com

Is there any way to do this with rules or via another module? Or does this have to be done through a custom coded module?

The Rules HTTP Client module (+ Rules itself) will handle that:

  This module adds an action wrapping of drupal_http_request to use Rules for making http requests. It has many general uses, because the Hypertext Transfer Protocol is the foundation of web data communication.


How to use the Elements module to make $form['element'] = array( '#type' => 'number' ); As Drupal 7, core field doesn't support HTML 5 form elements.

How can I use the Elements module from Form API to make the it works below?

$form['element'] = array(   '#type' => 'number' );

Have a quick look at the code of the elements module.

The number field is defined like this:

  $types['numberfield'] = array(
    '#input' => TRUE,
    '#step' => 1,
    '#process' => array('ajax_process_form'),
    '#element_validate' => array('elements_validate_number'),
    '#theme' => 'numberfield',
    '#theme_wrappers' => array('form_element'),
  );

So you should use '#type' => 'numberfield' instead.


How do I modify Drupal so that ONLY relative URLs are used through the whole site? I have a client who says that he is unable to view his company's website from inside his company's building. Their network engineers have asked to make sure that DOMAIN.COM is not included in any of the URLs generated by Drupal.

They want only relative paths everywhere in the code. Any insights?

You can alter all Drupal generated URLs to make them root relative using hook_file_url_alter

function mymodule_file_url_alter(&$uri) {
  global $base_path;

  $scheme = file_uri_scheme($uri);

  if (!$scheme || $scheme == 'public') {
    if (!$scheme) {
      $path = $uri;
    }
    else {
      $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
      $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
    }

    // Clean up Windows paths.
    $path = str_replace('\\', '/', $path);

    $uri = $base_path . ltrim($path, '/');
  }
}

For links in content you can apply the filter supplied by Pathologic


How to translate contact message field labels I have multiple contact forms in my multilingual D8 website:

questions or remarks
order gift voucher

Those have custom fields (like field_phone, field_amount, ...)

For my custom fields, the form-element-label.html.twig with label is a string, whilst the core "message" field is a TranslatableMarkup object.

How do I provide the translation for field labels of these forms?

Standard fields of a contact form are predefined in code. Custom fields are in configuration and the translation works differently.

This should work:

Enable the module "Configuration translation"
/admin/structure/contact/manage/feedback/fields
Add field
Enter an english label
Configure the field type
Choose Tab "Translate contact message fields"
Add a translation in another language
Enter a translated label


Markup filtering at theme level (security) Please could someone advise if any sort of sanitization/filtering is required for the #markup below i.e. check_markup(), check_plain(), etc

The $title variable is basically just from drupal_get_title().

function THEME_form_store_search_page_alter(&$form, &$form_state){

        // Some code goes here to remove title from page and use in form (not part of the question)

    $form['title'] = array(
        '#type' => 'item',
        '#markup' => '<h1>' . $title . '</h1>',
        '#weight' => -100,
    );

}

Rather than remembering specific rules about which variables are safe at which point in the process I suggest you just test things out.

If you can execute Javascript by entering it as the title then you know you have a problem. I try each of these two example snippets of javascript when I want to test something:

<script>alert('xss');</script>
<img src="notfound.png" onerror="alert('xss');">

If your sanitization is working properly then you should either see the tags escaped (displayed as >) or stripped (completely removed from the output).

It is also good to understand the internal workings of Drupal so that you know which functions are safe or not, but knowing how to test for XSS will serve you well in dealing with areas where you are unsure or working with something other than the API.