jQuery Colorpicker Set color I am using jQuery Colorpicker for some reasons i need to set change the values of the fields directly from javascript.

I found this function HERE in the plug in website

jQuery('input').ColorPickerSetColor(color);

But no luck. Have you experienced something like this. What is the way to do this? Is there any other modules i can use ?

You are setting 'input' which references any input on the site. Use the #id of the input field so that the input field you are targeting is explicit. To find this use firebug, chrome developer tools etc.

Also use Drupal.behaviors to load events where possible. Standard jQuery events do work but you get them all in the one place and clearly namespaced https://stackoverflow.com/questions/3941426/drupal-behaviours.

The code with the specific #id and wrapped in behaviors starts to look like the following, with the field changed to your color field:

(function($) {
    Drupal.behaviors.myModule = {
        attach: function(context, settings) {
            $('#edit-field-meeting-date-und-0-value-datepicker-popup-0', context).change(function() {
                // update code here

                $('#edit-field-submission-cutoff-und-0-value-datepicker-popup-0', context).val(formattedMonth);
            });
        }
    }
})(jQuery);

Finally, always inspect the code in the browser because javascript caching/optimization may be on. Check that there are no javascript errors in the browser console.


Multisite subdirectory not working Reading the guide, this seemed like it would be a walk in the park but I can't get to an install screen for my subdirectories.

I have created my database and users without any issue, I've got my httpd setup and ready for when I get Drupal to pick this up.

I followed the guide https://www.drupal.org/documentation/install/multi-site and followed steps through to 6 except I do not get a install page I simply get the root site that is installed already.

My current url is dev.sitename.com and I am trying to get it to work with dev.sitename.com/fr and dev.sitename.com/de

All permissions are correct so I believe my issue is how I have done the /sites/ step? In this folder I have "all", "default", "sitename.fr" and "sitename.de". The codebase I want to use is "default" and within the "sitename.fr/.de" directories I have the settings.php file setup which looks to be correct. I got my 2 symbolic links by running the command "ln -s . de" and "ln -s . fr".

If I can get to the install page my problems will be sorted. Any help would be appreciated.

The directory should be named dev.sitename.com.fr not sitename.fr. Also, you may find it easier to create a sites.php file from example.sites.php. I recommend that over directory naming.


Validate an ubercart checkout pane? I'm using the uc_ddate module.

How would one hook into the checkout pane to cause it to force it to validate and make the delivery date option required?

Would that checkout pane still be captured by hook_alter_form()?  If so you could add #required to the field there. Let me have a quick try and I'll get back to you.

EDIT: OK, this worked for me:

function tools_utilities_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'uc_cart_checkout_form') {
    // Make delivery date required
   $form['panes']['ddate']['ddate']['#required'] = true;
 }
}

Create your own module (mine is called tools_utilities in this example) and implement the above and you should be good to go :)


Custom search results I am using drupal 7 built in search  module. In my custom content type, I have multiple products for Industrial,mechanics and sports categories. I need to apply search restriction on some products for my mechanics category. Means If mechanics_product1, mechanics_product2 and mechanics_product3 are mechanics products then I need to apply search restriction on all products for only mechanics_product2. Only authorize user will be only able to search this particular product.

Try

1. Search configuration

This module has five main functions.

Alter the appearance of the core node search form
Group content types for more meaningful searching
Restrict search results by the content type. This is a role based restriction.
search results from showing individual items.
Alter the pager limit (aka number search item results per page).

2. Custom Search

  This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box, this module is for you.


Why does hook_menu add my menu items multiple times? I'm using a hook_menu to add some custom menu items to my user menu. One is a link to an external page, one is a duplicate of the "node/add/discussion" page.

I'd expect these menu links to be added to my user menu once and only once. Instead, these links get added to my user menu once for every time I clear cache.

function MYMODULE_menu() {
    $items['external'] = array(
        'title' => 'External',
        'link_path' => 'http://www.example.com',
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'user-menu'
    );
    $items['have_a_chat'] = array(
        'title' => 'Have a chat',
        'link_path' => 'node/add/discussion',
        'type' => MENU_NORMAL_ITEM,
        'access_callback' => 'user_is_logged_in',
        'menu_name' => 'user-menu'
    );
    return $items;
}

Exported from the database (SELECT * FROM menu_links WHERE menu_name = 'user-menu';) the menu looks like:

"menu_name","mlid","plid","link_path","router_path","link_title","options","module","hidden","external","has_children","expanded","weight","depth","customized","p1","p2","p3","p4","p5","p6","p7","p8","p9","updated"
"user-menu","2","0","user","user","User account","a:1:{s:5:""alter"";b:1;}","system","0","0","1","0","-10","1","0","2","0","0","0","0","0","0","0","0","0"
"user-menu","10","2","user/register","user/register","Create new account","a:0:{}","system","0","0","0","0","0","2","0","2","10","0","0","0","0","0","0","0","0"
"user-menu","14","0","user/login","user/login","Log in","a:0:{}","system","0","0","0","0","0","1","0","14","0","0","0","0","0","0","0","0","0"
"user-menu","15","0","user/logout","user/logout","Log out","a:0:{}","system","0","0","0","0","10","1","0","15","0","0","0","0","0","0","0","0","0"
"user-menu","20","2","user/password","user/password","Request new password","a:0:{}","system","-1","0","0","0","0","2","0","2","20","0","0","0","0","0","0","0","0"
"user-menu","336","0","profile-main","profile-main",,"a:0:{}","system","0","0","0","0","0","1","0","336","0","0","0","0","0","0","0","0","0"
"user-menu","1071","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1071","0","0","0","0","0","0","0","0","0"
"user-menu","1072","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1072","0","0","0","0","0","0","0","0","0"
"user-menu","1074","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1074","0","0","0","0","0","0","0","0","0"
"user-menu","1075","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1075","0","0","0","0","0","0","0","0","0"
"user-menu","1076","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1076","0","0","0","0","0","0","0","0","0"
"user-menu","1077","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1077","0","0","0","0","0","0","0","0","0"
"user-menu","1078","0","http://www.example.com",,"External","a:0:{}","system","0","1","0","0","0","1","0","1078","0","0","0","0","0","0","0","0","0"
"user-menu","1079","0","node/add/discussion","node/add/discussion","Have a chat","a:0:{}","system","0","0","0","0","0","1","0","1079","0","0","0","0","0","0","0","0","0"

My Drupal version is 7.23.

One odd thing I notice is that "module" is listed as "system" despite the fact that I'm adding these links in a custom module.

How do I fix my code so that these menu links only get added once?

This was a problem with link_path as hinted at by @xurshid29 and @ARUN.

link_path "works" in that it inserts a link with the given path into the menu, but it also has the odd side effect of inserting multiple links into the menu - one for each cache clear - despite each link having the same key in $items. It's also undocumented, so I have no idea where I picked it up from.

Removing the link_path argument and replacing it with "page callback" fixes the problem of multiple links being inserted.

"Have a chat" was fixed to explicitly callback the "add discussion form":

$items['have_a_chat'] = array(
    'title' => 'Have a chat',
    'page callback' => 'node_add',
    'page arguments' => array('discussion'),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('create discussion content'),
    'menu_name' => 'user-menu'
);

And "external" was fixed to page callback a function that then calls drupal_goto.


Drupal 8: Form fields are not updating when checking triggering element I have added a button to the node add form which allows the user to import data from the last node created into this one. Within hook_form_alter, I have:

// Import previous month's data if requested
$trigger = $form_state->getTriggeringElement(); //Check to see if button pressed

if ($trigger['#name'] == 'import_previous') {
  $id = \Drupal::request()->query->get('field_patient'); //grab node id from url
  $previous = st_access_patient_get_previous($id); //grab actual node
  $previous_array = $previous->toArray(); //cast node to array

  // Match up data from previous node to fields in this form, set default value
  foreach ($previous_array as $label => $field) {
    if (substr($label, 0, 5) == 'field' && $form[$label]['#access'] == TRUE) {

      if (array_key_exists('#default_value', $form[$label]['widget'])) {
        if (array_key_exists('target_id', $field[0])) {
          $form[$label]['widget']['#default_value'] =  $field[0]['target_id'];
        } else {
          $form[$label]['widget']['#default_value'] =  $field[0]['value'];
        }
      } else {
        if (array_key_exists('target_id', $field[0])) {
          $form[$label]['widget'][0]['value']['#default_value'] = $field[0]['target_id'];
        } else {
          $form[$label]['widget'][0]['value']['#default_value'] = $field[0]['value'];
        }
      }

    }
  }

}

$form['previous_import'] = [
  '#type' => 'button',
  '#name' => 'import_previous',
  '#value' => t("Import the previous month's values"),
  '#weight' => -9999,
  '#submit' => ['import_previous_submit'],
];

My understanding is that the button will just submit the form, I don't actually need

'#submit' => ['import_previous_submit']

When pressing 'import_previous' button the field values are not updated. If I remove the conditional (which just runs the replacement logic on every form load) then everything works fine. So, I know my logic for the replacement itself is correct. But once I wrap my replacement logic in:

if ($trigger['#name'] == 'import_previous') {}

Then the fields no longer update when the button is pressed. The conditional passes, so I know that is correct. Something else is keeping the form default values from being set. I have tried to add:

  $form_state->setRebuild(TRUE);
  $form_state->setCached(FALSE);

after:

$trigger = $form_state->getTriggeringElement();

and directly before the final closing tag of the conditional. I have also tried to add it to a submit function 'import_previous_submit'. No love with any of that. Any help is greatly appreciated.

You don't need to check the triggering element if you use it's own submit handler because the submit handler is only triggered by this element.

function your_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['previous_import'] = [
    '#type' => 'submit',  // changed to submit
    '#name' => 'import_previous',
    '#value' => t("Import the previous month's values"),
    '#weight' => -9999,
    '#submit' => ['import_previous_submit'],
  ];
}

function import_previous_submit(&$form, FormStateInterface $form_state) {
  // Example of altering / setting the field values. You have to adapt your foreach stuff.
  $user_input = $form_state->getUserInput();
  $user_input['title'] = [['value' => 'test']];
  $form_state->setUserInput($user_input);

  $form_state->setRebuild();
}


How to order unions separately in db_select? I have a UNION query, where the second part of the UNION should be ordered separately, not the complete UNION.

The resulting query should look like this:

(
  SELECT id, fname FROM tab1 WHERE fname = 'Frank'
) UNION (
  SELECT id, fname FROM tab2 WHERE lname = 'Sinatra'
  ORDER BY fname DESC
)

My question is: How can I order the second part of the UNION? I know, I could use a db_query, but I'd like to join this db_select in another db_select. And I think I cannot join an executed db_query result and a db_select object.

Here is my current code:

$subquery1 = db_select('tab1','t1');
$subquery1->fields('t1',array('id','fname');
$subquery1->where('fname=:fname',array(':fname'=>'Frank');

$subquery2 = db_select('tab2','t2');
$subquery2->fields('t2',array('id','fname');
$subquery2->where('lname=:lname',array(':lname'=>'Sinatra');
$subquery2->orderBy('fname','DESC');

$subquery1->union($subquery2);

$result = $subquery1->execute();
...

The resulting query is:

(
  SELECT id, fname FROM tab1 WHERE fname = 'Frank'
) UNION (
  SELECT id, fname FROM tab2 WHERE lname = 'Sinatra'
)
ORDER BY fname DESC

I found the answer not in Drupal, but in MySQL:

I added a new column to the subqueries with an indicator of the query. The first sub query has the sort column value "0_" and the second one "1_".

Here is the drupal db_select code:

$subquery1 = db_select('tab1','t1');
$subquery1->fields('t1',array('id','fname');
$subquery1->where('fname=:fname',array(':fname'=>'Frank');
$subquery1->addExpression("'0_'",'sort_column');

$subquery2 = db_select('tab2','t2');
$subquery2->fields('t2',array('id','fname');
$subquery2->where('lname=:lname',array(':lname'=>'Sinatra');
$subquery2->addExpression('1_','sort_column');
$subquery2->orderBy('sort_column', 'ASC');
$subquery2->orderBy('fname','DESC');

$subquery1->union($subquery2);

$result = $subquery1->execute();
...


Moving the fields and data from one content type to another content type I have created a content type called "ContentA" and in that content type I have two fields, "Summary" and "Title". I have already created a new content type called "ContentB" and it is also having the same fields. What I need to do is move the data and fields everything from the first content type "ContentA" to second content type "ContentB" and I'm using Drupal 7.
I tried the node convert module, it is allowing only each node at once, I am having approximately 500 nodes, I cannot use that module. So looking for any module/script for bulk transfer

Is this possible with a module or maybe from SQL. I don't know what to do, I've been trying to do this from weeks and I'm stuck :( please help!

you can definitely accomplish this with the migrate module (https://www.drupal.org/project/migrate). Your source DB and your destination DB will be the same, but that is acceptable. You're essentially migrating ContentA nodes into ContentB nodes and since they both have the same fields the mapping should be very simple.


How to dynamically create a view, and then export to PDF I'd like to dynamically create a view for each of my content types/items, and then export that View's data to PDF format.

My (Drupal 7) website tracks mileage, gas usage, engine usage, and other items for a fleet of cars. Let's say I want to run a report on Car A. I'd like to have a single view that could pull in only the information for Car A when I click a link on Car A's content page. Then, if I click a link on Car B's page, it would pull in only the information for Car B. The same would be true for Engine A, Engine B, etc. The purpose would be to see a snapshot of the usage of that car, engine, etc.

I use the Entity Reference module to link individual usage content items to each of the "master" content items (cars, engines, etc). The Usage content items have the following fields: the VIN/serial number of the car/engine (which links the usage content item back to the car/engine), miles driven since last visit, gas remaining since last visit, etc. These usage items are the most important thing for this usage report. There will be other fields from the Car, Engine, etc (such as the color of the car, starting mileage, etc) that will appear on the report, but those are really just information; the usage items are key.

Is all of this possible with Views out of the box? Or would I need an additional module to accomplish this?

Thanks!

I was able to get the output that I needed by using the Reference module and the Viewfield module.

Created Content type A and content types B, C, and D. B, C, and D are all associated with Content type A via Reference fields.
Created contextual/relationshipped views for B, C, and D, relating it to the title field of Content Type A.
Created a Viewfield on Content Type A for each of the sub-content types (B, C, and D).
Created a View for Content Type A, contextualized with Content:Title, and added the Viewfields to this new View (using reverse relationships with the node referenced field). I then added a PDF Page view using Views PDF, and that did the trick!

I can provide more detail if needed. Just let me know...


Information of the user in comments I want to show the information of the author in his comment. By default it shows the name and the picture, I want to add:

The number of node and created comments
The number of obtained userpoints.

What code should I use to achieve this?

Each comment runs through comment.tpl.php template, where the php variables are replaced with actual values and from where you get the actual html

Before going to tpl files, execution passes through template_preproces functions, preprocess function allows you to add new variables or override existing variables which you use on tpl files.

Now in your case it is comment.tpl.php, if you see the file in bartik theme the code

    <?php print $picture; ?>

        <?php print $author; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

is responsible to show comment author information. In order to override the html you can simply copy the comment.tpl.php from parent theme to your base theme and start overriding the html. If you want to introduce new variable to the template, then use template_preprocess_comment(), for example on your theme template.php

function your_theme_preprocess_comment(&$variables) {
  // To Debug what is inside variables already
  dpm($variables);
  // To override exisiting variable
  $variables['author'] = 'my test author';
  // To add any new variable to comment.tpl.php
  $variables['author_comment_count'] = _some_function_fetch_comments_count($user_id);
  $variables['author_nodes_count'] = _some_function_fetch_node_count($user_id);
  $variables['author_user_points'] = _some_function_fetch_user_points($user_id);
}

Now you will have three more variables to use on comment.tpl.php as
$author_comment_count, $author_node_count, $author_user_points

Use them on template, example

    <?php print $picture; ?>

        <?php print $author; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

        <?php print $author_comment_count; ?>

        <?php print $author_node_count; ?>

        <?php print $author_user_points; ?>


Is there any way to fetch all users into a list in rules? I want to know if there is any way to fetch all users into a list in Rules?

I used Views Bulk Operations (VBO) and "Load items from VBO" in Rules. But it seems it doesn't work !!

I'm assuming your question is about D7. A possible answer to your question is to use the Views Rules module, as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of those users you want "to fetch into a list in rules" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

3. Create a rule using the view of display type 'Rules'
Create the appropriate Rules Actions in your rule, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.

Easy, no?


How hierarchical taxonomy comparison works I'm bit confused about how hierarchical taxonomy comparison will work when using Views.

For an example (using Taxonomy and Menu block modules) I've 2 level deep taxonomy:

1 Animal(10)
     1a Tiger(2)
     1b Deer(5)

What should normally be is whenever I want to search for Animal type then the View search should return total of 10+2+5 = 17 nodes.

I've just now checked that it will instead return 10.

How to get this correct functionality?

try structure -> taxonomy -> (edit your vocabulary) and at the bottom there is a checkbox

"Select to rebuild the menu on submit."

Please note:

"Rebuild the menu on submit. Warning: This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies."

Hit save and it should help


How do I prepopulate a field with calculated options, when user is editing node? Say the user is creating a node. I want to display a drop down option list, with prepopulated options, based on a calculation (i.e. reference to user's groups, user's other nodes, etc...). Drupal 7.

I've had no luck with the rules, computed field, prepopulate field modules... maybe i'm missing something?

Use hook_form_alter or hook_form_FORM_ID_alter to pre-populate your dropdown list with results returned from a custom function.

For example, using a form of hook_form_alter():

$form['field_my_field']['und']['#options'] = _my_custom_function();

Then make sure your function _my_custom_function() return's a proper array.

function _my_custom_function() {
    $custom_values = array();
    $custom_values['key1'] = 'value1';
    $custom_values['key2'] = 'value2';
    $custom_values['key3'] = 'value3';
    return $custom_values;
}

Obviously you can include some 'logic' in the _my_custom_function() to return your calculated list.

Here are a few super-useful link's I wish I would have know about before.

The Devel module has two functions that make hook_form_alter simple as pie... check out dpm() and dd().
The FormAPI page is priceless for all things hook_form_alter().
The Example Modules for Developers makes for an awesome intro to the FormAPI


Drupal Commerce or Ubercart to sell subscription for user (not for sell product)? I want to create a website like learning lessons, and user can watch this lessons when subscribe of this website .. like lynda.com

I studied drupal commerce and ubercart modules, but I still confuse which one is the best for this type of sites.

help me please
thank you

If you want to create a site like learning site. I think you can do this by using Course module.

  Create Drupal e-learning courses with any number of requirements for
  completion.

  There's a slideshow from Drupaldelphia and a video as well.


Filter content by own content or admin So I have an entity reference field on a node, the widget is a select-box.

I want so that an user can choose one of their own authored nodes as a reference OR if an admin is logged in, they can choose any content. So admins should be able to bypass this restriction (with a permission, role or something).

I tried building a view based on this, but the contextual filter seems to be the problem. I can't really do any either/or kind of thing with contextual filter.

Background

So I have an entity reference field on a node, the widget is a
select-box.

You (Risse) have already done this, but to make this clear for other users, this involves adding an entity reference field to a content type and in the field settings changing from the default 'Simple..' to 'Views..':

Now the select list used to choose a referenced entity (in this case a node), will use views to create the select list, allowing us to customise the nodes listed. In the example above I have created a view (and added an 'Entity Reference' display) and called it entity_reference_select.

I want so that an user can choose one of their own authored nodes as a
reference OR if an admin is logged in, they can choose any content. So
admins should be able to bypass this restriction (with a permission,
role or something).

It is easy enough to list only nodes by the current author using the filter "Content: Author uid" in the view (as per @molot above). Unfortunately this does allow us to differentiate the results for admin users.
An appropriate response might initially seen to involve an OR statement in the views filters to allow admin user to see all nodes in the select list, and other users to only see their own nodes. Unfortunately there are two issues with this:

There is no way to create a views Relationship to the current user in order to evaluate the current user's roles in the filters section
An OR conditional in the filters will remove options, not add them, so would  remove non authored nodes from an admin role user anyway

Solution
Provide a default value for a contextual filter which is defined by PHP. This means we can specify which user(author) we are going to filter the results by, which would be the current user (fetched from the global $user object) unless the current user has the 'administrator' role, in which case we list nodes authored by all users.


Remove orphaned module data after uninstall I have installed the xmlsitemap module, which is in alpha state. The module has an incomplete uninstall routine. Right now I am getting this error at /admin/config:

  User warning: The following module is missing from the file system:
  xmlsitemap in drupal_get_filename() (line 240 of
  core/includes/bootstrap.inc). drupal_get_filename('module',
  'xmlsitemap') (Line: 263) drupal_get_path('module', 'xmlsitemap')
  (Line: 134) module_load_include('install', 'xmlsitemap') (Line: 93)
  module_load_install('xmlsitemap') (Line: 82) drupal_load_updates()
  (Line: 109) Drupal\system\SystemManager->listRequirements() (Line: 96)
  Drupal\system\SystemManager->checkRequirements() (Line: 102)
  Drupal\system\Controller\SystemController->overview('system.admin_config')
  call_user_func_array(Array, Array) (Line: 123)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  (Line: 574)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
  (Line: 124)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array,
  Array) (Line: 97)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  call_user_func_array(Object, Array) (Line: 144)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line:
  64) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
  (Line: 57) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
  (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object,
  1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line:
  78) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
  (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1,
  1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1,
  1) (Line: 23) Stack\StackedHttpKernel->handle(Object, 1, 1) (Line:
  656) Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

There are dozens of entries in my database, which are related to this module. Is there any quick way, to remove the module's orphaned data?

Use following database query to remove the module:

Drupal 8

DELETE FROM key_value WHERE collection='system.schema' AND name='module_name'

Drupal 7

DELETE from system where name = 'old_module1' AND type = 'module'

See: How to fix "The following module is missing from the file system..." warning messages.


How to form_later the user profile form to only allow 1 role to be assigned/removed I want to restict my site editors ( a role ) to only be able to select/deselect the role 'subscriber' and not be able to meddle with the other role assignments.  I have tried the following to remove the other roles :

case 'user_profile_form':
  global $user;
  if(in_array('site editor', $user->roles)  && !in_array('administrator', $user->roles)) {
    unset($form['account']['roles']['#options']['3']);  // administrator
    unset($form['account']['roles']['#options']['4']);  // site editor
  }

However this has the effect of both hiding the checkboxes and un-assigning the roles.  I want any existing assignments to these roles to persist.

Your help appreciated.

Roles are removed because when the form is submitted those roles are missing (and thus unchecked). You can hide those options instead:

$form['account']['roles']['3'] = array(
  '#disabled' => TRUE,
  '#attributes' => array('class' => array('hidden'))
);

And some CSS .hidden { display: none; } or something.

  In D7+, form_process_checkboxes() and form_process_radios() already support you in doing so by allowing for partial sub-element pre-definitions read more


Easy way to create blocks programmatically? Learning Drupal. I know now that I can create block through the backend, but I would rather precreate them programmatically, if it's possible. In fact I'm pretty sure that it's possible. But what's the easiest way?

For Drupal 7:

Use hook_block_info and hook_block_view hooks in your custom module. hook_block_info defines the block. It will show up in admin > structure > blocks. *hook_block_view* displays the content. See examples below from the Drupal API.

Example of hook_block_info, where two blocks are defined (titled Syndicate and Recent content):

    <?php
function hook_block_info() {
  // This example comes from node.module.
  $blocks['syndicate'] = array(
    'info' => t('Syndicate'),
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['recent'] = array(
    'info' => t('Recent content'),
    // DRUPAL_CACHE_PER_ROLE will be assumed.
  );

  return $blocks;
}
?>

Example of hook_block_view:

<?php
function hook_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {
    case 'syndicate':
      $block['subject'] = t('Syndicate');
      $block['content'] = array(
        '#theme' => 'feed_icon',
        '#url' => 'rss.xml',
        '#title' => t('Syndicate'),
      );
      break;

    case 'recent':
      if (user_access('access content')) {
        $block['subject'] = t('Recent content');
        if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
          $block['content'] = array(
            '#theme' => 'node_recent_block',
            '#nodes' => $nodes,
          );
        }
        else {
          $block['content'] = t('No content available.');
        }
      }
      break;
  }
  return $block;
}
?>

Refer to the Blocks API page on Drupal.org for full list of hooks. Drupal 6 is a little different. There is no hook_block_view hook; instead use hook_block to declare blocks.


Create drupal content programmatically with custom entity ( assets ) I am using asset module : https://www.drupal.org/project/asset

I creates a new entity type = asset. I get a form where I can add ( document, image, video..).

How can I, from a custom module add a content of asset ? I think that I cannot do it the way we creat nodes ... like :

$node = new stdClass();
$node->type = "asset";
node_object_prepare($node);
....

Please help

thank you

I think you can try to use core and EntityAPI methods for this task like this:

$asset = entity_get_controller('asset');
$asset->type = 'MY_TYPE';
$asset->... = '...';
....

$asset->save();


hide result on same node in block (view) I have 3 pages, vacation1, vacation2, vacation3. Under each page there is a block-view with fields (title, image, summary) that links to the other pages. I want to have on vacation1 links to vacation2 and vacation3, but my views show all the results. I wan't to filter out the result of the current node. How can I set the filter for this?

You need to use the contextual filter option here. You can get current page nid using contextual filter as shown in screen shot and can filter out the result.


Why does #submit apply to all buttons? I have added a #submit handler to the default submit action on a node edit form:
$form['actions']['submit']['#submit'][] = '_app_submit_to_usercart';

and it works correctly. But I then add a 2nd submit button as:
  $form['actions']['save'] = [
    '#type' => 'submit',
    '#name' => 'Standard Save',
    '#value' => t('Print and Mail Check'),
    '#button_type' => 'primary',
    '#weight' => 6,
  ];

and for some reason the submit handler for the submit button gets run for this button as well. I am sure in my handler I can act depending on which button was pressed; but wondering why I need to do that.
EDIT
Apparently I am asking the wrong question. From my code above it seems that regardless of which button i click it is still submitting as if the main button is pressed. So question is how can i add another button (I have done this dozens of times in D7 and I thought a few times in D8; so not sure why this isn't working).

Give your submit button a unique and valid #name attribute. I don't think it will work if you put spaces in it:
$form['actions']['save'] = [
  '#type' => 'submit',
  '#name' => 'standard-save',
  '#value' => t('Print and Mail Check'),
  '#button_type' => 'primary',
  '#submit' => [
    '_my_module_form_submit',
  ],
];

Submit handler
function _my_module_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  \Drupal::messenger()->addStatus(t('Standard Save button triggered.'));
}


How do I remove the underscore a view adds to a rewritten link? I am using fields, one has a link, rewriting the link as shown below sending the datetime to webform in the URL. All fields display as they should. When hovering over the link, the URL shows extra space at the end of each field as an underscore as follows. The underscore is not in the datetime field.

  2018-05-14T15:39:15-0400_

As seen above the underscore is added. Webform wont prepopulate the datetime field element with the underscore. When manually writing the value, webform correctly prepopulates my webform.
The link is /appt_testform?apptdatet={{ field_apptdatet }}&body={{ body }}, which becomes /appt_testform?apptdatet=2018-07-15T18%3A00%3A00-0400_&amp;body=Testing%20the%20appt%2C%20test%20and%20recommend. The underscore after 0400 should not be there.

I see an underscore is added to other fields, which accept values where the datetime will not. I am trying to do this without using hook_form_alter().

After testing on 5 servers using different 8.x versions
When importing using feeds module CSV file,
If the content field is date and time..imported using feeds then View linked to webform to prepopulate it will add the underscore as shown in the original question.
If a field is timestamp (unix number in CSV) after importing, the view rewrite results link does not have the underscore added. I don't know why, however, my site works using the timestamp field type. On all the servers.

This issue happens when the field value is rendered with HTML (which is appended by Drupal date formats).
In your View, edit your time field and make sure to use Custom formatter rather than any of the predefined ones, and provide the custom pattern in 'Date/time format' field. And then underscore should go. Check this useful answer.
In my case I was struggling with underscore appended after Year value (mysirte.com/tag/1994_), and when I created custom format and used 'Y' the underscore disappeared, see picture:


How do you keep production site in synch with development site? I've got a Drupal development site where I test everything (modules, configurations etc.) before implementing on the production site. As it is right now, I need to write everything I do on paper and carry out the same steps on the production site.

How do you keep production sites in synch with development sites? Is there any handy modules out there for this purpose? To what extent can Drush help me out on this?

There are a number of approaches to synchronizing configuration between environments.

A few popular ones for Drupal 7 are:

https://drupal.org/project/features (recommended)
https://drupal.org/project/strongarm
https://drupal.org/project/configuration

For example with drush and features you can revert a component to the code definition with

drush fr my_feature

For more info on drush and features https://drupal.org/node/960926

In Drupal 8, exporting configuration has become much easier:

  With Drupal 8 you can deploy a configuration from one environment to
  another. This capability replaces the need for various contributed
  modules such as Features, Strongarm and Context.
  https://drupal.org/documentation/administer/config


Drush field-create with specified label I would like to add multiple existing fields to a content type using drush.  Right now I'm using the following to create the fields:

drush field-create [content-type] [field-machine-name],[field-type]

Is there any way to do something like the following instead?

drush field-create [content-type] [field-label],[field-machine-name],[field-type]

I am afraid you need to edit drush files to achieve it.. Currently label support is not there if you see below code in contributions/drush/commands/core/field.drush.inc

function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');

  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }

  // Iterate over each field spec.
  foreach ($args as $string) {
    list($name, $type, $widget) = explode(',', $string);
    $info = field_info_field($name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
      );
      drush_op('field_create_field', $field);
    }

    // Create the instance.
    $instance = array(
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);

    $urls[] = url(drush_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}
?>

As you see above only field_name and type is taken from args.. To create label also you need to change code to below

function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');

  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }

  // Iterate over each field spec.
  foreach ($args as $string) {
    list($name, $label, $type, $widget) = explode(',', $string);
    $info = field_info_field($name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
        'label' => $label,
      );
      drush_op('field_create_field', $field);
    }

    // Create the instance.
    $instance = array(
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);

    $urls[] = url(drush_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}
?>

and use command like

drush field-create [content-type] [field-machine-name],[field-label],[field-type],[field-widget-type]


Getting "Call to a member function getName() on null" in custom breadcrumb I'm trying to customize the breadcrumb of drupal 8 to get something like this:

Home > category >article-title.

I wrote this and I wrote the code below.

namespace Drupal\module_demo\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\taxonomy\Entity\Term;

class ArticleBreadcrumbBuilder implements BreadcrumbBuilderInterface {

    public function applies(RouteMatchInterface $route_match) {
        $parameters = $route_match->getParameters()->all();
        if(isset($parameters['node'])) {
            return $parameters['node']->getType() === 'article';
        }

    }

    public function build(RouteMatchInterface $route_match) {

        $breadcrumb = new Breadcrumb();

        $term = $route_match->getParameter('taxonomy_term');

        $breadcrumb->addCacheContexts(["url"]);

        $breadcrumb->addLink(Link::createFromRoute(t('Home'), '<front>'));

        $breadcrumb->addLink(Link::createFromRoute(t('Articles'), '<none>'));

        $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));

        $request = \Drupal::request();
        $route_match = \Drupal::routeMatch();
        $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
        if (!empty($page_title)) {
            $breadcrumb->addLink(Link::createFromRoute($page_title, '<none>'));
        }

        return $breadcrumb;
    }
}

but I have the error below.

  The website encountered an unexpected error. Please try again later.
  Error: Call to a member function getName() on null in Drupal\module_demo\Breadcrumb\ArticleBreadcrumbBuilder->build() (line 34 of modules/custom/module_demo/src/Breadcrumb/ArticleBreadcrumbBuilder.php).

Apparently the problem is with getName() and id().

Can someone tell me where the mistake is?

You can also use hook_system_breadcrumb_alter to achieve this:
Try this:

/**
 * Implements hook_system_breadcrumb_alter().
 */
function MyModule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  $node = \Drupal::request()->attributes->get('node');
  if ($node && $node instanceof Drupal\node\Entity\Node) {
    if ($node->bundle() == 'article') {
      // Add Articles item.
      $breadcrumb->addLink(Link::createFromRoute(t('Articles'), '<none>'));
      // Add category term item to breadcrumb.
      // Change here the field_tags with your taxonomy you want to add to breadcrumb.
      $term_id = $node->field_tags->getValue()[0]['target_id'];
      $term = Term::load($term_id);
      $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
      // Add title as breadcrumb item.
      $request = \Drupal::request();
      $route_match = \Drupal::routeMatch();
      $page_title = \Drupal::service('title_resolver')
        ->getTitle($request, $route_match->getRouteObject());
      if (!empty($page_title)) {
        $breadcrumb->addLink(Link::createFromRoute($page_title, '<none>'));
      }
    }
  }
}

Update: To fix the error.
Update the applies method to apply your breadcrumb only on articles as it mentioned in @Jdrupal answer:

  public function applies(RouteMatchInterface $route_match) {
    $parameters = $route_match->getParameters()->all();
    if (isset($parameters['node'])) {
      return $parameters['node']->getType() === 'article';
    }
    if (isset($parameters['term'])) {
      return TRUE;
    }
  }

The error comes from the line:

$term = $route_match->getParameter('taxonomy_term');

$term equal NULL its normal, you are in node page so the taxonomy_term param always null, so try to get your term from the node object something like:

 $node = \Drupal::request()->attributes->get('node');
 // Change the field_tags with your filed.
 $term_id = $node->field_tags->getValue()[0]['target_id'];
 $term = Term::load($term_id);


Double click quickly on the entity save form two entity get created I am using Entity Construction Kit 7.x-2.0-rc2. I have created one entity type with some manage field as title,message. if i double click quickly on creating entity then it will save entity form two or more entities get created.

Try Hide Submit

  Features:

  Hide or disable the submit button after it has been clicked

  Display a message and/or image while waiting


Multiple widget for same field? I have defined some extra fields for User information in configuration > account settings > manage fields.

One of these fields is of type List (text) and the widget I have chosen for it is Select List.

I want to display this field using Select List widget in Profile Edit Form but as Check boxes/radio buttons in User Register Form.

How can I do so?

By using form_alter hook you can alter the type of field. I am assuming you are using Drupal 7. The below code will alter the field_working_as List (text) profile field in user_register_form in to checkboxes.

And the same field will show as selectbox in profile edit page. I hope this will help you.

function mycustommodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    unset($form['field_working_as']['und']['#options']['_none']);
    $form['field_working_as']['und']['#type']='checkboxes';
  }
}


How to test a database connection? I'm writing a module that will have to make a connection to a seperate database. In order for the user to configure the database, I'm allowing the user to fill out the database connection info in the module configuration form.

How can I test the database connection before submitting the form?

I added the relevant code below:

function mymodule_form($form, &$form_state) {
  //Form code omitted
  $form['#submit'][] = 'mymodule_form_submit';
  $form = system_settings_form($form);
  return $form;
}

function mymodule_form_validate($form, &$form_state){
  // Validation code, test db connection, need help here.
}

function mymodule_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $database = array(
    'database' => $values['database_name'],
    'username' => $values['database_username'],
    'password' => $values['database_password'],
    'host' => $values['database_host'],
    'driver' => $values['database_driver'],
  );
  Database::addConnectionInfo('mymoduleDB', 'default', $database);
}

I don't see anything in Database or DatabaseConnection specifically. In a pinch you can just run a query that you know won't throw an exception in a Drupal site:

try {
  db_set_active('mymoduleDB');
  db_query('SELECT COUNT(nid) FROM {node}');
}
catch (\PDOException $e) {
  // Berate the user.
}
// PHP5.5+ only
finally {
  db_set_active('default');
}


Change field options after form has been filled with data When creating my form, I wasn't enough aware of the configuration for the default core description field. I don't want a summary field, but I did not pay much attention at that  when setting my form in the past. Now, when I try to change the field options to remove the summary field, I get the message "There is data for this field in the database. The field settings can no longer be changed.". Is it possible to override this restriction and force the change?

I'm guessing the type is Long Text with Summary. If thats the case, can't you just go to admin/structure/types/manage/[your content type]/fields/[your field name] and uncheck Summary input.

Drupal will then automatically create a summary if it's required to, just as it would if you had chosen Long Text (without summary).


No results behavior not working when using contextual filter with content id from url I have a problem displaying the no result behavior.
a view gives me an image depending on what page i am on. So i have setup a contextual filter of "content:nid". When the filter is not validated, i add a default value:"content ID from url".
When i go to the nodes, the image is shown. Nodes who do not have an image should show my default image that i put in the "no result behavior" section.

The problem now is, that the filter does not validate when there is no image and just shows nothing. How do i get my view to show the "no result" ?

Kind regards

Assuming you are working with the default Article content type of Drupal 7.x
Your Content Type

You should add something similar to this in your NO RESULT BEHAVIOUR of your IMAGE field in your VIEWS

I'm attaching the exported VIEWS code, you can check that, create 2 dummy ARTICLES one with IMAGE and another without an IMAGE but remember to store a no-result.png image in your sites/default/files/styles/thumbnail/public
Views Code
$view = new view();
$view->name = 'preview';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Preview';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Image View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['empty'] = '<img src ="../sites/default/files/styles/thumbnail/public/no-result.png" />';
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'preview';

Using the above VIEWS code you can access the output at http://<your-host>/preview/<nid>
Let me know if you face any issues.
Cheers!


Views image field linked with nofollow attribute I have a view that renders a list of articles. Each article has a title, a main image and a trimmed part of its body.

I have both the title and the image are linked to the content i.e the article's details. This is not good practice for SEO. I want to add the attribute rel="nofollow" to the links to the content of the image field.

I have tried to search for a module that may do this task but I could not find any.

Also, I have tried to use REWRITE RESULTS like the following:

[field_image]

However, it rendered wrong content because [view_node] tokens gives Read More html hyperlink.

By this way, to keep SEO, I have only to remove linking from image and this is not a suitable choice.

Is there any suggestion for modules do that or any way to rewrite the image field to be linked?

The following screen shot may offer extra visual details about my issue:

Add Nid field , exclude to display then in rewrite section instead

[field_image]

try

[field_image]


Print primary and secondary tabs separately I am creating subtheme of bartik theme.

According to page.tpl.php file of Bartik theme it shows that tabs can be printed by following code.

<?php if ($tabs): ?>
  <div class="tabs">
    <?php print render($tabs); ?>
  </div>
<?php endif; ?>

The above code prints primary and secondary tabs at a single place.

Now i want to print primary and secondary tabs seperately in template file.

Is there any variable which gives me the primary and secondary tabs seperately ?

Finally I ended up like this:

<?php
  $primary = menu_primary_local_tasks();
?>

<?php print render($primary); ?>

The above code will return the primary links:

To print the secondary links

 if ($secondary = menu_secondary_local_tasks()) {
    $output .= "
\n". $secondary ."
\n";
  }

Above code will return the secondary links for the theme.


Is it necessary to learn php in order to use drupal to manage my site? I am planning on using Drupal to manage a website. Should I learn PHP because I understand Drupal is built on PHP language?

I don't know PHP and I am not planning to learn it, but I have decided to use Drupal as my CMS, will I still efficiently manage my geospatial data handling site?

No, it's not "necessary". Drupal core has a UI to perform its basic functions, as do most contributed modules.

Beyond that, it's totally up to you to say whether you need to learn PHP, based on the level of customisation you need in your site

If all the functionality you'll ever need can be provided through the UI of whatever modules you decide to use, then no, you won't need to learn PHP. If all of that functionality isn't provided "out-of-the-box", then yes, you'll need to learn PHP.

As with anything, your mileage will vary. The only possible way to answer this question properly is for you to get stuck in and try it out for yourself.


Change individual file from public to private and vice-versa Running Drupal 7.  I have two file fields set up: One is public, the other private.  I need to be able to take a file which has been saved as a public file, and switch it to the private file field.  And, vice-versa.  Can someone provide some some advice on this?  Thanks!

I've written an update script to switch a file field from private to public:

function MYMODULE_update_7100(&$sandbox) {
  $field_name = 'MY_FIELD_NAME';

  $fids_data = db_select('field_data_' . $field_name, 'dat')
    ->fields('dat', array($field_name . '_fid'))
    ->execute()
    ->fetchCol();

  $fids_revision = db_select('field_revision_' . $field_name, 'rev')
    ->fields('rev', array($field_name . '_fid'))
    ->execute()
    ->fetchCol();

  $fids = array_unique(array_merge($fids_data, $fids_revision));

  // Move files using Drupal's File API
  $files = file_load_multiple($fids);
  foreach ($files as $file) {
    if ($file && file_exists($file->uri)) {
      $destination = str_replace('private:', 'public:', $file->uri);
      $directory = drupal_dirname($destination);
      if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY|FILE_MODIFY_PERMISSIONS)) {
        file_move($file, $destination, FILE_EXISTS_RENAME);
      }
    }
  }

  // Update field configuration
  $field = field_info_field($field_name);
  $field['settings']['uri_scheme'] = 'public';
  field_update_field($field);
}

What this function simply does:

Gets the fid of all files from field_data and field_revision tables.
Moves files using File API
Updates field configuration


Sort criteria is ignored in Views I have a view that shows related products by means of a contextual filter (PHP). If the returned nid values from the contextual filter is for example "20697, 20735, 20768, 20903, 20695, 21863" I want the nodes to be rendered in that order.

But they don't, I have tried all kinds of settings with no luck. The order given is in fact the delta of a certain field, but when I try to use the delta version of that field as a sort criteria, it is simply ignored, even if I add a relationship under "Advanced".

Anyone who recognizes this behaviour?

EDITED:
This is my contextual PHP filter. It fetches all the nid's entered in a certain node reference field as I explained above. And I want them to show in that same order, so that the admin user can sort the order by dragging the rows in the Node reference field:

$node = menu_get_object();
$value = null;
if(empty($node->field_lagg_till_givargrupp['und'][0]['nid'])){
    $node->field_lagg_till_givargrupp['und'][0]['nid'] = NULL;
    $value = FALSE;
         return $value;
} else {
        $limit = count($node->field_lagg_till_givargrupp['und']);
        for($i = 0; $limit > $i; ++$i){
            $group_nid = $node->field_lagg_till_givargrupp['und'][$i]['nid'];
            $group_node = node_load($group_nid);
            $limit2 = count($group_node->field_koppla_givare['und']);
            for($x = 0; $limit2 > $x; ++$x){
                $value .= $group_node->field_koppla_givare['und'][$x]['nid'].",";
            }
        }
        return rtrim($value, ",");
}

EDITED: this is the SQL query (I have added a few nids as an example);

SELECT node.nid AS nid, field_data_field_koppla_givare.delta AS field_data_field_koppla_givare_delta, field_data_field_koppla_givare.field_koppla_givare_nid AS field_data_field_koppla_givare_field_koppla_givare_nid, 'node' AS field_data_field_givargrupper_node_entity_type, 'node' AS field_data_field_huvudbild_givare_node_entity_type, 'node' AS field_data_field_tumnagel_givare_node_entity_type, 'node' AS field_data_field_underrubrik_givare_node_entity_type, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_artikelnr_produkt_node_entity_type, 'node' AS field_data_field_pris_givare_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_koppla_givare} field_data_field_koppla_givare ON node.nid = field_data_field_koppla_givare.entity_id AND (field_data_field_koppla_givare.entity_type = 'node' AND field_data_field_koppla_givare.deleted = '0')
WHERE (( (node.nid IN('20697', '20735', '20768', '20903', '20695') ) )AND(( (node.status = '1') )))
ORDER BY field_data_field_koppla_givare_field_koppla_givare_nid ASC

And this is the simple query without the delta field and without the order by criteria trying to sort in hook_views_pre_render() instead (see this question about that Sorting logic with anonymous function does not work):

SELECT node.nid AS nid, 'node' AS field_data_field_givargrupper_node_entity_type, 'node' AS field_data_field_huvudbild_givare_node_entity_type, 'node' AS field_data_field_tumnagel_givare_node_entity_type, 'node' AS field_data_field_underrubrik_givare_node_entity_type, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_artikelnr_produkt_node_entity_type, 'node' AS field_data_field_pris_givare_node_entity_type
FROM
{node} node
WHERE (( (node.nid IN('20697', '20735', '20768', '20903', '20695') ) )AND(( (node.status = '1') )))

As you can see I am really stuck in all ways about this ...

You can use a custom sort in your module like

/**
* Implementation of hook_views_query_alter().
 */
function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'your_machine_name_view') {
        $query->add_orderby('node', 'created', 'DESC');
    }
  }
}


Drupal 7.54 DATE_RFC7231 already defined After moving my Drupal site to a new host, I got the following error in the error logs.

  [error] 8707#0: *1 FastCGI sent in stderr: "PHP message: PHP Notice:  Constant DATE_RFC7231 already defined in /ext/vhosts/public/includes/bootstrap.inc on line 258

How can I fix it?

My site currently says "The website encountered an unexpected error. Please try again later"

My setup is as follows:

Debian 8
PHP 7.0.21
MySQL 5.6
Drupal 7.54

Are you certain you're running PHP 5 and not a version of PHP 7? I've only ever seen that error when running PHP 7, and it was due to DATE_RFC7231 already defined in PHP 7.0.19 and 7.1.5.

Either way, the patches in that issue were committed and released with 7.55, so it might be worth trying a core update before anything else.


Image styles are not created 404 Not Found I'm running on Nginx. All permissions are set to 777 and owner is www-data:www-data.

Create/edit a node with image_field, upload an image.
Original image is uploaded and stored at sites/default/files/image.jpg
Preview works, etc. Save node, no image shown (style Large or any custom).
Error 404 Not Found e.g. URL https://test.example.com/sites/default/files/styles/product/public/image-hd-wallpapers-3_0.jpg?itok=1E64uuXF
The styles subfolders are created like e.g. product/public even the sample.png file is created inside sites/default/files/styles/product/public/modules/image/
But no image style is created when uploading image to a node and saving.

I followed and tried everyting done in this image style (imagecache) images are not being created and this Aplying image styles to images return 404 for images

I have this in my nginx conf:

location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
    try_files $uri @rewrite;
}

Permissions:
htdocs/sites/default/files # ls -al

drwxr-xr-x 10 www-data www-data   4096 Feb 13 13:01 .
drwxr-xr-x  3 root     root       4096 Nov 17 12:58 ..
drwxr-xr-x  3 www-data www-data   4096 Nov 25 18:57 bootstrap
drwxr-xr-x  2 www-data www-data   4096 Feb  8 13:01 ctools
drwxr-xr-x  2 www-data www-data   4096 Nov 19 23:17 fonts
-r--r--r--  1 www-data www-data    476 Nov 17 13:00 .htaccess
-rw-rw-r--  1 www-data www-data 243154 Feb 13 12:40 image-hd-wallpapers-3_0.jpg
-rw-rw-r--  1 www-data www-data 243154 Feb 13 12:49 image-hd-wallpapers-3_1.jpg
-rw-rw-r--  1 www-data www-data 243154 Feb 13 13:01 image-hd-wallpapers-3_2.jpg
-rw-rw-r--  1 www-data www-data 243154 Feb 13 12:37 image-hd-wallpapers-3.jpg
drwxrwxr-x  2 www-data www-data   4096 Feb  8 21:22 js_injector
drwxrwxr-x  2 www-data www-data   4096 Jan 25 00:35 mailsystem
drwxrwxr-x  2 www-data www-data   4096 Nov 17 13:02 pictures
drwxrwxr-x  4 www-data www-data   4096 Feb 13 12:41 styles
drwxrwxr-x  3 www-data www-data   4096 Dec 29 13:00 videos

/styles/ incl. subfolders.

drwxrwxr-x  4 www-data www-data 4096 Feb 13 12:41 .
drwxr-xr-x 10 www-data www-data 4096 Feb 13 13:01 ..
drwxr-xr-x  3 www-data www-data 4096 Feb 13 12:41 large
drwxr-xr-x  3 www-data www-data 4096 Feb 13 12:41 product

I tracked down the issue causing it, but still need to figure out why it is causing it, because we need that setting to keep our images and other files optimized with correct headers, etc.

The issue is this snipped in the domain's nginx config:

location ~* \.(?:css|js|ico|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
    expires 1w;
    #add_header Pragma public;
    #add_header Cache-Control "public";
    add_header ETag "";
    add_header Cache-Control "max-age=2628000, no-transform, public";
}

Removing it, solves the problem, but we need to keep it.

The solution is to add try_files $uri $uri/ @rewrite; at the bottom right after add_header, final snippet with more edits:

location ~* /sites/default/files/.*\.(?:css|js|ico|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
    expires 1w;
    add_header ETag "";
    add_header Cache-Control "max-age=2628000, no-transform, public";
    try_files $uri $uri/ @rewrite;
}

This solves the issue, we use this snipped with AdvAgg module.


How can i add a block below the content of a node? I created many blocks and used them in my nodes regarding to contet types.

But i need another thing.
I created new block.
In the "/admin/structure/block" page i dragged this block to "Content" region.
The block appeared in content region. But it appeared above the node body.

In content part of "/admin/structure/block" there is 2 blocks:
"Main page content" and "My own block".
My own block is below the other block. But still it appears above the content body.
Should i pay attention any other thing?
Thank you.

In the Block UI at admin/structure/block toggle "Show Row Heights"

Set the weights manually to ensure they are correct.


node load multiple order by How can I order by weight using node_lode_multiple and the weight module ?

   <div id="photos_inner">
         <?php
           $type = "staff";
           $nodes = node_load_multiple(array(), array('type' => $type));
           foreach($nodes as $staff):
         ?>

No, results of node_load_multiple() are in the order in which the node IDs were passed to it in the first place. There are no other sorting options through that function.

The weight module doesn't appear to have an API for this, so you'll need to create a query that joins the node and weight_weights tables to get the nids in the right order, then pass them to node_load_multiple().


Custom login for specific role On a site there are some pages from a Content-type. Some of those pages (for the Belgium language only) need to be only accessible for Dokters.

So when you try to reach the URL of one of those pages you are redirected to a login-page.

But the role 'dokters' needs to have an extra login-field. Or only this field to login is even better if thats possible! It should be a field with 11 digits. Or if this is to complicated (Username, Password, 11-digit field).

How (which modules) are best practices to built this functionality?

UPDATE:

Now i managed to do a workaround with Content Access module. I made a role 'doctor'. And now only users with role 'doctor' can access those pages.

But is there something to do like when the Doctors visit those restricted pages they are redirected to a custom login-page. On this page you have a small form: Fill in your 11-digit code to access this page.

Because all doctors have their own 11-digit code. We don't have to send all doctors the username name and password for role 'doctor', instead they can access the content directly, with their 11-digit code! The only validation should be that the field contains 11 digits.

How do i manage this in the simplest/best way?

First, create a custom permission:

/**
 * Implements hook_permission().
 */
function MY_MODULE_permission() {
  return array(
    'access doctor content' => array(
      'title' => t('Access content for doctors'),
    )
  );
}

If the restricted content is a custom page you can do this:

/**
* Implements hook_menu().
*/
function MY_MODULE_menu() {
  $items = array();
  $items['doctor_page'] = array(
    'title' => 'Doctor page',
    'page callback' => '_doctor_page_content',
    'access arguments' => array('access doctor content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

If the restricted content is a node make sure there is a reliable way to filter that content in your code (e.g. by adding a checkbox 'Protected' to the node). Set access restrictions on nodes like this:

/**
 * Implements hook_node_access().
 */
function MY_MODULE_node_access($node, $op, $account) {
  // Check if the content is protected.
  if (!empty($node->field_protected_content[LANGUAGE_NONE][0]['value'])) {
    // If so, check if the user has access to it.
    if (user_access('access doctor content', $account)) {
      // Allow access.
      return NODE_ACCESS_ALLOW;
    }
    // Deny access.
    return NODE_ACCESS_DENY;
  }

  // Handle the default restrictions.
  return NODE_ACCESS_IGNORE;
}

Don't forget to add your custom permission to the user role via the permissions page (admin/people/permissions).


Stripping the wrappers in a custom field d7 I have a custom field in d7 and I output it as

 <?php print render ($content['field_product_image']);

The problem is it wraps around a whole load of stuff. How can I get in and edit this html?

I suspect somewhere in the field templates or using the api. I can live with the bloated html if I could get rid of the title on the a tag (title="Sample 1")

You can override field.tpl.php and its derivatives if you want to code it manually.

Or the Fences module might do the trick:

  Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

It lets you control the base markup for each field through the UI - a must have for any project these days in my opinion :)


Migrating paragraph items to their host nodes from Drupal 7 to Drupal 9? I am trying to do a Drupal 7 -> Drupal 9 migration using the UI. It was able to convert field collection types to paragraph types. I was also able to create a few custom migrations using the d7_paragraphs_item plugin provided by Paragraphs to migrate all paragraph items from D7 into the database.
Now I need to attach them to the nodes.
My migration yaml:
id: field_content
migration_tags: {}
migration_dependencies: {}
migration_group: yale
label: Field Content Paragraphs
source:
  plugin: node_items
  key: migrate
destination:
  plugin: 'entity:node'
process:
  nid:
    - plugin: migration_lookup
      migration: d7_node_complete:page
      source: entity_id
      no_stub: true
    - plugin: extract
      index:
        - 0
  title: title
  items:
    plugin: migration_lookup
    migration:
      - accordion_items_paragraph
      - editor_items
      - highlight_files
    source: field_content_value
  field_content:
    plugin: sub_process
    source:
      - '@items'
    process:
      target_id: '0'
      target_revision_id: '1'

Except this is only doing maybe 20% of the total. It would appear that its not pulling back all possible paragraph items to stick into the field, or maybe I am just thinking of it wrong.
The source plugin is returning a set of data from Drupal 7 for a field that held Paragraph references:
class NodeItems extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('field_data_field_content', 'fc');
    $query->join('node', 'n', 'n.nid = fc.entity_id');
    $query->join('paragraphs_item', 'pi', 'pi.item_id = fc.field_content_value');
    $query->fields('fc', [
        'entity_id',
        'bundle',
        'delta',
        'field_content_value'
      ]);
    $query->fields('n', [
      'title',
    ]);
    $query->condition('n.status', 1);
    $query->condition('fc.bundle', 'accordions', '!=');
    $query->orderBy('fc.entity_id');
    $query->orderBy('fc.delta');
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      'title' => $this->t('title'),
      'entity_id' => $this->t('entity_id'),
      'bundle' => $this->t('bundle'),
      'delta' => $this->t('delta'),
      'field_content_value' => $this->t('field_content_value'),
    ];
  }

"field_content" in D9 is a Paragraphs field. It does seem to plug some values, I do see items on various nodes. But its failing because I think the lookup doesn't always return a value or maybe it doesn't know what to do with them? Also the nid: mapping needs to support multiple node types, I passed one migration. There are 12. Can I add all of them there or ?
Is this the way to attach them to host nodes? Is there a better way?

I was thinking about this in the wrong way. The source plugin returns a list of results to migrate one at a time - the SQL query I was using would cause you to get for example, 5 rows for one node, each with a paragraph id. That is why only one paragraph was showing up on nodes at the end of a migration.
That isn't what you want - what you want instead is one row with the node id and 5 paragraph IDs.
I was able to do that by adjusting my source plugin query to the following:
  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('node', 'n');
    $query->join('D7_FIELD_NAME', 'fc', 'fc.entity_id = n.nid');
    $query->fields('n', [
      'nid',
      'title'
    ]);
    $query->condition('n.status', 1);
    $query->addExpression('GROUP_CONCAT(fc.D7_FIELD_NAME_VALUE)', 'paragraph_ids');
    $query->groupBy('n.nid');
    $query->groupBy('n.title');
    $query->orderBy('fc.delta');
    return $query;
  }

This produces a result set of
nid | paragraph_ids
-------------------
1     2, 4, 6, 8
2     13, 18, 12, 9
...........

Once you have that part, then you can fill in your Migration definition:
  D9_DESTINATION_FIELD_NAME:
    - plugin: explode
      delimiter: ','
      source: paragraph_ids
    - plugin: to_array
    - plugin: sub_process
      process:
        target_id:
          - plugin: migration_lookup
            migration:
              - accordion_items_paragraph
              - editor_items
              - highlight_files
            source: value
          - plugin: extract
            index:
              - 0
        target_revision_id:
          - plugin: migration_lookup
            migration:
              - accordion_items_paragraph
              - editor_items
              - highlight_files
            source: value
          - plugin: extract
            index:
              - 1

explode changes the comma delimited list into an array, and to_array is a small plugin I made to make it an array of arrays, each with an index of "value" and the id.
sub_process iterates over that and does a lookup against my other 3 paragraph migrations to drop the new destination id into target_id and target_revision_id.
The nid mapping from the original question still works, and passing multiple node migrations provides the full lookup capability. So for any nodes the result set returns, they are updated accordingly.
Now all migrated Paragraphs show up on their respective nodes in the correct order. I was able to apply this pattern to 3 different entity_reference_revision fields in Drupal 9 that held Paragraphs.


Views Configure contextual filter by user's country Drupal 7, commerce kickstart2.

Need to create a view with ContentType ProductDisplay. ProductDisplay has field Product. A Product has multiple field of a Country type.

User object has a property Country filed by IP2Country Module. The view need to show only products with user’s country.

View: type=page, link= /products (no other arguments in url expected), added releation Product

Here what I tried

Created Contextual filter: "Product: Country List (indexed)". Had to add index to this field so it can be select in contextual filter
Configured default argument for the "When the filter value is NOT in the URL". By using "hook_views_plugins" created "Current user's Country name" argument type. It is working and providing correct argument value  - user’s country

Didn’t manage to make it work. Also, tried some other things and spent few hours browsing web for a possible solution. Didn't find any similar problems or solution. There’re many examples with taxonomy terms and url args.

As a plan B,  think to create view for every country and override main view, but don't like it

Is a better solution to the task possible?

Thanks!

Found the problem!

All I did was correct, except one thing; I choose wrong View type during creation.

wrong: selected Show "Product display"

working: choose Show "Content" of type "Product display"

Don't know the difference, but it's working


How to add table column aliases I am trying to perform a query on a database that has the following info (in Drupal 7.21):

nid | sid | cid | data
----------------------
32  |  2  |  1  | date
32  |  2  |  2  | name
32  |  3  |  1  | date
32  |  3  |  2  | name
32  |  4  |  1  | date
32  |  4  |  2  | name
         etc..

I would like to perform a query on the database where I extract the following information in this manner:

nid | sid |    date    |    name
-----------------------------------
 32 |  2  | date_value | name_value
 32 |  3  | date_value | name_value
 32 |  4  | date_value | name_value

Where date and name are the actual values. Of course the result of this query would be an object. I am using the table display here to illustrate what I want to achieve in terms of data extraction.

My query looks like this:

$query = db_select('webform_submitted_data', 'sub1');
$query->innerJoin('webform_submitted_data', 'sub2', 'sub1.nid=sub2.nid and sub1.sid=sub2.sid');
$query = $query
  ->fields('sub1', array('nid', 'sid'))
  ->addField('sub1', 'data', 'date')
  ->addField('sub2', 'data', 'name')
  ->condition('sub1.nid', 32)
  ->condition('sub2.cid', 2)
  ->condition('sub1.cid', 1);

I thought the addField command would accomplish this but Drupal doesn't like it. What am I doing wrong?

Thanks.

Okay, I fixed it by doing the following:

$query->addField('sub1', 'data', 'date');
$query->addField('sub2', 'data', 'name');
$query = $query
  ->fields('sub1', array('nid', 'sid', 'data'))
  ->fields('sub2', array('data'))
  ->condition('sub1.nid', 32)
  ->condition('sub2.cid', 2)
  ->condition('sub1.cid', 1);

The issue was addField does not return an object so you can't chain the commands together. Also note that even though you aliased the colums to date and name you still need to refer to them as tablename.data. The aliased names will appear in the result of the query.


Drupal to Salesforce - Check if record exists before create I am using the Salesforce Suite to push Entity Registrations to Salesforce in our commerce workflow. The problem I am experiencing is that there is no checks to first see if the registrant exists before creating a new one. At the moment every registrant is a duplicate.

How can I make it do the following? Seems like it should be pretty straight forward but isn't there...

Check to see if Registrant exists based on a set of fields (email, first name, last name)
If so, update that record with information that is different and obtain the SFID
If not, create and obtain the SFID

This should be available regardless of record type, you should be able to check if something exists based on a series of fields.

If it needs to be done via a hook, I have been looking for documentation on how to use the Salesforce hooks to handle this but I can't find anything, so if you have any examples of how this can be done it would be awesome if you could share!

Looks like some work was done here for D6, https://www.drupal.org/node/507800 but it doesn't look like the changes were applied to the D7 rewrite.

I have solved this myself utilizing the hooks provided in the Salesforce Suite module. I wrote details about it in a 2 part blog post.

Customize Syncing Between Drupal Commerce and Salesforce – Part 1


Images not displaying on site (or in view source) after uploading them with ckeditor I've manually added the filtered Html option because it wasn't there with my drupal 7 installation. In the editor view I get the upload image option etc, and I am able to browse and insert images. However, after hitting save, the images aren't displayed on the site.

I am using IMCE file uploader.

What am I doing wrong?

The text format needs to allow <img> tags, otherwise they will be stripped out by default.

For example, add <img> to the allowed tags here:

admin/config/content/formats/filtered_html > "Limit allowed HTML tags"

Alternatively, try the "Full HTML" text format, if available and applicable as it will allow images by default.


Performance issues with Migrate Cron update I am running Migrate updates with cron every couple of minutes. I don't have many nodes (less than 100) but certain of them are data-heavy. Because of the wonky way my XML is written, I am forced to update all data every couple minutes. My site is now taking a real performance hit. Is this because I am running Migrate with cron? Or is there a way to force Migrate to update via hashes or something? I can't use the highwater field because my XML isn't ordered by update time.

Updating all nodes every couple of minutes is bound to kill your performance. It's write-heavy and invalidates caches and there is no way around it in any possible CMS, not only Drupal.

If you cannot decide which nodes needs to be updated on XML read, try to decide on export, and export only nodes that changed since last time. Perform full export-import once a day, deep at night.

Other way around it is to write a custom module that would perofrm following steps:

Download XML file to local variable
Compare checksums of current and previous XML

If checksums was equal, exit.
If checksums was different, perform import.

If changed update XML checksum.

That way you will only write anything if XML was changed - couple of times a day instead of every other minute.


How to select a Taxonomy term in a Pane's settings and send it as an argument to Views? I have a taxonomy vocabulary Help with several terms, representing different topics. I also have a Panel page where I would like to add Panes that contain all nodes with a certain Help term. My idea was to create a content View that accepts filtering on a provided Help term. Next, I would simply add this View to my Panel page and select the desired Help term from a list in the Pane's settings.

I more or less succeeded: my View has a relation Content: Taxonomy terms in node (where I selected the Help vocabulary) and a contextual filter Taxonomy term: name (where I set up an appropriate validation criterium Term name). This works fine, but I have to manually type the term name in my Pane's settings. That is not so efficient, because the term names might change in the future.

Is it possible to pick the desired term name from a list?

Maybe my initial request has a valid answer, but it is easier to forget about the contextual filter and only keep a relationship Content: Taxonomy terms in node to select the correct vocabulary. Next, filter on Taxonomy Term: Term and select the previously added relationship. Now you can select the required term from a list! Of course, you can duplicate the Views block as many times as needed and only override the taxonomy term. Finally, these blocks can be used in a Panel or elsewhere.


taxonomy_node_get_terms(arg(1)) kills layout in page.tpl.php I use this function to get the node's taxonomy term.

$tax = taxonomy_node_get_terms(arg(1));

Calling this function destroys the layout of the page. Why?

taxonomy_node_get_terms() needs a node object as the first argument; arg() returns a part of the URL (which is just a string).

You can use the menu_get_object() function to get the current node (if available) so it would be easier to use that:

$node = menu_get_object();
if ($node) {
  $tax = taxonomy_node_get_terms($node);
}


How do you sql-sync a site with multiple databases? I have a site that uses two databases.  I would like to sql-sync both of those databases to the development version of the site. Is this possible?

// Default
drush sql-sync @prod @dev

// Optional?
drush sql-sync @prod @dev --database=my_other_db

drush sql-sync @prod @dev --source-database=my_other_db --target-database=my_other_db


500 error during installation? Trying to install the new Drupal-COD Drupal 7 distribution, but got this error:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows

Is this the sort of error one can overcome by increasing my memory_limit in the php.ini file?

Removing the comment sign at "RewriteBase /" fixes my problem on migration of Drupal 7.
in the .htaccess file to fix.


Any chance for alter system settings form via hook_form_alter? I would like to create module based on other custom module. One thing that will be nice to able to do is to alter module settings form fields. Is this possible?

Do not forget at the end of your hook_form_alter() or hook_form_FORM_ID_alter():

$form = system_settings_form($form);

If you don't want to add the "Save configuration" button, you have to add your custom callback submit with $form['#submit'][] = '_my_callback_form_submit'; and :

function _my_callback_form_submit($form, &$form_state) {
  variable_set('my_variable_name', $form_state['values']['my_variable_name']);
}


How to set form element order with field_attach_form (and why does it do it?) Problem

I'm attaching the user register form to the add node form using hook_form_alter (for a custom content type). (Forcing an anonymous user to register when they create a node.)

My solution to this problem, has been to put a large chunk of the user register code into hook_form_alter (because I'm a "great" developer).

While this works in a custom form, in hook_form_alter the following function

 field_attach_form('user', $form['#user'], $form, $form_state, $langcode);

Causes the register fields to always appear in the middle of the form. (#weight does nothing.)

Reading through the documentation, it appears this function always puts the fields at the top of $form_state['values'] and you can change it by setting the #parents property on the incoming $form parameter.

2 Questions:

Why does the order in $form_state effect the display of my form? I thought the #weight property in the form elements determined this.
I don't really understand how to set the parents property. Do I need to create a parent which encompasses all of the standard node add form, and then set this new form relative to that?

More code in case it's wanted.

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

...

if (user_is_anonymous($user)) {

    $admin = user_access('administer users');

    $form['administer_users'] = array(
       '#type' => 'value',
       '#value' => $admin,
    );

    $form['#user'] = drupal_anonymous_user();
    $form['#user_category'] = 'register';

    $form['#attached']['library'][] = array('system', 'jquery.cookie');
    $form['#attributes']['class'][] = 'user-info-from-cookie';

    $account = $form['#user'];
    $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

    $form['#validate'][] = 'user_account_form_validate';

    $form['account'] = array(
      '#type'   => 'container',
      '#weight' => 61,
    );

    .... //form elements for user reg like password, username email etc. go in here...

    $langcode = entity_language('user', $form['#user']);
    field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
    foreach (field_info_instances('user', 'user') as $field_name => $instance) {
      if (empty($instance['settings']['user_register_form'])) {
        $form[$field_name]['#access'] = FALSE;
      }
    }

}

I can't really offer much explanation here but here's my solution. I suspect it has something to do with having a single form create two entities and how you need to separate that to allow both to be created.

The above created both, but didn't order the form correctly. The solution below does both.

The solution came from bundling up everything to do with user registration and attaching it inside a form container as opposed to just putting it in the form.

As I mentioned in the question, the documentation says this function always attaches to the top of the form, so you position the form container at the bottom then put it in that.

Here are the updated sections of my code, only two sections changed, the rest stayed the same. So you can just add the following parts to the code above.

   ....

   $form['account'] = array(
     '#type'   => 'container',
     '#weight' => 61,
   );

   //The new form container I added is below

   $form['user_reg'] = array(
     '#type'   => 'container',
     '#weight' => 62,
   );

   ....
   //added variables for clearer reading
   $account = $form['#user'];

   //The crucial part is the third parameter. This attaches it to a container rather
   //than the standalone form
   field_attach_form('user', $account, $form['user_reg'], $form_state, $langcode);


Cannot use object of type stdClass as array error in node save I built a custom form and one of them is of  type geocode with lat/lon fields. When I try to save the node I receive the following error:

  Cannot use object of type stdClass as array in
  /var/www/vhosts/example.com/httpdocs/modules/field/field.attach.inc on
  line 208\n'.

The error disappears when I put comments in this field. My question is how can I solve this since it is very important field (I try to create nodes with geocode locations)

Here is how I declare my field:

$form['field_locationmap'] = array(
    '#title' => 'geofield',
    '#type' => 'geofield_latlon',
  );

It seems that the error occurs when I m trying to pass the values to the object:

$location->field_locationmap->und->{0}->geom->lon=$form_state['values']['field_locationmap']['lon'];
$location->field_locationmap->und->{0}->geom->lat=$form_state['values']['field_locationmap']['lat'];

Assuming this is Drupal 7 field_locationmap is an array so your assignment should look something like this:

$location->field_locationmap['und'][0]['geom']['lat']

Also make sure that['geom']['lat'] is the correct structure for that value (i.e it is an array with two keys)
P.S. Consider using $location->language instead of 'und' in case you support multiple languages.


Contextual Filter for a Multiple Value Taxonomy Field I have a content type with a taxonomy field that allows multiple values (a set of positions within the organization).  I'm trying to create a view of some of these positions by passing a contextual filter via the URL.  I can make a hard coded filter for a specific position by entering a filter criteria that says the field must be one of whatever position I'm looking for.  However, when I try using a contextual filter instead, nothing is returned.  I'm guessing it's because the contextual filter is not using a "one of" comparison. How do I create a filter that will display content types with the given position from the URL?

Should be possible with View → Advanced → Your Contextual Filter → More → Allow Multiple Values.

Then supply values like "123+456" to get all that have either tid 123 or 456, or values like "123,456" if you only want those that have both terms applied.

Note this does not scale well because of the way Views does its SQL


Email validation '+' not accepting I have written email validation as follow.

if($email != ''){
             if (!ereg("^[_a-zA-Z0-9]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$",$email)) {
               form_set_error($email, t('Please enter a valid Email address.'));
             }
          }

But when i try to register with 'test.byme+1@gmail.com' , Not accepting with '+'. Can any one correct my code..Thanks

No need to reinvent the wheel: valid_email_address().


Attach custom css library to entity print output I need to attach custom css library so entity_print module uses it to generate the final PDF.

The goal is to get custom css effect the generated PDF at  /print/pdf/node/{{NID}}

I have set the PDF engine to mpdf under entity print configuration

I tried the following 2 methods unsuccessfully :

Attach to node.html.twig file using {{attach_library('THEMENAME/library_name')}}
Attach it to entity_print at THEMENAME.info.yml file per described at https://www.drupal.org/node/2706755

I don't see the attached css at /print/pdf/node/{{NID}}/debug when inspecting elements

Any help or pointers are appreciated.

I am answering my own question for the ones who might probably face similar issues.

The 2nd method as described at https://www.drupal.org/node/2706755 where we attach the library to entity_print works.

I had a custom entity-print--node.html.twig in which I missed printing the css styles using the variable {{ entity_print_css }}


How to wrap node output with a link using Display Suite? how would I best wrap my entire node in an  tag linking to the full node? My nodes are display using Display Suite and a custom view mode.

I'm guessing creating a php template and manually writing the link somehow would work?

A good option for this is Field Group Link.

For your case, basically you need to create a field group wrapping the whole node, and set the group type to 'Link'.