How do I get the content of a Panel variant to display on as Content? I've made a module that you can add to a Panel Variant's Content section by clicking a region's gear icon and selecting 'add content'. This seems to work fine and I can view the module's output if I set the Selection Rules to a certain url.

However, I want to add this module to a Node (by this I mean the sort of content where you can select Basic Page, Blog Post, Article, etc). When I click 'Add Content' I don't see where I can add the module - there's no Regions with little gear icons, unlike panel variants. It just seems like a page with a text field.

Would anyone know how I can actually add my Module to a new Content/Node page?

OK I think I figured this out:

'Content' is actually Nodes. Don't know why they arnt just called 'Nodes'.
There area different types on Nodes, these are called Content Types. You can add fields to a Content Type. Don't know why they're not called 'Node Types'.
You can use Panel Variants as a kind of template for a Node. You can set Selection Rules to tell it which Nodes to apply it's self to.
Here, in the Panel Variant you can attach Pane Component (my module) to a region.


Add taxonomy terms to files Is it possible to add a taxonomy term to a file that it is uploaded to the site? If not I imagine that I would need to create a content type to encapsulate the file and tag that.

Your file would need to be fieldable. i.e. - using something like the File Entity module.

More complete media solutions exists also, like Media, Scald, or Asset exist which would provide this and more.


How to apply function to a chosen region only? I am using this template.php function:

function mytheme_menu_tree($variables) {
    return '
' . $variables['tree'] . '
';
}

Now it applies to the menu no matter in which region it is. What if I want it to apply only if the menu is inside i.e. Top Menu region? I guess its something that needs to be added before return line?

Also I noticed another problem. It applies to all menus, i.e. if I have two menus, my return line applies to both menus, and 2nd menu is not even shown because id="" can be shown only once.

So I need that function to apply to the menu which is in Top menu region only.

You can use theme_menu_tree__MENU_NAME() to target a specific menu.


Multisite override modules If I have a module in sites/all/modules named dc_front and then I have a module in sites/default/modules named dc_front, which one gets used when it is enabled?

It appears the module in default gets used.

Is this expected and reliable behavior?

drupal_system_listing() is the function that handles this.

According to its inline documentation:

// Duplicate files found in later search directories take precedence over
// earlier ones, so we want them to overwrite keys in our resulting
// $files array.
// The exception to this is if the later file is from a module or theme not
// compatible with Drupal core. This may occur during upgrades of Drupal
// core when new modules exist in core while older contrib modules with the
// same name exist in a directory such as sites/all/modules/.

And as far as I can tell from the function, it searches directories in the following order:

/profiles
/sites/all
/sites/[domain]

So each directory in the list above would override matches from previous directories.

Having modules in the /sites/default directory is not normal, so I'm not sure what the expected behavior would be. My guess is that it depends alphabetically on your [domain] directory name.


Is it necessary to export features with a version number? By default, modules generated with features are created with a version string in the *.info file.

I think the convention is to increase this version number when the feature changes.

In a distributed development work flow with a lot of merging, a linear version increment is not a useful model or metaphor.

Is the version number, and incrementing it, useful or necessary for anything?

I work in a project where until now almost none of the features has version number. But recently a colleague reported problems reverting the features on deployment, if they don't have a version. Of this could be pure concidence, and caused by something other than the missing version number.

It's metadata for keeping track of a Feature release. In D7, the use of Features has two cross purposes:

Bundling Drupal configuration up as a part of a released feature that can be deployed to any site (e.g. a bunch of re-usable content types).
Snapshoting config as code which is useful for capturing config that D7 didn't normally have (and has been supplanted by D8's config management system).

In the first case, the use of version tagging is more useful when you're a vendor of some project leveraging Features. A tag gives you an identifiable way to know what will be rolled back if you force a Feature back to its original state.

If you're using Features solely as config as code, versioning is not really important. Especially, if it's part of a large project that is already leveraging some release tagging.


How to move captcha fieldset I am using the Captcha module to protect my site against spam.

I have put everything else on my form inside a fieldset which is collapsible by default. Howeve, the captcha fieldset is the only thing being output last and outside of the fieldset. Using hook_form_alter and dsm($form) I cannot see the captcha fieldset so i'm guessing it's not part of the form??

after scouring through the code i have discovered it's created via a theme function (theme_captcha) which I can override inside my template.php.

I would like to know how can I bring this fieldset inside the form just above it? Look at the screenshot attached.

Thanks

Use hook_form_alter to hook into the form and programmatically insert the captcha element or adjust the weight of the element or pur the element inside the fieldset.

function example_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_FORM_ID') {
    // 1. Put the captcha element inside the fieldset

    // OR

    // 2. Associate the capthca element to the form
    //$form['captcha'] = array(
    //'#type' => 'captcha',
    //'#captcha_type' => 'image_captcha/Image',
    //);

    // OR

    // 3. Adjust the #weight attribute in the form
  }
}

References

FORM API

How to add a CAPTCHA programmatically

If you need more details please let me have the $form variable in txt format.


3 separate fields,one views exposed filter I would like to have a Rent/Sell radio button for 3 content types.
Then I want to show this radio buttons on a views exposed filter.
How is this possible to do without sharing the radio buttons field on the 3 content types i.e. use a different field on each content type (so as to make easier to upgrade to D8).

If you add all 3 fields as exposed filters and hide 2 of them (with CSS or if you set all fields as "hidden" type with hook_form_FORM_ID_alter()). Then you can use the visible field as master and alter values of the two others with a #submit callback.

<?php
/**
 * Implementation of hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
    if (isset($form['field_to_expose1'])) {
        // Hide two fields and left one exposed.
        $form['field_to_hide2']['#type'] = 'hidden';
        $form['field_to_hide3']['#type'] = 'hidden';

        // Execute set_value_for_hidden_fields() as first function submit on $form['#submit'] array.
        array_unshift($form['#submit'], 'set_value_for_hidden_fields');
    }
}

function set_value_for_hidden_fields($form, &$form_state) {
  $value = $form_state['values']['field_to_expose1'];

  // Modify form_state values of concerned field.
  $form_state['values']['field_to_hide2'] = $value;
  $form_state['values']['field_to_hide3'] = $value;

  // Modify form_state of concerned field to pass to the view.
  $form_state['view']->display_handler->handlers['filter']['field_to_hide2']->validated_exposed_input = $value;
  $form_state['view']->display_handler->handlers['filter']['field_to_hide3']->validated_exposed_input = $value;
}

That's unstested code, but I hope you get the idea.

But is it worth the effort? Is sharing a field between multiple content types really a blocking issue when planning an upgrade? I'm not well informed on upgrade procedures for D7 to 8, but sharing a field between content types seems to be a pretty common thing using D7.


How can I trigger a rule when there's no more scheduled content? I have a Drupal 7 blog where I write content in advance and publish it using the Scheduler module. I'd like to be able to write a rule to send me an email when the site has published the last scheduled node available. I have a View set up which lists all the scheduled nodes, but I can't figure out how to get the result count of that view into the condition of a rule. I've got Views Bulk Operations and Views Rules installed, but I can't figure out how to use either of those how I need to.

You can make this work also by using Rules in combination with the Views Bulk Operations module, as further detailed below.

Step 1

Use the Views Bulk Operations module to create a view of all your "nodes to be published" (as in your question), in which you add a VBO field to it. Simply include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Step 2

Create a Rules Component with a Rules Condition "Check number of results returned by a VBO view". And select the VBO view created in the previous step. If the number of results is below 1, then perform a Rules Action (in that Rules Component) to trigger your eMail.

Step 3

Create a Rule like so:

Use some relevant Rules Event related to those nodes to be published.
Don't use any Rules Conditions (there is no need for them in this rule).
Perform a Rules Action to execute the Rules Component from Step 2.

If you cannot think of any relevant Rules Event that would fit for such rule, then just create a Rules Component which has (only) 2 Rules Actions:

Perform a Rules Action to execute the Rules Component from Step 2.
Reschedule this (extra) Rules Component itself, eg after X mins or hours

Then trigger the very first execution of this Rules Component using the Rules UI.

Done!


Render Twig in hook_mail() I want to render twig when sending email (if it is possible) or include a template.

My code is like so:

/**
 * Implements hook_mail().
 */
function reg_email_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );

  switch ($key) {
    case 'new_user':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('User created: @title', array('@title' => $params['title']), $options);
      $message['body'][] = \Drupal\Core\Mail\MailFormatHelper::htmlToText($params['message']);
      break;
  }
}

I'd like to change $params['message'] or part of this with twig. Is it possible?

$body_data = [
  '#theme' => 'something',
  '#somearg1' => 'somevalue1',
  '#somearg2' => 'somevalue2',
];
$body_content = \Drupal::service('renderer')->render($body_data);
$message['body'] = explode("\n", $body_content);


How to set user status drupal 8 I have tried the following code but nothing seems to be working. I have removed the other field just to make focus on status field.

$user = \Drupal\user\Entity\User::create();
$user->set("status", 0);
$user->activate();
// Save user
$saved = $user->save();

Another code is

$user = \Drupal\user\Entity\User::create();
$user->status= 0;
$user->activate();
// Save user
$saved = $user->save();

But none of the above code is working. Please guide how to set the user status.
Here is my full code

$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $user = \Drupal\user\Entity\User::create();

    $user_data = db_query("SELECT * from eberhard_users ORDER BY uid ASC limit 0,1");

    foreach ($user_data as $delta => $details) {
        // The Basics
        $password = user_password(8);
        $user->uid = $details->uid;
        $user->created = $details->created;
        $user->changed = $details->login;
        $user->access = $details->access;

        $user->setUsername($details->name);
        $user->setPassword($password);
        $user->setEmail($details->mail);
        $user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object

        // Optional settings  <-- Thanks to http://drupal8.ovh/ for these suggestions!
        $user->set("init", $details->mail);
        $user->set("langcode", $lang);
        $user->set("preferred_langcode", $lang);
        $user->set("preferred_admin_langcode", $lang);
        $user->set("timezone", 'Pacific/Wallis');
        $user->set("status", FALSE);
        $user->activate();
        // Save user
        $saved = $user->save();die;
    }

There are a number of issues with your code. First, you are setting status as false, then activating. You don't need to set the status as false first. Just create the user, and set activate() on it.

Next, you are trying to set properties directly, like the created. You cannot do that in Drupal 8. You need to use the methods on the user object. So you would use set(). Other properties have methods for setting the property, such as setEmail(). You can view all the methods on the User object here: https://api.drupal.org/api/drupal/core%21modules%21user%21src%21Entity%21User.php/class/User/8.3.x

One other issue is that you are setting the UID. I don't believe you can do this, as the user ID is determined by the auto-increment value in the database, and trying to manually set it, if you can get it to work, will only cause you issues.


Showing popup after user registration using the "Popup message" module How do I show a popup to a user after he/she has registered, using the Popup message module?

Not with Popup message but this will work:

Install Rules, then create a rule with the following settings:

React on event: After saving a new user account
Actions: Show a message on the site (your message)

Drupal will show your message as a system message.


String overrides doesn't override certain Commerce components It actually overrides everything except 'Order total', I do not understand how that component doesn't get overwritten by String overrides.  Order total is in Checkout page.

Order total
$5,100.00

I cleared my caches.

It's a field label, meaning it doesn't get passed through the basic string translation system. You'd need to use something like the i18n Field module instead.


Does Search API index custom fields? I am using search API on my website (Version 1.8), I have a problem with indexing custom fields. In the Configuration -> Search and metadata -> Search API I have added the custom fields to be indexed, in the view in the "Fulltext search" the custom fields appeared. In the database I can see that the fields got indexed. But when I test, there is no result. Has anyone had similar troubles with Search API?

Edited: The problem occurs only with the fields of "Entity reference" type

You probably need to index the referenced entity Name* (assuming you want to search on name) as a field instead of just simply the entity ID (which is what entity reference fields actually store). The pattern should look something like the following on the 'fields' page:

field_yourfield:entity:name


Different User Points for different nodes I am using the User Points module to assign points to users if they post some content and so on. Works great. Now the admin can set some tasks to the users in the form of nodes. To be clear, a node would describe to perform some tasks and then upload a blog about it. IN that node the admin would assign a field CREDITS which tells how many points a user would get for creating a content related to this node. To relate the nodes i am using References module which works fine. So my question is is there any way to do this, i.e, when admin uploads a new node he can provide the user points in a field which would be the user point assigned to the users when they post a content about this node. I hope i am clear. If any doubt please ask i would only be happy to clarify my doubt.

Any suggestions?

User points can be assigned based on default points or their particular points defined in content type form page.

If you want to override that points use hook_userpoints function. In that function points before case will execute before user points is assigned to users.

second parameter in hook_userpoints, you will get points and entity_id using that you can change points based on your condition.


How to format 'node reference' field values from the Views module How can I format the output of a 'node reference' field that is generated using a View?

Currently it's formatted as (See 2nd graphic): "FirstName - Lastname Pagetitle"

I'm trying to change that to: "Firstname Lastname"

Where do I modify this fields format?

Here is my current view:

Here is the 'node reference' output:

Interesting. Initially it would appear that the "Pagetitle" is being stored in the Last Name field. However assuming that it's not, you can use the devel_themer module to find out what and where is theming that field's output. The culpript could very likely be inside one of your own custom Views templates or theme function override. If not, devel_themer should point you in the right direction.


Drupal 7: Permissions when Apache is running as user account My current host has it set up so that Apache runs as the same account that I use to manipulate files on the file system and, subsequently, the same user that I used to install Drupal 7.

I'm trying to pass the checks in the Security Review module, but it keeps complaining that (pretty much all) files and directories are accessible. I've looked at the handbook page and tried applying the script, but to no success.

Can anyone suggest the proper permissions for my files and directories?

If you're on a shared host this is to be expected, a lot of them operate like that.

Most use suEXEC as the Apache PHP handler which is what makes the web user have full read/write rights over the whole document root. Unless you have access to change the Apache PHP handler (or at least its settings) I doubt you'll be able to change this yourself.

Your hosting provider might do it for you if you get in touch with them, but going on past experience they're normally reluctant to change this sort of thing (in the case of a shared server they might not even be able to do it on a site-by-site basis).


How to get Drush in my path in Windows 10? I have Drush 9 installed on Windows 10.  I installed it via Composer using Lando.

I want to put this drush in my system path so that I can use it from cmd.exe, Powershell, and so on. I want to do this because I am trying to run Drupal Behat Extension tests with the Drush driver, which requires drush to be in the path.

What I tried

Windows 10 Control Panel -> System -> Edit environment variables

Under "User variables for MYUSERNAME", I added:

Variable: LANDO_FRIENDS
Value: C:\pathtowebsiteinstalledbycomposer\vendor\bin

Then I rebooted and tried to run drush:

  drush : The term 'drush' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

So then, from PowerShell, I changed to the \vendor\bin directory and ran ./drush.  This opened up a prompt How do you want to open this file?

I don't understand why this is happening.

Here's what does work:

I can run drush from Powershell using lando, i.e., lando drush status.
I can open up a bash shell with the Windows Linux Subsystem and go to /vendor/bin and enter ./drush, which causes drush to load normally.

So drush is definitely installed, but how do I use it from Powershell/cmd.exe?

The variable will be "Path". Just select that one and edit it then add new line.

You have to download the drush.phar file from here: https://github.com/drush-ops/drush-launcher/releases/tag/0.6.0

Then you have to change the file name from 'drush.phar' to just 'drush' and put that file somewhere and that location needs to be in your path. I put mine in both my system path and user path. Once that is done you shoud be able to call drush from your drupal directory if it was installed with composer.


How to group li element via using Drupal.behaviors? A newbie question here.

How can I select a range of li so I can moved them inside new element?

For example:

test

test

test

test

test

test

test

test

test

test

test

test

To be like this:

test

test

test

test

test

test

test

test

test

test

test

test

So far I tried using Jquery:

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

    $('#navigation ul li.expanded').hover(function() {
      $(this).find('ul').css('display', 'block');
    }, function() {
      $(this).find('ul').css('display', 'none');
    });

    var $lists = $('#navigation li.expanded ul.menu');

    // Loop through all target lists.
    $lists.each(function(i, e) {
      var $list = $(e);

      //These are temporary variables.
      var $new_list = $('
');
      var $list_item, $sub_list, $sub_set;

      // The number of items per column.
      var per_column = 6;

      // Calculate the amount of columns needed.
      var n = Math.ceil($list.find('li').length / per_column);

      // Loop through all columns.
      for (var i = 0; i < n; ++i) {
        // Creates the sub list for the current column.
        $sub_list = $('
');

        // Gets the first set of list items from the original list and adds them to the sub list created above.
        $sub_set = $list.find('li').slice(0, per_column).appendTo($sub_list);

        // Creates a new list item and adds the sub list to it.
        $list_item = $('
').append($sub_list);

        // Add the newly created list item to the new list.
        $new_list.append($list_item);

        // Create a div with the class 'columnX' and wrap the sub list with it.
        $sub_list.wrap('

');
      }

      // Replace the original list with the new one.
      $list.html($new_list.html());
    });

  };
})(jQuery);

The above approach generates "

But I'm having difficulty in manipulating elements via Jquery or JS. Any thoughts will be appreciated. Thanks

I am not completely sure I understand what you are trying to do - I am assuming the html is some kind of Drupal menu you are trying to add some kind of dropdown/flyout action to?

I am not sure whether you want to be doing all this DOM manipulation on mouseover/mouseout either? At least I think that's what you are doing from looking at that code snippet.

Taking your html example at face value, this bit of javascript should do the job of splitting it out into 'columns':

var $list = $('ul'),
    $items = $('li', $list),
    column_counter = 1,
    $current_list,
    items_to_column=6;

$items.each(function(index,item){
  if (index%items_to_column==0){
    var new_column = $("

").appendTo($list);
    $current_list = $('ul', new_column);
    column_counter ++;
  }
  $current_list.append( $(item).detach());
});


How to archive old orders in Drupal Commerce I have a site with more than 15000 commerce orders. This is slowing down the site drastically. I have upgraded all the modules and applied the patches regarding the table locking and so on. They haven't been of much help.

I am ok with removing the order history from the site. I just want to keep an archive of that so that I can use them once I have enough resources to handle everything.

I am not able to get the site up. Hence I will have to do all the work from the command line. So is there any safe and suggested way to archive the orders?

Couldn't you just backup your database using phpmyadmin, doing a .mysql export of the whole database which would keep record of all orders in the commerce_order and commerce_customer_profile tables?

Then using phpmyadmin, just remove all rows from the commerce_order table, to wipe the slate clean.

In the future, if you wanted to add all orders back into the site, you could import the data from your backup.


Securing my drupal website I'm working on my very first drupal website and it will consist of a login form which will then give the user access to a form. This next form will allow the user to query my database to show the closest matches in the category they search - and when they select one they will able to fill in some details on another form, attach some files and then send the information via email.

Security is the most important factor here as the information is all confidential. Can you help me work out what plugins/modules I should be looking at to make my system most secure. And what possible security problems I need to be aware of?

[Note: I have used cmsmatrix.org to compare what the CMS can do and one thing I've noticed is for Drupal it says it can't do things like ssl logins or ssl pages. So should I even be using Drupal in that case?]

I serve several Drupal sites on HTTPS, I don't see what Drupal has to do with that, that's the webservers job to handle. You can test the login for yourself in via HTTPS on drupal.org.

For querying the database in a safe fashion, I would recommend Views.
For gathering data with forms, the Webform module. I haven't collected files with Webform, and I'm not sure if that's doable in it's current form. This may require some custom work.

There's a Securing Drupal guide which also specifically mentions getting HTTPS up.


How to save validated third party API data if form validation fails Here's my issue.  During user register I'm adding fields via form_alter and creating a stripe account.  When validation fails $form_state gets wiped out and when the user passes through validation again a second account gets created.

I'm thinking about using cache_set to hang on to the account info until the user gets through the registration process error free but is there a better way to do this?

It sounds like before your mymodule_form_validation($form, &$form_state) function returns you want to store the Stripe information in the users $_SESSION array as a valid attempt/data.

You write to user session using the global session value in PHP and Drupal adds it to the Users' DB/Mongo user session info at the end of page execution. For example:

// in your form validation code ...
$_SESSION['stripe_username'] = 'john_doe';

On form load simply prepopulate the form data from $_SESSION. Eg, you're stuffing the content into session because it will be wiped on form reload -- then you're replacing it so a 2nd account isnt created.


Get the draft data in the webform hook_form_FORM_ID_alter() I'm building a multi page webform in Drupal 8 as shown below

(1) Consent to ask questions >>> (2) Chekcing eligiblity >>> (3) Consent to Participate >>> (4) Base line info >>> (5) Complete

multipage webform

In the 2nd page (Checking eligibility) as soon as the user clicks on Next Page > button, I need to validate the submitted values (which contains several radio buttons) and assess the user whether he is eligible to participate in a survey or not.

/*
 * hook_form_FORM_ID_alter()
 */
function webform_form_webform_submission_registration_content_node_77_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    ...
    if($form_id == 'webform_submission_registration_content_node_77_form')
    {
        $form['#submit'][] = 'webform_webform_submit_handler';

    }

}

function webform_webform_submit_handler($form, &$form_state) {
    /* This is not displaying any submited values mostly because I haven't clicked on Sumbit button yet */
       dpm($form_state['values']);
}

src: https://www.drupal.org/node/2634266

Is there any way to get the Form's draft values before submission?
Any better approach to process the values within the page(form) itself?
Any help much appreciated.

As jrockowitz suggested, the best way to get the webform's data and processing it is, to create custom WebformHandler. Please refer "Creating a custom webform handler plugin for drupal 8" section here for more details.


How to make an uploaded video visible on the node page in drupal 7 I have created a CCK named sample with a field name VIDEOS of type file. I have added a video of CCK type Sample. But it only showed a url after the node is saved.

Instead of displaying the file name how to make the video playable on the same page.

I installed jwplayer in libraries. I tried changing display type From Generic to JWplayer

Was trying since past 2 days using video module, VideoJS. But did not succeeded. Please help.

UPDATE

here is the result which i got when working with Video module

It is returning empty data with Play button on it. No video is displayed

UPDATE

A small progress,Tried Flow Player  flv videos are able to play. but mp4 is not playing. It simply shows a black screen.

Have you tried using the Video module. You can create field type video insted of type file and then upload and render with the player you have configured.


What's wrong with this code? function welcome_menu() {
  $item=array();
  $item['welcome'] = array(
    'title' => 'welcome',
    'access callback' => 'welcome_init',
    'page callback' => 'welcome_test',
    'type' => MENU_CALLBACK,
  );

  return $item;
}

/*
 * Implements hook_init().
 */
function welcome_init() {
  if (empty($GLOBALS['user']->uid)&& arg(0)!='welcome') {
    drupal_goto('welcome');
  }
}

function welcome_test() {
  $output = 'welcome';
  return $output;
}

I want to auto redirect the anonymous users to the login page, and avoid that an authenticated user can see this page. how I use user_login_block() as page callback?

The most obvious thing is that it does not follow Drupal's coding standards at all. It makes it very difficult to read.

hook_init() is it's own hook, it should not be used as an access callbacks. Access callbacks need to return either TRUE or FALSE.


Drupal Views: Passing a Variable Here's my intention...
I have one view to output my Downloads (Downloads is set up a content type). As a field in the content type for Downloads, I have Product. The user can choose a product for which this download applies. For example, a product brochure for product A would then have Product A as it's product field.

I wouldn't want the content editor (my client) to be able to edit and control the views, I fear it'll blow her mind. So I want to create a single view, and have this view (as a block) display on every Product page. I only want the downloads for the relevant products being displayed, not every single product.

The Downloads view is set up, but at the moment it just lists every download for every product. Is there a way to try and match [field_download_product] replacement pattern with the page's title?

Could you suggest an alternative set-up to achieve this?

First of all, instead of using taxonomy, I would recommend a module like Entity Reference or References to create links between 'download' and 'product' nodes. I think Entity reference is your best bet in this case, because the module page explicitly says it supports "Integration with Views (for both forward and backward references)".

Once you have defined the download-product relations, you can build your view. The key to your solution is the concept of "contextual filters". A contextual filter is a filter with a variable filter value. You will find the settings for it in the right column when editing a view. I can't give you detailed instructions because I don't have a test site with entity reference here, but you'll need to take the following steps:

create a view, listing nodes of type 'download' in a block
add a contextual filter on the entity reference field in your download nodes
when configuring the contextual filter, under "When the filter value is NOT available" choose "Provide default value" -> "Content ID from URL".

So what does this all mean? You now have created a view that will only display download-nodes where the entity reference value is equal to the content ID detected in the URL.

Now, try if it works by enabling the block on product pages. Good luck - I hope this helps.


Validate upload size before starting upload with Filefield? I'm doing some pretty massive uploads, up to 1gig. Right now if I upload a 1.1 gig file it uploads to the limit then fails.

Is there any way to make it fail before even beginning the upload?

The only easy way to check a file upload's size on the client-side that I know of is with Flash.

You should see if the Uploadify module  works for you. I haven't used the module, but I have used Uploadify a lot, and it works great.


Why would a (working) theme function defined in nodequeue module not be registered in theme registry? Trying to overide a  theme function defined in nodequeue  from another custom module:

/**
 * Implements hook_theme().
 */
function nodequeue_theme() {
  return array(
       'nodequeue_arrange_subqueue_form_table' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Theme the subqueue overview as a sortable list.
 *
 * @ingroup themeable
 */
function theme_nodequeue_arrange_subqueue_form_table($variables) {
  $form = $variables['form'];
  // Build output snipped for clarity...
  $output = 'bunch of code';

 return $output;
}

I was expecting to use theme_registry_alter but upon doing a var_dump of $theme_registry in the alter hook (after cache was flushed), it seems the function is not registered. Did I miss something?

Try

function yourtheme_nodequeue_arrange_subqueue_form_table($variables) {}

I don't think you can override module functions from the theme layer without theme_hook_function or hook_function_alter... You'll need to create a module to override nodequeue_theme() - take at look at drupal_alter()


How can I create unique path alias for image styles? image_style_url returns the public url of an image in the files/styles folder. Is it possible to create alias to that? What I want is the following:

Call image_style_url from the image style and the uri, which gives me typical public url /sites/default/files/style/[style_name]/path/to/image/[image_file_name]. I want to serve simple url like /image/[randomized_number] to the user that will internally alias to the aforementioned public url. This is similar to asking what pathauto module does for /node/[nid], but for image styles.

Note that I do not want custom url to individual images per se, but rather a way to programmatically create unique unpredictable url aliases for image styles.

Is a little difficult because image_style_url() uses internally image_style_path() who creates the path /sites/default/files/style/[style_name]/path/to/...
Maybe you can use File (Field) Paths module:

The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

If you only want to change the path alias you can use hook_node_insert() or hook_insert()
/**
 * Implements hook_insert().
 */
function mymodule_node_insert($node) {
    // Set the URL alias
    if (empty($node->path['alias'])) {
        $node->path['alias'] = 'image/' . my_random_function();
    }
}


how to implement Ajax callback on form_alter for entity field? EDITED: I am able to display image for a field dropdown which have entity reference values to another content type. That is when a node content is edited or created.

Note: I'm not creating form elements I'm using them.

For a content type I have a field_select dropdown list (entity reference to another content type). I am trying to alter my form, to display the images of the selected entity from dropdown.

I'm new to the ajax callback functions, and need a little help here. I have a searched a lot and succeeded a bit.

output of my dsm($form):

$form => array (
['field_select'] => array (
  ['und'] => array (
    ['#options'] => array (
      [_none] => -None-
        [1] => content1 //1 is key
        [2] => content2 //2 is key
        [3] => content3 //3 is key
      )
    )
  )
)

Present ISSUE: When the below drop down is selected to a value of above, Image is being displayed in the dummy field below, but only once. For example if I select 1 (content1) the it renders image from node 1 according to the ajax callback function [success]. But now if I select 2 its not loading image from node2, instead it shows only node1 image which was rendered first.

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

 if ($form_id == "article_node_form"){
   $form['field_select']['und']['#ajax'] = array(
     'callback' => 'field_select_ajax_callback',
     'wrapper' => 'another-field-select-image',
   );
   $form['field_select']['und']['#prefix'] = '
';
   $form['field_select']['und']['#suffix'] = '
';

}

function field_select_ajax_callback($form, $form_state) {
  $id = $form_state['values']['field_select']['und'][0]['target_id']; //node id
  $node_id = node_load($id);

  if(is_object($node_id)) {
    $image_uri = $node_id->field_image['und'][0]['uri'];
    $image_url = file_create_url($image_uri);
    $image = '';
  }
  return $image;
}

I want to display respective selected dropdown image near to field-select

Posting my own answer, I will be happy if it helps someone.

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

  if ($form_id == "article_node_form"){
    $form['field_select']['und']['#ajax'] = array(
      'callback' => 'field_select_ajax_callback',
      'wrapper' => 'field-image',
    );

//Note: this $form_state is set only after ajax function call (field_select_ajax_callback)
    if(isset($form_state['values']['field_select']['und'][0]['target_id'])) {
      $node_id = $form_state['values']['field_select']['und'][0]['target_id'];
      $image_path = get_image($node_id);
      $form['field_image']['und'] = array(
        '#markup' => '
 ' .$image_path. '
',
      );
    }
    $form['field_image']['und']['#prefix'] = '
';
    $form['field_image']['und']['#suffix'] = '
';
    return $form;
  }
}

function field_select_ajax_callback($form, $form_state) {
  return $form['field_image']; // very important step, Where I did it differently from previous.
}

function get_image($id) {
  $node_id = node_load($id);

  if(is_object($node_id)) {
    $image_uri = $node_id->field_image['und'][0]['uri'];
    $image_url = file_create_url($image_uri);
    $image = '';
  }
  return $image;
}

Yay fixed it.


Page visible for authenticated user, not custom role I have a custom module that has type MENU_LOCAL_TASK with path user/%/custom-page.

The page callback is displaying a content and with custom page arguments and access arguments functions, only the author of the content can see that content. So far so good.

I have authenticated users and custom role (editor).

Now my goal is to display the MENU_LOCAL_TASK with the page callback content only for the authenticated users, not the editor.

All authenticated users are with role[3] and the Editor is with role[5].
Because of the role "Editor" is automatically authenticated user I cannot set the custom page to be visible only for the other authenticated users.

On my page.tpl.php I've managed to display links that will be visible only for authenticated user without user with role[5] (editor) with this code and its working great.

<?php
if(isset($user->roles[3])){
    //visible only for roles[3], the ordinary authenticated users
}

How can I do this with my custom module?

I didn't find an examples in hook_menu for roles.

Hook_permission() didn't helped, because when I choose the authenticated user in drupal permissions UI, automatically marks the editor role.

I'm using Drupal 7.

When declaring items in hook_menu(), you can specify a custom access callback property. This should be a function that returns TRUE if the user has access to the page.

In this function you can have a look at the global $user object (ie. the currently logged-in user) and determine whether to grant access or not:

/**
 * Implementation of hook_menu()
 */
function hook_menu() {
  $items['user/%/custom-page'] = array(
    'title' => 'Custom Page',
    'type' => MENU_CALLBACK,
    'page callback' => 'your_page_callback',
    'access callback' => 'custom_page_access',
    'access arguments' => array(1),
  );

  return $items;
}

/**
 * Access callback for /user/%/custom-page

 * @param  {[type]} $account [description]
 * @return {[type]}          [description]
 */
function custom_page_access($account) {
  // how do you want to handle role restrictions? if looking at the user
  // whose custom-page is being loaded, use $account, otherwise the global
  // $user object:

  global $user;

  // check that role id 3 IS set, and role id 5 is NOT
  if (isset($user->roles[3]) && !isset($user->roles[5])) {
    return TRUE;
  }

  return FALSE;
}

Don't forget to clear the site's cache (to rebuild the menu registry) after making these changes.


"Unpublish content" doesn't work I have a content type 'company' which has a field: field-paid. This field is a integer list who only has 1 option: 'yes'

This is my export of my rule:

{ "rules_testv2" : {
"LABEL" : "Depublish when not paid",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_i18n", "rules_scheduler" ],
"ON" : { "node_update" : [] },
"IF" : [
  { "data_is" : { "data" : [ "node:type" ], "value" : "company" } },
  { "data_is" : { "data" : [ "node:field-lid-" ], "value" : "1" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_paid" } },
  { "data_is_empty" : { "data" : [ "node:field-paid" ] } }
],
"DO" : [
  { "drupal_message" : { "message" : "Testing" } },
  { "schedule" : {
      "component" : "rules_delete_company",
      "date" : 1508823060,
      "identifier" : "Unpublish node [node:nid]",
      "param_node" : [ "node" ]
    }
  }
]
  }
}

Now I've tried like this (without my component) but still not working:

 { "rules_testv2" : {
"LABEL" : "Depublish when not paid",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update" : [] },
"IF" : [
  { "data_is" : { "data" : [ "node:type" ], "value" : "company" } },
  { "data_is" : { "data" : [ "node:field-lid-" ], "value" : "1" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_paid" } },
  { "data_is_empty" : { "data" : [ "node:field-paid" ] } }
],
"DO" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

It unpublish all my nodes... But I have 2 nodes (for testing) that has value in 'field-paid' (checkbox) so normally those 2 nodes has to remain published...

There are multiple possibilities that may be causing your issue. So below is 1 hint for each of them to verify ...

Hint 1:

To simplify your debugging, just for temporary unit testing, add a Rules Action (as the very first Rules Action) to "Show a message on a site", e.g to say 'Bingo, let the Rules party begin (we did find a combination of Rules Conditions to continue building on)'. This is much easier to do debugging then the ultimate set of Rules Actions you want to get to work.

Hint 2:

Not sure if it is "the" reason why your rule doesn't work, but try to add an extra Rules Condition like ""entity has field" (for your field-paid field). And make sure this is added before any other Rules Condition in which you want to check the value of that field. The bets are open ...

Hint 3:

As per your question, your field-paid field can only have value "yes" (or no value at all I assume). So replace your last Rules Condition (= "not empty") by a "data comparison" (to check if the value is NOT "yes", and note the NOT-negation here). Also note that after you applied hint 1, the "entity has field" will contradict your "not empty" (so both Rules Conditions can never be true together, so your Rules Conditions would never be executed).


I lost custom fees when apply pricing rules I'm using commerce fees modules to add fees when I create orders manually from the backoffice, but click when I click apply pricing rules I lost the added fees. If I add fees (custom fees line item) after applying pricing rules, the VAT taxe be applyed to the unit price only.
Any help please.

Are you using Rules 7.x-2.8? There's a known issue with that release that breaks the application of pricing rules: https://www.drupal.org/node/2403851

The latest development build of Rules may fix the issue: https://www.drupal.org/node/2324587


ERR_TOO_MANY_REDIRECTS on images after switch to HTTPS I have the Drupal 8 site was working with HTTP on the port 80. I switched it to HTTPS with port 443. I got the problem for ERR_TOO_MANY_REDIRECTS when accessing some images from physicals path.

For example path: https://www.example.com/theme/sites/basic/img/fileimage.png

It happened on some files which are display on the pages. I tried access other files on the same level folder "img" is working. (i.e img/logo.png)

I guess it's cache problem. Here what I did:
 - Clear cache
 - Drush cr
 - Deleted some special table within cache_ inside.
 - I stop mysqld, it's still happened.

Here is my .htaccess:

# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

From my admin/config/Basic Site Setting. I still saw

Default front page: http://www.example.com

It should be https? How I can resolve it? Thanks

Try this out -

# ensure www.
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]


Taxonomy term title not displayed as page title in Panels when paged I have use case where for some terms, on the term pages (where nodes with that term are displayed) where for selected terms, I need to display an image instead of the title. To (try to) do this, I've done the following steps:

Add field_image to the vocabulary.
Upload images for selected terms
Enabled the built in taxonomy term panel page.
Created a content pane in the built in taxonomy term view that passes the tid.
Created a term view with a content pane display with term name and field_image as fields.
Hide term name from display, and set term name to be displayed in the No Results settings for field_image.
Add the content pane to the panel page display above the content pane from the taxonomy term view.

This all works great - on the first page. However, once I use the pager (from the view) to go to any subsequent pages, the page title (i.e. the term name or image) disappears. Looking at the page source, you can see that the panel pane with the term title (step 5 above) is not added at all, which makes sense, since there aren't multiple pages of term titles.

Is there a way to do what I need with the Views and Panels UI, or will I need to wield some code fu to replace the name with the image selectively?

Thanks.

Your pager IDs are conflicting.  Adjust the pager settings for one of the views to have a pager ID of 1 rather than 0.


Migrate-d2d UI - Where does sites/default/files source content go? I am setting up a dedicated development environment on my home LAN where I can work on a Drupal 6 to Drupal 7 migration. So far, I have a clean Centos 7, LAMP stack, and Drupal 7 install and have configured periodic file and image backups to my local NAS. The D6 drupal database has been imported and connected in settings.php and appears to be recognized by the migrate_D2D UI.

What I am unclear about is how to migrate the D6 site's downloadable file content and images under sites/default/files.  Although the D6 site is live and remote, I was thinking about copying relevant portions of the sites/default/files path over to the development system, but I don't know where to put it or how to reference it as a data source in the migration process.

I would assume that the format or field mapping conventions for content in sites/default/files is different between Drupal 6 and 7 and source and destination content must remain separate, but I am not sure about this.  So can anyone advise me as to the best approach for incorporating this D6 content into D7?  I would be happy to either copy the content over or read it remotely from the live site if this is supported.  Thanks.

19 hours later:

I haven't resolved this yet so let me ask my question again with a couple of visual aids.  Here is the file tree of the sites/default/files section from my legacy Drupal 6 website:

Here is the file tree of the sites/default/files section from the clean install of the Drupal 7 website I am trying to migrate into:

My question is where migrate_d2d wants me to put the legacy (source) Drupal 6 files.  Do I put it inside the new sites/default/files tree or somewhere separate from where the post-migration Drupal 7 files will be?

Thanks again.

I'll post this as a preliminary answer, but please feel free to comment with better suggestions.

Step 4 (Files) of the migrate_d2d UI asks for path where the source files can be found.  I took the conservative approach and uploaded the legacy sites/default/files file system to a separate source directory on the development server, but I don't see why you couldn't directly import the legacy file content into the sites/default/files directory on the destination server.

At least this seems to work so far.


Two concatenated links throwing an error upon attempted logout I've looked everywhere, and can't seem to find an answer to my problem. I've written some code to toggle between a log in block and, once the user has logged in, a line of text that includes both a link to the logged-in user's profile (I have the Profile 2 module installed) and a log out link.

Both the log in block and the line of text display nicely on my site when users log in and out. The problem comes when I click on the user profile link, which takes me to the user's profile page (which is correct). But then, when I click the "log out" link while on the profile page, it throws an error, rolling the two URLs into one.

Here is the code I included on the page.tpl.php:

  <?php
    global $user;
    $var1 = $user->name;
    $var2 = 'Welcome back' . " " . '' . ucwords($user->name) . '' . " " . '|' . " " . 'Log Out';
    if ($user->uid == false) {
      print render($page['code']);
    }
    else {
  ?>

  <?php print $var2; ?>

(Not that it matters, I'm sure, but a few lines of this code are wrapped in div wrappers that this post wouldn't allow me to include.) When a user logs out from the profile page, this is the URL that results:

www.site.com/users/user/logout

Which obviously doesn't do the job of logging the user out. I want to emphasize that on every other page I've tested, the user can hit the log out link and be logged out with no problem; the issue only exists when trying to log out from the profile page. I suspect that I've coded something wrong with respect to the link HTML, but can't seem to figure out what the issue is. Any help would be much appreciated, thank you.

The issue is you have href="users/logout" not href="/users/logout", eg, it's a relative url, and thus building upon where you are in your site.


Views: Apply a wrapper to every 3 and 6 group of rows My Views Output is as follows

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

I would like to put a wrapper around every 3 and 6 group of Views rows.

So my mark up would look like this:

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

How can I do this? I know that I have to use views-view-unformatted.tpl.php but I am not sure how to alter the $row variable to target every 3rd and 6th group.

Thanks in advance for any help that can be offered.

A few tips about the code:

You also can make the logic in the preproccess or proccess hooks if you prefer
To complete the information given by Jack: Modular arithmetic . This theory help us to build our strategy.

Aplication in a preprocces hook to separate the logic from the template:

function YOURTHEME_preprocess_views_view_unformatted(&$vars){

   $vars['prefix'] = array();
   $vars['suffix'] = array();
   $group = 1;
   $last_row = count($vars['rows']) -1;

   foreach($vars['rows'] as $id => &$row){

     $vars['prefix'][$id] = '';
     $vars['suffix'][$id] = '';

     // Apply modular arithmetic
     $remainder = $id % 9;

     // First div => 3 items
     if($remainder == 0){
       $vars['prefix'][$id] = "\n
";
     }

     if($remainder == 2){
       $vars['suffix'][$id] = '\n
';
       $group++;
     }

     // Second item => 6 items
     if($remainder == 3){
       $vars['prefix'][$id] = "\n
";
     }

     if($remainder == 8){
       $vars['suffix'][$id] = '\n
';
       $group++;
     }

     // Close the div in case there are not enough items
     if($last_row == id && $remainder != 2 && $remainder != 8){
        $vars['suffix'][$id] = '\n
';
     }

   }

}

Your template in you theme that will overwrite the default template provided by views:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!empty($prefix[$id])){ print $prefix[$id]; } ?>
    <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  <?php if (!empty($suffix[$id])){ print $suffix[$id]; } ?>

<?php endforeach; ?>


Domain administrator role that can only see users of that domain Is it possible to define a "Domain Administrator" that would only be able to see the users (in the People interface) assigned to the same domain as itself? I've got a few Domain Access modules installed, but I still can't seem to figure this out.

Have you tried the Domain Admin module?  Looks like there's a bit of stuff in there.  It's a shame that a few of the features listed are currently missing for Drupal 7 though.

  Domain Admin adds more granular permissions to the Domain Access module and several of its sub-modules.

  Currently the module allows the site admin to delegate the following tasks:

  Access the domain overview page - delegated user will only be able to see the domains assigned to him/her (not there in D7 yet)
  Editing of domain record, domain settings and domain theme
  Administer primary and secondary menus (also navigation in D6)
  Translate interface into the domain language (wont be ported to D7 - use i10n_client instead)
  View, edit and delete all unpublished/own unpublished nodes on domain (needs to be tested in D7)
  Administer book outline/ rearrange child pages of nodes on domain (requires book module)
  View webform results on domain (requires webform module)


How do I allow users to rearrange the fields order during content creation? Assume I have a content type with fields a, b, c.

How to allow users to rearrange fields (when they create one content) if they want to display fields in another order? Like b,a,c or c,b,a, etc ...

EDIT:
Panelizer do the job for my case.
There is a bug when trying to save the display. But getting both the Panels and Panelizer modules in latest dev version fixed it.

If you want per-node changing of field display order I recommend looking at Panelizer module. It takes over view modes at the level of entity bundles (content types) and additionally individual entities.

It is not an exact fit of what you describe in that:

It works on an interface separate from content creation.
It is view
mode specific. So rearranging one view mode (teaser) will not change
the full view mode. That might be good or bad depending on what you
want.


International path alias not working I am trying to translate an existing site.

I've used i18n before successfully so I'm not totally new to it. Now to my problem…

I can create content fine in different languages the problem occurs when I try to access languages (other than the default, without path-prefix) with a path-prefix. I keep getting a 404.

Example:

English
Swedish

Their system-path counterparts:

English
Swedish

Any ideas about what might cause this?

Please note that this is a Drupal 6 install.

In reply to your fix you posted in language_initialize. It's very strange that the first arg would be empty.

So now that you've added in your changes, http://www.hillsongconference.co.uk/se/home works.
However, this should be exactly the same as http://www.hillsongconference.co.uk/?q=se/home
and you will see that this brings in the 404 error (whereas q=/se/home doesn't).

So I'm worndering if the htaccess file has been edited?  As this is how Drupal converts the arguments in the url path to $_GET['q'].  The Drupal .htaccess file also strips out leading slashes, to insure the first argument isn't empty.

You've hacked core now, which is a terrible no-no.  Even if you are never going to update this site, it still needs to be fixed out of principle!

If you are running a nginx setup the correct rewrite (to not include the slash) is  rewrite ^/(.*)$ /index.php?q=$1  last; not rewrite ^(.*)$ /index.php?q=$1   last;


how to add table tr using ajax_command in drupal 7 I am using ajax_command_replace method in my ajax_callback function . its working fine its replacing my whole table.. But I just need to add tr on the table after submit a ajax form if data exist. what should I use for this.?

The HTML wrapper you will be replacing sounds like it includes the whole table, so when you return the markup for the new table row, it will replace all the content in that selector/wrapper. You need to include the markup for your whole table including the newly added row, not just the new row.


Check contents of order in commerce So I have a custom module function that checks a cart order for a certain product type

global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);

foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $type = $line_item_wrapper->commerce_product->value()->type;
  if($type=='X'){
    //go mental
  }
}

This is used within checkout to display certain list items for "checkout progress" depending on whether a product type is in the cart (i.e show the gift aid stage if there is a donation).

The issue with this is it seems that when the order is no longer within the cart, for example when we hit the payment stage, and further go on to checkout complete. So the function commerce_cart_order_load($user->uid); no longer works. How would I achieve this same functionality checking the order for product of type 'X' when the order status is updated post-shopping-cart?

I think I can use $order = commerce_order_load(); but somehow I need to get the $order_id?

$order_id = arg(1);
$orderLoad = commerce_order_load($order_id);

foreach ($orderLoad->commerce_line_items['und'] as $line) {
    $line_item = commerce_line_item_load($line['line_item_id']);
    $product_id = $line_item->commerce_product['und'][0]['product_id'];
    $product = commerce_product_load($product_id);
    $type = $product->type;

    if($type == 'X'){
      //go mental
    }
}

If anyone has any improvements to this code (to make it more efficient etc. then please comment below). Thanks.


Why won't JS fire on ubercart checkout page and how do I fix? I need some custom JS (jQuery to be precise) to run on ubercart's  /cart/checkout page. I turned off JS optimization and tried adding it to several different files that are already loading and the JS never fires. It is in the page as if I view-source I can search and find it. I did put $(document).ready(... so it should be waiting for the page to load before running. If I run the same JS from the console of firefox or chrome it does exactly what it's supposed to do. The JS files are all loaded with drupal_add_js().

My only solution at this point is the make a block that only contains that JS and only shows on that page, which it not an optimum solution, but will probably work. Anything else I'm missing on this though?

Only solution I came up with for this was to create a block, assign a blocktheme and in the tpl.php file put the JS. Then assign the block to only show on that page. Bit of a work-around, but it did work.


Set number of slides shown for mobile? I'm using the Slick Carousel module in my D7 layout and it's awesome. My carousel view is currently set to Grid, and to display 9 slides at a time. That said, how can I set the view to display a different number of slides (at different sizes) when the site is being viewed from a mobile device? For example, if the browser is open on a phone and only 414px wide, I want to display 1 slide in the carousel instead of 9 slides with their current image style.

You need to enable the Slick UI, then press on configure.

Click on the List tab, and edit the default.

You need to add some breakpoints, make sure you select the correct skin.


Is there a live video feed module? Is there a way to let visitors to my site watch a video via a live stream?

For example, I want to let students watch a course in which a professor lectures live?

How can I do this easily?

Try BigBlueButton

BigBlueButton Demo, http://demo.bigbluebutton.org/


Trying to add profile2 fields to user/edit page I am trying to show the profile2 fields in my user edit page, but I can't figure out how for the life of me. I read that they should autmomatically show up but it's not happening..

I have added the following in my template.php:

function mytheme_theme($existing, $type, $theme, $path){

        $hooks['user_profile_form']    = array(
        'render element'       => 'form',
        'template'             => 'user-profile-form',
        'path'                 => drupal_get_path('theme','mytheme').'/templates');

    return $hooks;
}

function mytheme_preprocess_user_profile_form(&$variables) {
    global $user;
    $variables['form'] = drupal_render($variables['form']['account']);
    //???
    $profile2 = mytheme_profile_form();
}

function mytheme_form_user_profile_form_alter(&$form, &$form_state){
    global $user;
    $mainprofile = profile2_load_by_user($user->uid, 'main');
    $profile = profile2_load_by_user($user->uid, 'basic_information');

    //Example field
    $form['profile_basic_information']['field_field_1']['und']['#id'] = 'school-district';
    $form['profile_basic_information']['field_field_1']['und']['#attributes']['data-placeholder'] = "Choose your Field1";
    $form['profile_basic_information']['field_field_1']['und']['#attributes']['class'] = "input-xlarge";
    $form['profile_basic_information']['field_field_1']['und']['#default_value'] = !empty($profile) && isset($profile->field_field_1['und']) ? $profile->field_field_1['und'][0]['value'] : '';

}

function mytheme_form_user_profile_form_submit(&$form, &$form_state){
    //TODO
}

I also have user-profile-form.tpl which right now consists just of echo $form;

But the fields I am adding to the form are not being added.. I'm not sure that the form_alter is affecting the output (it is running, though).

I do not think it is an issue regarding with your theme. I have also built a theme from scratch but its showing perfectly up there. You need to change the display settings while you edit your profile type. SO under profile type edit you would find options such as Manage fields, Display fields etc. Under Display fields there would be three tabs just below them...Default, User Account, and Profile Page. By default, the fields which are not required are hidden, you need to change them and then they should show up


How to add users in organic groups using services Rest api? I'm having problem while adding users in organic group. Here I'm trying to add user in organic group called "Supervisor", I'm using following json and Rest api :

Json :
{ "title":"Supervisor",
  "type":"group",
  "og_group_ref": { "und": [{ "target_id": "1921" }]},
  "field_records": { "und": [{ "value": "5" }]}
}

Rest api :
http://localhost/dev/test/node/1921

but, above json and api is not working, am I using correct json and rest api ?

Install this module: https://www.drupal.org/project/og_services
Go to admin/structure/services/list/[MY-ENDPOINT]/resources
Enable at minimum the join resource
Flush all of Drupal's caches
Make a POST call to [MY-ENDPOINT]/og/join/[GROUP-NID]/[USER-UID]


Drupal website goes offline every 2 days for 15 minutes We provide hosting services (Dedicated Server) to a client whose website is based on drupal. This month, his website goes offline for 15 minutes every 2 days.

We already have monitoring tools (i.e pinguzo) showing that the server never went down. And the log files show nothing that is related to this issue. Also, there is no crontab entry executing every 2 days.

And we already checked the website many times at the same hour, but we never encountered the website while offline.

Nevertheless, the client still sends reports about this issue, and we do not know what could be the culprit.

Where should I look? Is there anything in drupal that can cause this?

Thank you.

Drupal can be configured to use a "poor man's cron" (exectuting jobs after a normal visitor's HTTP request). If you have access to the Drupal Admin UI, check Admin > Reports > Recent log messages, this is a core module helpful for debugging (it might be disabled though)


Commerce controller hook_entity_delete The DrupalCommerceEntityController should invoke hook_entity_delete before the records in the database are deleted.

As seen in node_delete_multiple.

These comments should be filed as a code task in the Drupal Commerce issue queue: https://www.drupal.org/project/issues/commerce


Show the ID of referenced entities using tokens, instead of the label with link I have a content type, Company, which is referenced to a User with an entity reference. The token for that entity reference for the current user is     [current-user:field_user_company].

No matter how I configure the field I'm using the token in, when using this token, it always translates in a the label with a link TEST COMPANY.

Is there any way I could make this token translate into just the Node ID (17 in this case)?  I would need just the ID to pass the reference on to other entities in a workflow (using Rules or Business Rules).

Adding the solution given by Clive in the comments to my question as an answer :

[current-user:field_user_company:target_id]

= the token translating into the node ID of a referenced content type.


Define HTML element classes with pattern fields I want to use drupal fields to define class names in ui_patterns. i.e. define a field in a pattern twig.html file and use its {{ twig variable }} as a class name. The following doesn't work. Is there a correct way of doing this? even possible?

{%
set classes = [
'class_name_1',
'class_name_2',
{{ ui_yml_field_name }},
]
%}
<div{{ attributes.addClass(classes) }}>

yaml_field_name.field_drupal_machine_name[0]['#markup'] gave me the selection. problem solved.


How can I implement a shopping cart limit? Possible Duplicate:
limit items in commerce shopping cart

I`m using drupal commerce for my webshop, i want to limit products in the shopping cart which means when the user has a product in his shopping cart he must not be able to add other products.
Is it possible ?

Sure it's possible there are several ways of doing it.

The simplest solution would be to add a custom validation handler to the add_to_cart_form and raise a validation error if there is something in the cart:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'MODULE_cart_validate';
}

function MODULE_cart_validate($form, &$form_state) {
  $order = commerce_cart_order_load($GLOBALS['user']->uid);
  if ($order) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    if ($order_wrapper->commerce_line_items->value()) {
      form_set_error('', t("You can only have one item in your cart");
    }
  }
}

Another option is to remove other items in the cart when you add a new one. This could probably be done with rules, but is more easy to do with code if you know a bit of Drupal and PHP.


How do I mirror a database from remote Linux into Windows localhost? I would like to mirror Linux dev.example.com into Windows dev.example.com.local properly to be able to do development locally.

I have already set up xampp and hosts (dev.example.com.local)
I have created localhost mysql database instance (dev).
I have set up Drupal 7 settings.php on local.
I can export remote db into sql.zip file and I can import it into local db

The key question I have now is
how to properly handle mysql export and import to make sure both local and remote mysql instances are in sync?

I bet Step 4 is not enough here.

Step 4 is enough, they both will be in sync until you change data on one or the other instance.

As a bonus tip, you can ease this procedure by using drush to sync your environnements, via the use of drush aliases.

More details on this here.

Good-luck friend, happy coding.


Skip updating certain themes/modules on composer update My setup is composer driven.

I have overridden some module with patches and customised a contributed theme (boostrap_sass).

Now I want to avoid overbidding these modules and theme when I perform composer update in console, so as to skip updating those modules and themes and perform update on only the modules, themes and core that I want to update via composer.

If you want to pin a version of a module you could do so by running this in your console:
composer require drupal/module_name:1.1

In case you have many modules also see my contributed module:
Composer Update Assistent
This module generates a commando to update all modules to the recommended version which can be copied to your console.


How to automatically enable custom modules upon theme activation? I have a custom module that I have defined in the [root]/modules/[custom module] directory. I want it to get activated as soon as someone installs my theme rather than handing over user the custom modules folder and asking to manually install that module one by one via the Extend option on the dashboard. How can we get that done in Drupal 8?

As @4k4 mentioned there's ongoing development to Allow themes to declare dependencies on modules which hopefully lands in core with 8.6.0. Until then you are a little bit out of luck, except you find a place somewhere in your theme to trigger the following line of code:

\Drupal::service('module_installer')->install(['MYMODULE']);

Alternatively you could provide a second module which provides some button in the back-end which on-click triggers the above line PLUS the following two lines all at the same time.

\Drupal::service('theme_installer')->install(['MYTHEME']);
\Drupal::service('theme_handler')->setDefault('MYTHEME');

The background behind the issue mentioned above is that themes can't provide Drush 9 commands. As Drush 9 commands depend on certain services. But themes ain't allowed to provide these services. See the following issue: Allow themes to provide services.yml which was closed as won't fix.

The reason to close the service-issue (in a nutshell) is to keep things clean (from an OOP point of view) and don't let themes become other modules. Themes should provide templates, styles, scripts. Whereas modules should provide everything OOP-related, including services.

And as themes now (because of this decision) can't provide Drush commands anymore there must be away to allow them to rely on companion modules to provide useful commands/scripts and libraries for (sub-)theme development and maintenance. Which then will probably get activated automatically upon theme activation. So let's look forward and contribute to get this into core ASAP!


How to set a default controller if no other routes match I my project I would like to have a default route or controller that handles any request that does not match any available route. For example on requesting /abcd it now returns 404 as there is route defined for the path /abcd. I want any such request to be handle by a default controller that consider 'abcd' or any other string for that matter as a parameter. How can I implement that. If I define a route for path /{param} wouldn't that override other active routes

Go to /admin/config/system/site-information and set Default 404 (not found) page to the path of your custom controller.

In the controller place a typecasted $request in the argument list. Then get the path from the request and either build a custom 404 response or redirect to another page:

use Symfony\Component\HttpFoundation\Request;

  public function myController(Request $request) {
    $path = $request->getPathInfo();
    if ($path === '/abc') {
      return ['#markup' => 'Path "abc" does not exist!'];
    }
    else {
      return $this->redirect('<front>');
    }
  }

To answer the deleted comment. The controller can't set a status code 200, because it responds to a sub request and the master request is set to 404 no matter which 2xx status you set in the controller. For this you need an event subscriber: Does not redirect in EventSubscriber.


Adding "Directions To" to Geofield Map I have a content type with a Location text field and a Geofield. The Geofield is geocoding the Location field into a coordinate and displaying it to a Google Map embed on the page.

This is working quite well and the map is always marked at the correct location. The problem I have is that the Google Map is quite useless because it doesn't allow the user to do anything with it.

The map shows the location but doesn't allow the user to get directions to it or get the address or anything. When the user clicks on the marker on the map they get a shout out box with the name of the event not the location.

Is there any way I can have the Google Map be more useful? ie add a Directions To button or something like that?

I added directions links to my markers, and to the view's attachment that contains a list of locations displayed on the map. To do this create the directions links:

Added my content type's Post Address field (from the addressfield module) to the views list of available fields.
Re-wrote the Post Address fields view output with the following:

Directions


What step am I missing installing drush with Composer? From my project root, where composer.json and composer.lock are, I tell composer to require drush/drush. It seems to do what it should, but upon completion it seems drush is not installed.

$ composer require drush/drush
Using version ^8.1 for drush/drush
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing webmozart/path-util (2.3.0)
    Downloading: 100%

  - Installing symfony/var-dumper (v2.8.13)
    Downloading: 100%

  - Installing jakub-onderka/php-console-color (0.1)
    Downloading: 100%

  - Installing jakub-onderka/php-console-highlighter (v0.3.2)
    Downloading: 100%

  - Installing dnoegel/php-xdg-base-dir (0.1)
    Downloading: 100%

  - Installing nikic/php-parser (v2.1.1)
    Downloading: 100%

  - Installing psy/psysh (v0.7.2)
    Downloading: 100%

  - Installing pear/console_table (v1.3.0)
    Downloading: 100%

  - Installing consolidation/output-formatters (1.1.0)
    Downloading: 100%

  - Installing consolidation/annotated-command (1.4.1)
    Downloading: 100%

  - Installing drush/drush (8.1.5)
    Downloading: 100%

Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

$ drush
The program 'drush' is currently not installed. You can install it by typing:
sudo apt install drush

Well, actually you installed it locally. You can find it in your project's directory under vendor/drush/drush place (maybe, it depends where the composer put it). You can call only from that place because it's not in your global path. If you want to use this method, you need to call it with an absolute or relative route. Like if your composer installed to here:
On Windows:
D:/phptest/my_project/vendor/drush/drush
On Linux:
~/my_project/vendor/drush/drush
and you are in the D:/phptest/my_project (Windows) or ~/my_project (Linux) dir, in that case, you need to call it like:
On Windows:
vendor/drush/drush --version   OR  D:/phptest/my_project/vendor/drush/drush --version
On Linux:
vendor/drush/drush --version   OR  ~/my_project/vendor/drush/drush --version
and you will get something like:
Drush Version   :  8.1.3
Of course for this, you need a PHP in the global path. (so you need to be able to call PHP from anywhere.)
If you installed it globally with composer (I think you just installed it locally), in that case maybe you need to create a (soft) symlink one place which is globally available for you (listed in the %PATH% variable on windows or in the $PATH variable on Linux), or you need to add the drush's dir to your global path variable.
I suggest you, install it globally, like here is written: https://docs.drush.org/en/8.x/install/
# Browse to https://github.com/drush-ops/drush/releases and download the drush.phar attached to the latest 8.x release.

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

# Optional. Enrich the bash startup file with completion and aliases.
drush init

Then you can use it in any site's dir.
TIPP: if you're installing drush launcher (https://github.com/drush-ops/drush-launcher) globally, then you can have per-site base different drush installed. In this case, you don't need to have global drush installed.


Images not loading until the page is refreshed The links are identical, the path is correct, the image is there,but i have to refresh the page for the image to show, i am suspecting the "itok" parameter might be causing the problem,. It was working fine at the beginning, at some point during the development i started having the problem.

Any help with be appreciated.

Thanks

Have you tried  the Image Allow Insecure Derivatives module?

  Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.

  Details

  Drupal 7.20 comes with a security fix that changes all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

  s an example, links that previously pointed to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png

  will now point to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD

  For more information on the security improvement, visit the release notes.

  This is a fantastic security improvement, but in certain cases, has some ramifications. This module provides a configuration setting in order to toggle whether or not Drupal bypasses that token check.


Inserting based on the results of a select query Initially I had all columns under 1 table. In table shown below had one additional column for all media items.

  did | disclaimer_title | disclaimer_body | disclaimer_media_items

But for some reasons, I need to pull out the disclaimer_media_items column into separate schema. So now I have 2 tables.

Table 1 schema

  did | disclaimer_title | disclaimer_body

Table 2 structure:

  did_media | disclaimer_media_items

Now what I want is when I insert media in table 2, the results get stored for table 1.

i.e. I want to achieve same functionality of all columns under table 1 with two individual tables.

I know 2 things can work, either foreign key or Drupal joins. How can I achieve this?

Hope I explained it well.


How to logout all active users? Instead of putting my site in "maintenance mode" I would like to put it in a complete "readonly mode". There is a module for that, however, it only prevents "node add and edit".
I would like to prevent all user activity including login and registration to basically have the site get served from the (varnish) cache. As as side benefit I would use this type of "read only mode" if the site gets flooded with requests.

My question: how can I logout all active users? The login and registrations I can then redirect with a hook.

As far as I know you can empty the sessions table and all users will be logged out. There may be an issue though, depending on the modules that you have installed. For example, modules that implement hook_user_logout() will never get their actions fired, which could be an issue. Check to make sure none of your installed modules is implementing this hook.


Change teaser template based on a field I have a drop down in my article content type which lets the user select which teaser template to use for that article.

I'm trying to change the template in themename_preprocess_node(), since this is where I know what template is assigned to that specific article.

My problem is that I am struggling to specify which twig template to render.

How can I achieve what I am trying to do?

You can't change the template in preprocess, there's a separate hook for that, hook_theme_suggestions_template()

This is what node is doing for the node template:

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function node_theme_suggestions_node(array $variables) {
  $suggestions = array();
  $node = $variables['elements']['#node'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'node__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->bundle();
  $suggestions[] = 'node__' . $node->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->id();
  $suggestions[] = 'node__' . $node->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}

You can provide something similar. Note that when you do this in a template, you have to use the alter hook, like this example from the bartik theme:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 */
function bartik_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}


How to redirect language prefix to language domain (TLD) I have a single Drupal 7 install running in 2 languages, on 2 domains, but currently using a language prefix as selection. Content can be access as follows:

  English
  mysite.com/content/wonderful
  mysite.de/content/wonderful

  German
  mysite.com/de/content/wunderbar
  mysite.de/de/content/wunderbar

I will change to domain language selection, so that one language is accessible on each domain:

  Englishmysite.com/content/wonderfulGermanmysite.de/content/wunderbar

The setup works wonderfully on my dev server, but all the old links with the /de/ language prefix will be broken.

Is there a way to 301 them all with one fell stroke? Or how can I detect and strip the prefix in /de/content and at the same time redirect to .de/content? Is this best accomplished in .htaccess?

For German content, the appropriate redirect pattern would be as follows:

  mysite.com/de/content/wunderbar -> mysite.de/content/wunderbar
  mysite.de/de/content/wunderbar -> mysite.de/content/wunderbar

Since English has no language prefix, how can I subsequently detect English content that is trying to be accessed on the .de domain and redirect accordingly?

I had the same issue and solved it by putting a 301 redirect in the htaccess file:

# 301 rewrite for all prefixed language nodes to their own domain
RewriteRule ^en/(.*)$ http://example.com/$1 [L,R=301]
RewriteRule ^de/(.*)$ http://example.de/$1 [L,R=301]

Then I generated a new sitemap and inserted it in the google webmaster tools. I'll monitor the performance impact of this solution. Update is coming in two weeks!


form_set_error highlights only select fields and not other required field types I have a content type with few required fields. When I try to save a node without filling any data, all the required fields throw an error message saying the field is required, but the required fields aren't highlighted in red. Only the select fields are highlighted; date fields or text fields aren't.

This is happening when I use the Zero Point theme (version 7.x-4.10).

How should I proceed with troubleshooting?

This was because of CSS overwritten by Zero Point theme, added more classes in my custom CSS file:

    /* .form-item input.error, */
    .form-wrapper .fieldset-wrapper .form-item input.error,
    .form-item textarea.error,
    .form-item select.error {
            border: 2px solid red;
    }


Associate webform submissions with the user created I am allowing anonymous user create submissions, and creating a user programmatically based on these submissions. How do I associate this submission with the user I've just created?

UPDATE: I thought I could use db_update for this but I'd be interested to know if there is a more functional way.

I would recommend checking out the available hooks provided by the Webform module: http://cgit.drupalcode.org/webform/tree/webform.api.php

It looks like hook_webform_submission_insert() will be your best bet, with that you should be able to not only programmatically create the user at that point, but then update the submission with the newly created user id.

function my_module_webform_submission_insert($node, $submission) {
  // Create new user.
  // Retrieve new user id.
  // Update webform submission with new user id.
}


How to import a live Drupal site into Acquia Drupal Dev Desktop? I would like to make some major changes to our live Drupal website. I'd prefer to do it in a safe local development environment on my laptop. What are the steps/process to exporting a live Drupal 7 and importing it into the Acquia Drupal Dev Desktop?

First, use the Backup and Migrate module to create a copy of the database. Then download all the Drupal site files to your machine as well.

You can set up a local version by using the import option Acquia Drupal Dev Desktop instead of creating a new site and importing the Drupal files you just downloaded.

Then use the Backup and Migrate module again on the local site to synchronise the database.


template_preprocess_html(&$vars) dynamic code I have an html template variable called "sitepage" that needs to be set by a module based on node relationships.

Is there a way to set html.tpl variables from a module?

function dc_preprocess_html(&$vars)
{
    $vars['sitepage'] = '/*Insert Business Logic as described below*/';
}

The logic for what the sitepage should be is as followed:

If we are on a car model or car make page then find the car make node and check to see if there is a node reference to an Advertiser node.
Using the advertiser node, check the field "field_sponsor_site_page" to determine the site page

I can easily do this in the module code, but need to do this so I can put the variable in html.tpl.php

The way it works now:

I have 2 pages in play:

Car Detail Page: model/[Car Make Node FIELD_COLLECTION_ID]
List Cars of a particular model: makes/[Car Make Node Id]

A car make node has a node reference to Advertiser. The advertiser has a sitepage that needs to be inserted into html.tpl.php in both cases based on this business logic

try

hook_module_implements_alter()

to alter the hooks order


Different custom view per taxonomy I'm currently working on my first Drupal 8 project and while many things are now integrated in the core, others still stump me (for example restoring options to now bare bones CKEditor requires like 4 additional modules). As I relied on Taxonomy Display module to display different taxonomies with different views and this module is not ported to D8 while similar module TVI is still in beta, I am left wondering what's the current standard of handling this use case. I could use template_preprocess_views_view to programatically switch displays depending on vid. Some suggested you can just use contextual filters to do the same, but I don't see how could you switch between different displays using contextual filters. To me it seems that multiple views would run at once, but some would return empty result sets, spamming database with duplicated queries. Is there really no cleaner way to do it?

You can use the option Specify validation criteria of the Contextual filter to restrict your Views display to one or more Vocabularies, as you've heard before.
Then clone the display and do the same for different combinations of Vocabularies. You can change the path of each new page to avoid conflicts between different Views and calling multiple queries.
I don't know how Taxonomy display module works, I'm not sure if it improves performance, maybe you end up with the same performance metrics in your custom solution. The nodes still have to be matched with taxonomy in another database table, no matter which options you choose. I'm not a SQL expert, maybe someone else will be able to enlighten about the performance and how it affect Taxonomy term queries.


How do I hide bulk operations form for a specified user role? I have a view where I list user's own contents, this contains bulk operations. Users with "add article" permission can see this bulk operations thing but I would like to hide this bulk operations "form element" / "functions" for users in employee role.

How can I do this?

To remove the bulk operations "form element" use ViewExecutable->removeHandler in hook_views_pre_view():

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_view().
 */
function rgr_main_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() === 'content') {
    $account = \Drupal::currentUser();
    $is_employee = in_array('employee', $account->getRoles());

    if ($is_employee) {
      $view->removeHandler($view->current_display, 'field', 'node_bulk_form');
    }
  }
}

This will hide the dropdown form elements, the checkbox in the row and the submit buttons.


From managed file ID to end-user link - neat and clean way? I have a structure in database, and I want it printed. So in hook menu I have entry with

'page callback' => 'mymodule_mystructure_display',

And in inc file I have

function mymodule_mystructure_display($id_structure) {
  $mystructure= something(); // Data preparation
  return $mystructure;
}

And I have all helpers set up so in mystructure.tpl.php I can simply use:

kpr($mystructure);

and it all works, so let me omit details for now, they are covered in Examples for Developers anyway.

The real struggle is with files.

In $mystructure['files'] I have a nested array like this:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(26) "Display name of first file"
    ["fid"]=>
    int(34)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(27) "Display name of second file"
    ["fid"]=>
    int(62)
  }
}

where ["fid"] corresponds to {file_managed}.fid field in Drupal's database.

What's the cleanest way to output links to files, with ["name"] used as link text?

What I'm doing now is pretty dirty:

In function mymodule_mystructure_display I foreach or array_walk over files.
For each element, I take file id, and use this helper function on it:

_uri_by_id($id) {
  $file = file_load($id);
  return $file->uri;
}

Result is fed to file_create_url function, and it's result is saved under ["url"] index, to give me this array in $mystructure['files']:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(26) "Display name of first file"
    ["fid"]=>
    int(34)
    ["url"]=>
    string(50) "http://example.com/sites/default/files/example.pdf"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(27) "Display name of second file"
    ["fid"]=>
    int(62)
    ["url"]=>
    string(50) "http://example.com/sites/default/files/example.txt"
  }
}

In mystructure.tpl.php I use l() to print actual link:

echo l($item["name"], $item["url"]);

This all works. But it feels bad. I was always a backend guy, my frontend knowledge is somehow lacking. But I'm sure there should be a shorter way from managed file ID to a link. So what would it be?

Note: value under ["name"] is derived from $mystructure, it is not something taken directly from file object. This pretty much stopped me from using theme_file_link(). But even if it wouldn't be the problem, I still need to load file object manually to use theme_file_link().

I'd personally prefer something like this:

// Extract file IDs so we only run one file_load().
$fids = array_map($mystructure['files'], function($x) { return $x['fid']; });
$files = file_load_multiple($fids);

$build = array();
foreach ($mystructure['files'] as $file) {
  // Update the description
  $files[$file['fid']]->description = $file['name'];

  // Add to the build
  $build[] = array(
    '#theme' => 'file_link',
    '#file' => $files[$file['fid']],
  );
}

return $build;

A bit cleaner/more performant, and using as much core API as possible.


Using LIKE in search query I would like to search for words that contains the keyword when a user executes a search. I have tried to hook into hook_query_alter():

function MYMODULE_query_alter(&$query) {
  // Check if this is a search query
  if (!$query->hasTag('search_node')) {
    return;
  }

  $conditions = &$query->conditions();
  $conditions = &$conditions[1]['field']->conditions();
  // Change the condition to '%<keyword>%'
  // and add LIKE as operator
  $conditions[0]['value'] = "%" . $conditions[0]['value'] . "%";
  $conditions[0]['operator'] = 'LIKE';
}

I can alter the search query, but I'm not getting any results.

The modified query that gets executed looks like this:

SELECT FROM {search_index} i
  INNER JOIN {node} n ON n.nid = i.sid
  INNER JOIN {search_total} t ON i.word = t.word
  WHERE (n.status = :db_condition_placeholder_0)
    AND ((i.word LIKE :db_condition_placeholder_1 ESCAPE '\\'))
    AND (i.type = :db_condition_placeholder_2)
  GROUP BY i.type, i.sid
  HAVING  (COUNT(*) >= :matches)

And the placeholders in the SelectQuery object are set to:

[:db_condition_placeholder_0] => 1
[:db_condition_placeholder_1] => %liv%
[:db_condition_placeholder_2] => node

I can verify that the tables search_index and search_total both contain a couple of words that contain liv, so this should return some results.

I have also tried Fuzzy Search module, but I don't know how I can connect the provided search to the ordinary search form.

Notice that I have tried db_like(), but without any success.

I don't understand why it should be so hard to change the default search to search through the index using a LIKE rather than = condition?

Something like this should work if I only knew how to implement it:

$keyword = $_GET['s'];
$status = 1;
$types = array('article', 'contact');

db_query("SELECT node.nid FROM {node} n
  INNER JOIN {search_index} si
    ON si.sid = n.nid
    AND si.word LIKE :keyword
  INNER JOIN {search_dataset} sd ON sd.sid = n.nid
  WHERE n.status = :status AND n.type IN (:types)
  GROUP BY n.nid", array(
    ':keyword' => '%' . db_like($keyword) . '%',
    ':status' => $status,
    ':types' => $types
  )
);

you connect the the fuzzy search via search api pages module (or views).

when using views you can place the views search block in your desired region.

Manual instructions: (from fuzzy search)

From the main Search API configuration page, create a server using the Fuzzy Search service class.
Create an Index using the server you just created.
Click the Workflow Tab.
Enable "Complete entity view".
Enable the following processors: Both Fuzzy search processors, Ignore case, HTML filter, and Tokenizer.
Move the Fuzzy Search excerpt processor to the bottom of the list, and the Fuzzy Search search settings processor just above it.
The default settings should be fine.
You will need the Search API Pages module or Views to provide a place to search your site.
Go to the main Search API page,
Click Search Pages, add a search page, and configure with the index you created above, multiple terms for query type, and view mode as themed as search results.
For Views, make a new view using the default fuzzyseach index, add a page display and configure as desired.
Run cron to index your content. Visit the path for your search page.


How can you hide modules form all listings without deleting them I have a growing collection of modules on site.  My module management page and on my feature management page are starting to get cluttered (even with module filter enabled.)  Several of these modules are example modules which are disables and currently only serve to clutter things up.  I would like to hide these modules so that they do not appear in any of my module  lists.  I don't want to delete them (or alter their code if possible.)  Is there a way to temporarily hide a module so it does not appear in any of the module lists?

Use this module to Hide.
Hide Module
This will hide the module based on role.

Hide Modules allows selected modules not being listed at the module administration page except for selected roles.
It enables administrators to safely grant 'administer modules' permission to other roles and keeping at the same time some modules out of the list to avoid untrusted users enabling or disabling them.