How to move the comment form to the top?

You can in field--comment.html.twig

{#
/**
 * @file
 * Default theme override for comment fields.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - content_attributes: HTML attributes for the form title.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 * @see comment_preprocess_field()
 */
#}

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}

So copy the above code and go to /themes/YOURTHEME/templates folder and create field--comment.html.twig and now paste code.

Now, all you gotta do is just move

 {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}

and place it above the {{ comments }} line

Flush/Clear the cache to see changes.


Another idea for this that you just create your custom module and form_alter function to modify or change the template for login/register/forgot password form. With this way you can handle everything but just in case you want to build your own module. If you want to do this way. I can give you the example code right here.

By the way which drupal version do you use


How to attach JSON data to JS variable without it being escaped

something like:

$variables['page']['content']['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with alert("Hello world!");.
       '#value' => 'alert("Hello world!");',
       // set attributes like src to load a file
       '#attributes' => array('src' => ''),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world'
  ];
}


How to hide the field names in a custom view?

In Drupal 7 with views 3 it works like this:
If you use fields as display format you can click in your field and disable the "Create a label" checkbox.


This cache is located in sessionStorage on modern browsers.

I'm just clearing the entire sessionStorage with window.sessionStorage.clear(); on logout to solve this problem. I could be more precise on this deletion, but it does not matter in this app.


Migrating into custom node type with multi value field

Nothing to do with destination plugins, what you need to do would be in the process pipeline. You could write a custom process plugin like, say, d6_cck_link. Or, you can use the iterator process plugin - see, for example, how d6_upload.yml in core populates the target_id/display/description columns of the 'upload' field.


Rules in Drupal 8 doesn't have much flexibility.
So in your case, you will do the following to achieve it.

Under Data selector, you will type: {{node.field_b_status.value}} and choose Direct mode instead.

And rest will be similar to your screenshot.


How do I get the field definition of a paragraphs image field

As it mention in comment just use paragraph instead of node.

$fieldDefinition = \Drupal::entityManager()->getFieldDefinitions('paragraph', 'your_paragraph_type_name');
    foreach ($fieldDefinition as $field_name => $field_definition) {
      if ($field_definition->getType() == 'image'){
        $settings    = $field_definition->getSettings();
        $resolution  = $settings['min_resolution'];
      }
    }


You can use Views module to create a block and place that block in your custom region

Here is the step by step process to create a slide show with slide show module
And  placing block in the region can be done here
admin/structure/block

To create custom block and template

/**
  * Implements hook_theme().
 */
function YOUR_MODULE_theme() {

$theme = array();

$theme = array(
    'my_custom theme' => array(
        'variables' => array('items' => array()),
        'template' => 'my-custom-theme'
    ),
return $theme;
}
/**
* Implements hook_block_info().
*/
function YOUR_MODULE_block_info() {
   $blocks = array();
   $blocks['slideshow'] = array(
   'info' => t('Block Name'),
);
return $blocks;
}
/**
 * Implements hook_block_view().
*/
function YOUR_MODULE_block_view($delta = '') {
   $block = array();
  switch ($delta) {
        case 'slideshow':
        $block['subject'] = '';
        $block['content'] = _YOUR_MODULE_slideshow_callback();
        break;
     }
   return $block;
 }
function  _YOUR_MODULE_slideshow_callback() {
  $result = "Your query to fetch content";
   foreach($result as $row){
       $items[] = $row;
       }
   $output = $output .= theme('my_custom theme', array('items' => $items));;
    return $output;
 }

and write html code for your slide show in my-custom-theme.tpl.php file


How to filter users based on address location?


You can use the Print module

  This module allows you to generate the following printer-friendly
  versions of any node:

  Printer-friendly version (webpage format) (at
  www.example.com/print/nid) PDF version (at
  www.example.com/printpdf/nid) Send by email (at
  www.example.com/printmail/nid) where nid is the node id of content to
  render.

And your choice of one of the 4 PDF libraries it supports. It does have very high memory requirements when generating PDF as previous comments have noted. It is well documented and the PDF output is fully themeable.


How should I add ID or classes to secondary tabs?

The theme function that render the single menu local tasks is theme_menu_local_task(), which is the function that output the <li> tags.

return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";

In a theme, you can implement an alternative of that theme function, using the code of that function as base; you then can add more CSS classes.

Supposing that your theme is "my_beautiful_theme," you need to create a "template.php" file (if it doesn't exist), and add the function my_beautiful_theme_menu_local_task() with the code for your theme function.

From a module is more complicated, but it has the pro of being applied for every theme you set in your site. If users are allowed to set a theme for themselves, you don't need to add that theme function in all the themes you enable, which also means not altering the code provided by other users. If you alter a theme you install, you then would lose your customizations every time the theme is update, and you install the update in your site.

With a module, you just need to implement something similar to the following code:

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['menu_local_task'])) {
    $theme_registry['menu_local_task']['function'] = 'theme_mymodule_local_task'; // The new theme function.
  }
}

function theme_mymodule_local_task(&$variables) {
  // Add here your code for the theme function.
}

For more information, you can look at hook_theme(), and hook_theme_registry_alter().


How do I create a local menu action to node/add/page?

Basing on this comment found on Local action links now provided by plugins using YAML discovery and implementing LocalActionInterface, this is the action declaration you should use.

amidori_utils.add_content:
  route_name: 'node.add'
  title: 'Add content'
  route_parameters:
    node_type: 'blog'
  appears_on:
      - view.admin_blogs.page_1

I take that, in your case, node_type should be simply blog, if that is the machine name for the content type you want to let users create.


how to insert image inside an existing image

It depends on your theme which you're using. Normally you've to create a block with image in its content and assign to the right region.

If you don't have the right region to assign to, try changing the existing content, or expand your theme and add new region based on your needs, or use Panels and replace your current page with custom layout (e.g. by using a flexible layout).


How do I pass a value from the url to a custom field in the registration form?

You can create hidden form elements in drupal simply by setting the type to hidden. So in your case, it could be achieved like so:

$form['field_recipientid']['#type'] = 'hidden';

You can access URL arguments in drupal via the arg() function. So if you want to pass something to the user register page and set it in your field_recipientid, you could do it by sending the user to the registration page via "http://example.com/user/register/MLRP_8UByesUEfeeIA".

Then from your same form alter function, just call arg(2) to get the third item in the path and set the value like so:

if (isset(arg(2))) {
  $form['field_recipientid']['#value'] = arg(2);
}

Note for anyone else thinking of doing this on other form elements that aren't hidden (e.g. text fields), use #default_value. If you set #value on text fields, drupal forcable only accepts that value, and disregards any edits to the text field value, the user might have made.

For more information on drupal's form api, see the forms api reference page on the drupal api site.


Force access denied on 'admin/structure/menu' for everyone except admin

Menus are cached, but decision making functions aren't. So what you need is:

function MYMODULE_menu_alter(&$items) {
  $items['admin/structure/menu']['access callback'] = 'MYMODULE_menu_admin_access';
}

function MYMODULE_menu_admin_access() {
  return $GLOBALS['user']->uid == 1; // Or whatever makes most sense for your use case.
}


commerce multicurrency module currency menu selector not switching currency in Shopping cart

Here is answer which finally worked for me.

https://www.drupal.org/node/1853638#comment-9385053


How do I use a views data with a paragraph?

The way I've done this is to preprocess the paragraph and alter the $variables['content'] to contain the views data/render array you've retrieved programatically:

function HOOK_preprocess_paragraph(&$variables) {
  if ($variables['paragraph']->type->target_id == 'yourparagraph') {
     //code to get the view you want
     ...
     ...
     $variables['content']['view_content'] = $theviewdata;

  }
}


You should create your own module for your hook_menu. It's not hard or bad in any way. :) It's also near trivial.

in sites/all/modules/custom_module create two files:

custom_module.info with

name = My custom module
core = 7.x

custom_module.module with (copied from linked to question)

<?php
function custom_module_menu() {
  return 'my_custom_callback/%' = array(
    'title' => 'My Custom Callback',
    'description' => 'Listing of blogs.',
    'page callback' => 'my_custom_php_function',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

And you have a new module with a hook menu entry. Replace core = 7.x with core = 6.x if you want this to work for D6 instead of 7. And replace custom_module everywhere if you call the module something else :)


In order for a Drupal contributed module to be eligible to be tagged as a security monitored project, one or more of the maintainers have to be 'vetted'.
Here is the main Drupal security policy on this.  See the "Which Projects are covered" section.  There is a link in this to the process of becoming 'vetted'.
Basically, you submit a Drupal.org project to a queue.  Eventually, security community members will review it for use of best security practices, code quality, and some other stuff.  If approved, the maintainer becomes 'vetted'.  Unfortunately, this process can take a long time to happen.
Once you have a project approved and are 'vetted', any other projects you maintain can be labeled as covered by the security community.


Solr server URL needs to include a scheme?

The issue was with the '#' character in the password which was failing the parse_url called in the module.


The problem here appears to be the location in which you are calling drupal_add_js(). The way Drupal works with form submissions, is that after processing is complete, it does a redirect to the page again. This way when you click back (or forward) in the browser, you don't get the message asking you if you want to post the data again. You are adding your JS in a processing function, which happens before the redirect, so it is getting lost after the redirect.

You'll need to find a different location to put your call to drupal_add_js(), that comes after the redirect. It should go in the same place where you are loading your script in the first place.


Okay, I wrote that line you're quoting above ("uri': This should always be the same as the site's folder name in the 'sites' folder."), but unfortunately that is an oversimplification that is not always correct, especially when using a Drupal 7 site.

This is what I say about "uri" in the Definitive Guide to Drupal 7:

  The URI used on the command line should be the same as when the site
  is being accessed from a web browser. It is also possible to use the
  name of the folder that contains the settings.php file for that URI
  (e.g. --uri=default).  This works, and is, in fact, equivalent to
  [back reference to an example that runs core-status using the cwd to
  select the Drupal site] in terms of the site URI that Drush will use
  when calling in to Drupal; you can confirm this by comparing the
  output of the "Site URI" line in [back reference to same listing] with
  this output.  Having a correct site URI is not always required, but
  some modules might need it if, for example, they are generating
  absolute URLs or making HTTP requests back to the same host; it's
  therefore advisable to set a correct URI whenever possible.

This quote is 100% correct for Drupal 7, but the situation is slightly more complicated with Drupal 6.  In D6, the value of the --uri option (and correspondingly, the URI used to access the site from a browser), will sometimes be written into the database.  For example, if your settings.php file is stored at sites/mysite.org/settings.php, and your URI (from the browser) is http://mysite.org, then you might in some circumstances find paths "sites/mysite.org/files/myuploadfile.png" in the database.  The URI from the browser is converted to the name of the folder containing settings.php before being used by Drupal (for some uses), whereas the --uri option passed to Drush is always used as-is.  Because of the fact that your site folders are written to the database, it's often handy to continue to use the sites folder "mysite.org" for your dev site "http://dev.mysite.org", and of course there's always the possibility that your sites folder is called 'default' (often a good idea on D6).  So, while --uri=dev.mysite.org and --uri=mysite.org and --uri=default may will all work (presuming a site http://dev.mysite.org which is a dev copy of http://mysite.org with its settings.php file in the default folder) to select the site for Drush, there are some edge cases where --uri=default is better in that the other options will not match what your modules are seeing when the same code.  On the flip side, there are also other edge cases where --uri=mysite.org is what you need to align your runtime variables with what your module will see with the browser (c.f. above dgd7 quote).  So the truth of the matter is that there is no value that is absolutely best for D6. The simplified advice you quoted above was used in the example file because things can really go wrong if you use --uri=mysite.org instead of --uri=default, AND a path is generated and written to the database, AND you migrate your database to another instance of the site, breaking the path.

For D6, the most pragmatic thing to do would be to name your sites folder 'sites/mysite.org' instead of 'sites/default' (and make sure that it is also 'sites/mysite.org' for http://dev.mysite.org).

I changed the advice in examples/example.aliases.drushrc.php as follows:

  'uri': In Drupal 7, the value of --uri should always be the same
  as  when the site is being accessed from a web browser (e.g.
  http://mysite.org, although the http:// is optional).  In Drupal 6,
  the value of --uri should  always be the same as the site's folder
  name in the 'sites' folder (e.g. default); it is best if the site
  folder name matches the URI from the browser, and is consistent on
  every instance of the same site (e.g. also use sites/mysite.org for
  http://dev.mysite.org).


Does DrupalWebTestCase::drupalGet() use the permissions of DrupalWebTestCase::$loggedInUser?

Permissions to access the page are considered. ContactPersonalTestCase::testPersonalContactAccess() uses the following code to check users has permission to access the right contact pages.

  // Test allowed access to user with contact form enabled.
  $this->drupalLogin($this->web_user);
  $this->drupalGet('user/' . $this->contact_user->uid . '/contact');
  $this->assertResponse(200);

  // Test denied access to the user's own contact form.
  $this->drupalGet('user/' . $this->web_user->uid . '/contact');
  $this->assertResponse(403);

  // Test always denied access to the anonymous user contact form.
  $this->drupalGet('user/0/contact');
  $this->assertResponse(403);

  // Test that anonymous users can access the contact form.
  $this->drupalLogout();
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
  $this->drupalGet('user/' . $this->contact_user->uid . '/contact');
  $this->assertResponse(200);

$this->web_user, and $this->contact_user are initialized using the following code.

$this->web_user = $this->drupalCreateUser(array('access user contact forms'));
$this->contact_user = $this->drupalCreateUser();

If the permissions assigned to the test user would not be considered, the first test would fail, as only users with the "access user contact forms" permission can see the contact page of another user, and by default users don't have that permission.


Drupal core doesn't redirect everything. Do you have the Redirect module installed? Then disable the route normalizer in the module settings, which is by default enabled:
/admin/config/search/redirect/settings

GLOBAL REDIRECTS
[x] Enforce clean and canonical URLs

If you want to keep the global redirect try this module specifically for the language prefix Disable Route Normalizer.


SMTP Authentication Support + Unable to send e-mail

Looks like Gmail needs SSL encryption, so I had to select that in the list of encryption, my bad!


Drupal 7 Commerce Stock Decrease stock when reverting cancel the order

It can be done using hook_default_rules_configuration().
Below is my code:

<?php
/**
 * implement hook_default_rules_configuration().
*/
function phponwebsites_default_rules_configuration(){
$rules = array();
$rules_export = '{ "phponwebsites_rules_decrement_stock_revert_cancel" : {
            "LABEL" : "Stock: decrease when revert canceling the order process (cloned)",
            "PLUGIN" : "reaction rule",
            "OWNER" : "rules",
            "TAGS" : [ "stock_control" ],
            "REQUIRES" : [ "rules", "commerce_ss", "entity" ],
            "ON" : { "commerce_order_update" : [] },
            "IF" : [
              { "data_is" : { "data" : [ "commerce-order:status" ],
                  "op" : "IN",
                  "value" : { "value" : {
                      "pending" : "pending",
                      "processing" : "processing",
                      "completed" : "completed"
                    }
                  }
                }
              },
              { "data_is" : {
                  "data" : [ "commerce-order-unchanged:status" ], "value" : "canceled"
                }
              }
            ],
            "DO" : [
              { "LOOP" : {
                  "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
                  "ITEM" : { "list_item" : "Current list item" },
                  "DO" : [
                    { "commerce_ss_decrease_by_line_item" : { "commerce_line_item" : [ "list-item" ] } }
                  ]
                }
              }
            ]
          }
        }';
   $rules['phponwebsites_rules_decrement_stock_revert_cancel'] = rules_import($rules_export);
 return $rules;
}
?>


Commerce - Theme Add-to-Cart form on Product Display page

Here's a good start on your first form alter for add to cart:

function MODULENAME_form_alter(&$form, &$form_state, $form_id){
  // Add to cart form overrides
  if(substr($form_id, 0, 30) == 'commerce_cart_add_to_cart_form'){
    kpr($form);
  }
}


What you are looking for is now called upcasting, the handbook page is https://www.drupal.org/node/2122223

I do not think options is necessarily for entity upcasting. For example, check the node.type_edit in core/modules/node/node.routing.yml for a routing definition not using any options (or user.admin_permission in user).

As with your previous question, I wonder whether your entity class properly defines its storage controller? If you have a debugger, the parameter conversion happens in core/lib/Drupal/Core/ParamConverter/EntityConverter.php


Ubercart product quantity count in product view page show as smsung 2/10 sold?

This is not an answer, but you can find the stock level using the below code, just put in the node.tpl.php, and print the var $stock_html in a proper place, probably in node-product.tpl.php <?php print $stock_html ?>  .

<?php
if ($node->type == 'product') {
  $arr_sku = uc_stock_skus($node->nid);
  $stock_html .='
';
  foreach($arr_sku as $sku){
    $stocklevel = uc_stock_level($sku);
    if ($stocklevel) {
      if ($stocklevel < 1) {
        $stocklevel = ''.$stocklevel.'';
      }
      $stock_html .='
'.$sku.'	:&nbsp;&nbsp;'.$stocklevel.'
';
    }
  }
  $stock_html .='
';
}
?>

or you can try this http://www.ubercart.org/comment/60577


How to remove malicious scripts from admin pages after being hacked?

If you suspect that your code has been altered, you should track any malicious code which could infect your webroot.

If you've access to the server terminal, try the following suggestions, otherwise sync the files into your local machine in order to run below commands.

Here are few general solution to get rid of the attacker:

Use some tools to scan for malicious PHP files (e.g. php-malware-finder, php-malware-scanner, phpscanner).
Look for your webroot for any suspicious files consisting base64_decode/eval which most commonly are used for obfuscation, e.g.

grep -R return.*base64_decode  .

If you found one, probably you've multiple of them. If so, please check: How to get rid of eval-base64_decode like PHP virus files thread for further suggestions.
If you know some specific pattern of the malware appearing in your source code (which you do), try scanning your code base for this name, e.g.

grep -R gymweb .

And depending on where these URLs were added, remove extra code or restore to the original version (either from VCS history or your recent backup before the infection).

If above won't help, try these suggestions which are more Drupal oriented:

When using code under version control (like Git), find the files which are not suppose to be there (git status) and remove them (git clean -f .).
Upgrade your Drupal core, to replace any modified files (drush up drupal).
Upgrade contrib modules using drush (drush upc --no-core).
Also scan your entire database for this name:

drush sql-dump --ordered-dump | grep gymweb

If this still won't help, compare the code base from the backup before the infection with the current one (either by diff -r, using some diff GUI tool or use Git).

Check also:

How to get rid of eval-base64_decode like PHP virus files?
What does this malicious PHP script do?


Socially ranking content is a feature Drupal can provide very well. You will want to use a combination of modules consisting of something like:

Views (used to build the lists of content and order them by votes / popularity),
Voting API (a frame work for scoring / aggregation and will be used to record votes)
Vote up/down (Vote up/down widget for user input on voting). you can even look at something like Fivestar.

Once you have chosen and setup your voting widget on your content you will need to setup some views to display them in lists order by votes. Typically you will create a page view for any landing pages such as a Home Page and a block for displaying in sidebars on content pages. I also use Quicktabs for the Blocks so you can have a nice tabbed interface which lists content by Most recent / Highest Rated / Most viewed etc.

On setting up the actual views you will need to add in fields for what you would like to show in each list. For example on a highest rated you might want the node title and the score for the node as voted for by users. Then you will add in a sort by option for the score so the list is presented in the correct order


Programmatically added block does't appears in block admin page

Did you use the button "Place block"? The block does not appear in the block layout by itself. The block layout is a bit misleading by providing the disabled section, which suggests that all blocks not used are listed there.

The technical background is, that the block layout only lists blocks that have a configuration. When you install a module with a block plugin this block is not registered with a configuration entity yet. That happens when you press the button "Place block" for the first time. You can do this multiple times to get multiple instances of the block. The configured blocks will keep their configuration entity and will stay in the block layout, even when disabled.


Executing PHP code only once, when the node is created

You should use hook_node_insert in a custom module to run your code when the node is created.

function hook_node_insert($node) {
  // To include @marcvangend's comment.
  if ($node->type == 'type') {
    // Run code here only for node of type 'type'.
  }
  // Run code here for all nodes...
}


country based product price should be changed in commerce kickstart?

You can use IP based Determination of country module for identify the user ip address and the country.

You can use Commerce Multicurrency module for INR price field in the products content types.

By using Rules module to change the price for indian users


Best way to optimize for authenticated user performance?

Every site is different, thus it will require different tricks to get it working. Here are the ones I use for our sites for logged in performance.

http://drupal.org/project/dbtuner
http://drupal.org/project/advagg
http://drupal.org/project/labjs
http://drupal.org/project/css_emimage
http://drupal.org/project/imageinfo_cache
http://drupal.org/project/cdn

If you REALLY want to know what is causing the slow code, get a cache grind of your site. What all contributes to drupal page execution time?

edit: Looks like the 7.x version of Auth Cache is starting to be developed. Haven't used it but something to look into.

http://drupal.org/project/authcache


On you THEME.libraries.yml:

global-styling:
  version: VERSION
  header: true // <--- To the header!!!
  css:
    theme:
      css/mystyle.css: {} // if you want add custom css
  js:
    js/stepcarousel.js: {}
  dependencies:
    - core/drupal // for use drupal.js
    - core/jquery

On you THEME.info.yml:

name: THEME
base theme: Bartik
...
libraries:
  - THEME/global-styling
...

and Clear Cache

  Where is page.tpl?

Here: core/modules/system/templates/page.html.twig

If you want use it, copy to theme folder inside templates, like this:

 THEME
   templates
     page.html.twig

Change all you want and Clear Cache


Drupal 7: notify user module recommendation

For the record: The Notifications module will not do what you want.  But worse, the D7 port is in alpha and hasn't progressed since 2011-Dec-04, there are 217 bugs in the issue queue and no maintainer in sight. Its maintenance status is listed as "Seeking new maintainer".  In other words, this yet another abandoned Drupal module. Unless you're prepared to adapt and maintain this yourself - stay away.

There is a survey page for notifications modules, but it only confirms that what is called a "Notification" module by Drupal developers provides email notification, which is not what you want.  The type of notofication you want tend to be referred to as "flags" by Drupal developers, so you want to search for "flags" in addition to "notifications".

To get on-screen Javascript notifications (similar to Facebook and Stack Exchange), my suggestion for a starting point is to see whether you can combine the Flag module, the Message module and the Rules module to do what you want.  But to get these three modules combined to produce the desired effect will not be trivial.

An alternative solution (first mentioned in a comment by Nigel Waters), you could use the Message module to create the activity stream. Then use Views to generate the stream applicable to the currenly logged in user. And finally use the Menu Badges module to display the number of notifications.

You may also want to read: How to create a basic message - notifications system displaying a real time message counter badge?


Which type of page to use for a customized front page in Drupal 7?

I always tend to use the Context module.  Just set up a front page context that doesn't load all the unnecessary items (blocks, breadcrumbs or whatever) then have any node/panel you fancy as a home page without all the extra items that you don't need rendered onto the page.  It does seem slightly overkill to have an entire content type dedicated to one node though, I agree with that.


How to access values from earlier steps in multi-page Webform?

This does not answer the question in your title, but reading your use case it sounds like the scenario that Profile2 was written for.  Related stackoverflow post

Webform is great for surveys and such, but when you want "to be able to use them as default values for future fields" they need to be connected to the user.  So you would then need more custom code to fetch the user's historic webform submission to pull these values in a form alter for your billing address.  Profile(2) is written precisely to make this easier.

Also, the less last-minute custom coding you are doing before handing this off to some one else, the less that some one else will curse you in their heart when they are trying to make updates.


Custom module search ranking not working + ranking admin settings not showing properly

Finally I cracked this frigging case!
As it turns out, there was no way for anyone to be able to answer this question since my given information was incomplete. Although in my defence if I knew that I should've given that info, I would've solved the problem long ago(two days) :-D.

Solving problem #1:

Dead simple! In my case I had commented out the following line inside hook_search_execute():

_node_ranking($query);

this functions adds the rankings to the results.

Solving problem #2:

As for this problem, the influence choosing form doesn't show up automatically. The node module, if active in the Active search modules, lists all the factors for all Search active modules. But for a module to list its own factors, it must implement the hook_search_admin() function like this:

function hook_search_admin() {
  // Output form for defining rank factor weights.
  $form['post_ranking'] = array(
    '#type' => 'fieldset',
    '#title' => t('Post ranking'),
  );
  $form['post_ranking']['#theme'] = 'node_search_admin';
  $form['post_ranking']['info'] = array(
    '#markup' => '
' . t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '
'
  );

  // Note: reversed to reflect that higher number = higher ranking.
  $options = drupal_map_assoc(range(0, 10));
  foreach (knowledge_ranking() as $var => $values) {
    $form['post_ranking']['factors']['node_rank_' . $var] = array(
      '#title' => $values['title'],
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => variable_get('node_rank_' . $var, 0),
    );
  }
  return $form;
}


I needed something similar: user purchased an item (points) and depending on the purchased product a value (points) should be added to the user profile. The rule below is ready to accept (loop through) multiple products/lineItems. In my case I only need the first one:

 "value" : [ "commerce-order:commerce-line-items:0:line-item-id" ],
        "limit" : "1"

First I fetch the purchased products (line items) by property (line_item_id). The result is an array (list of purchased products).

Next you need to loop through this array/list and add the desired action to the individual/current purchased product. If you need a condition (product 1 -> role 1) you can use conditional rules. It is an awesome rules addon that lets you insert IF conditions within loops (so you dont have to create a component that checks the product).

{ "rules_purchasing_points" : {
"LABEL" : "PURCHASE Points",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"DO" : [
  { "entity_query" : {
      "USING" : {
        "type" : "commerce_line_item",
        "property" : "line_item_id",
        "value" : [ "commerce-order:commerce-line-items:0:line-item-id" ],
        "limit" : "1"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "data_convert" : {
            "USING" : { "type" : "decimal", "value" : [ "list-item:line-item-label" ] },
            "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
          }
        },
        { "component_rules_set_points" : {
            "recipient" : [ "site:current-user" ],
            "sender" : "1",
            "points" : [ "conversion-result" ]
          }
        },


How to lock in the Sort Order for view display?

You want the Nodequeue module.

You can make a queue and add nodes to it an arbitrary order. All queues have an associated view that gets created, and can be used anywhere you use a view.


How to get the node from the url referer?

This method works for me:

use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
// Getting the referer.
$request = \Drupal::request();
$referer = $request->headers->get('referer');
// Getting the base url.
$base_url = Request::createFromGlobals()->getSchemeAndHttpHost();
// Getting the alias or the relative path.
$alias = substr($referer, strlen($base_url));
// Getting the node.
$params = Url::fromUri("internal:" . $alias)->getRouteParameters();
$entity_type = key($params);
$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);

//to use dpm you need the devel module
dpm($node->id());
dpm($node->title->value);


The Mobile theme module conflicts with the default cache

I don't think there's a straightforward solution to this in Drupal7 but there are some workarounds available:

Use JavaScript to detect and do the switch
This issue happens because D7 uses page URL as page's cache id (CID). To distinguish different devices for same page, you'll need to alter the CID somehow so it looks something like CID_phone, CID_tablet and CID_desktop. I used mobile_detect module before and know there are some patches on this. Do keep in mind there's a side effect that this approach will triple the amount of CIDs in you database table.
If you use Varnish you can try something like this


Check if the page is the front page in a template

You should not declare a function in a Drupal template. Instead, you should just refer to that function:

<?php
if (drupal_is_front_page()) {
    ?>
Test
<?php
}
?>


Get Field Manage Display configuration in node preprocess

As @googletorp commented, the field should be rendered automatically considering the Manage Display configuration.

In my case [I was a node which has reference to paragraph A and A has reference to paragrapgh B which has a date field. The twig template markup needs heavy customisation so I was preprocessing the data to make it consumable by custom twig templates, now in order to get the date field show on node I have to load referenced paragraph entites and map the fields, because of which the fields was not rendering through the '#theme' => 'field' and Manage Display configs were not working.

But in order to make it working while mapping the field values we can can actually call for rederable field definition, something like

$date = $entity->field_date->view('full');


Is there a way to export ALL translations into a single .PO file?

Each entry in .po file has only two strings;

msgid untranslated-string
msgstr translated-string

Thus, by it's very nature it can only keep two languages: original and one translation. So no, there is no way to do it because format does not support that. For details, see documentation.


showing translation of the related node in view

You can use the Translation redirect module (part of the Internationalization module) if your users are anonymous (unauthenticated). It just issues a 301 redirect whenever translated content exists.

If your users are logged in then there is another approach I have used, use an URL alias for your nodes. Set the alias to be the same for all translated content of a node and when linking to that node use the URL alias instead of the node number.


How to group content in view by taxonomy terms?

I don't think a single View can you your job.

In the case you have fixed Term a non best practise approach will be to create 3 Views and a custom module

Views:

Create new view without add a page or a block
Add a filter to taxonomy term = 'Term 1'
Limit the results to the desired number, remove pager, add read more link.
Do the same for Term 2 and Term 3

Module:

term_display.info

name = 3 Term display
description = Display the articles of 3 terms
core = 7.x
package = My custom modules
version = 7.x-0.1

term_display.module

<?php
/**
 * Implements hook_block_info().
 */
function term_display_block_info() {
  $blocks['term_display'] = array(
    'info' => t('term display'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function term_display_block_view($delta = '') {
  // Initialize a block array.
  $block = array();
  // In case that we have more that one blocks the $delta will define witch one
  // to render.
  switch ($delta) {
    case 'term_display':

      // Give a block title.
      $block['subject'] = t('Term Display');

      // Tells the theme to render the content using ul list.
      $block['content'] = theme('item_list', array(
        'items' => term_display_create_items(),
        'type' => 'ul',
      ));
      break;
  }
  return $block;
}

/**
 * Create the items that will be render in the block.
 *
 * @return array
 *   Return an array of the block's items.
 */
function term_display_create_items() {
  // Initialize the items that will be rendered.
  $items[] = array(
    'data' =>  'Term 1' . views_embed_view('trem_view_1', 'default'),
  );
  $items[] = array(
    'data' =>  'Term 2' . views_embed_view('trem_view_2', 'default'),
  );
  return $items;
}

All the job is done in term_display_create_items() that embeds the View views_embed_view('VIEWS_MACHINE_NAME', 'DISPLAY_ID');

A better approach will be to give the Term as a parameter to the views_embed_view() and fetch it from the View. So you will have a single View that uses Contextual Filters to give you your results. But follow the above steps and you will find your way ;)

A third and more dynamically solution is using the Views Field Views but it will add a huge overhead to your site + will take more time to build it.


How to update role name progammatically in Drupal 8

If you already have the role object loaded:

$role
  ->set('label', 'New label')
  ->save();

If you don't:

$role = \Drupal::entityTypeManager()
  ->getStorage('user_role')
  ->load('client')
  ->set('label', 'New label')
  ->save();


7 - Views Filter where one field equals Logged in User's Email field

Add your "Assigned to" field as contextual filter, and set "provide default value" to PHP code just like you were thinking, but change your php snippet to return a value instead of printing:

global $user;
return $user->mail;


How can I programmatically get a list of orders purchased by a specific user?

to get ALL orders of a user - get user ID ($user_id)
then

$orders = \Drupal::entityTypeManager()
  ->getStorage('commerce_order')
  ->loadByProperties(['uid' => $user_id]);


Numerous dependencies don't get installed with "drush en -y" command for rooms module

Drush will only check the .info file for dependencies, in the case of the Rooms module those are:

dependencies[] = date
dependencies[] = date_api
dependencies[] = date_popup
dependencies[] = jquery_update
dependencies[] = libraries (>=2.x)
dependencies[] = variable

If Drush is missing any of those out, you have a buggy version of Drush and need to get an issue opened for it (or check for a similar existing one).

Other than that any "missing" dependencies are either down to a bug in the Rooms module, or your expectations being incorrect.

For example, maybe you're expecting Drush to auto-download all of the dependencies for the sub-modules included with Rooms as well?

It won't, those are considered separate modules. If you want those dependencies downloaded/installed automatically, you'll need to run drush en for each module individually.


Just a suggestion.

As hook_init is only called on non-cached page, and you require this JS to be called on every page; why don't you go ahead and add it to your theme's .info file?

scripts[] = js/stickyMojo.js


Views: Link Title using Text URL field (GUID)

Assuming that you know the link and can construct it from the GUID field (either by some/text/[guid_field_machine_name]/maybe/more/text or just [guid_field_machine_name] or what have you):

Using the dropdown arrow to the right of the Fields section of your view, select "Rearrange"
Move the GUID field above your title field and save
Make sure your title field no longer has the link box checked off, because we're going to use a different link box.
Click on the title field to pull up the settings where you unchecked the link box. This time, select the Rewrite options.
Select the link option under the rewrite options. This will show you a text box where you can use fields that appear above the title field in your rearranged list of fields in a link to add to the title field. In this box you should put your GUID url, using [guid_field_machine_name] for the GUID field.

If you have questions, let me know, I can definitely provide more specific directions with a bit more information from you, like what exactly the GUID field contains and stuff.


How can I hide menu items based on permissions?

Hi have done it this way:

function mymodule_menu_link_alter(&$item)
 {
  $item['options']['alter'] = TRUE;
 }

function mymodule_translated_menu_link_alter(&$item, $map)
 {

  if (!empty($item['access'])) {

  if(
   ( $item['link_title']=="MyLinkToHide1" && !user_access("access link 1") ) ||
   ( $item['link_title']=="MyLinkToHide2" && !user_access("access link 2") )

   )
   {
            $item['access'] = FALSE;
   }

 }
}


Entity reference field on select show some data about entity

There is an option to use views for populating the dropdown in the entity reference fields. Since you are building the options using views, you can pretty much customize it as you want.

Check out this video http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7 for more details.

----------------THIS PART ADD BY QUESTIONER-----------------

Thanks to Gokul N K.

This tutorial made what i want in the view mode. What to do in the edit mode?

Create a custom module
Hook form_alter
Add a HTML div just below the autocomplete field
Inject some JavaScript and bind the auctomcompleteSelect trigger on your specified field.
In the bind function add an ajax callback to acquire your desired information and display it inside the div.


How do I hide an article if it doesn't have an image?

You can put a condition on view filter. If image field is empty then row will not display.

  Content: field_image:fid (not empty)

OR

  Content: Slide image:fid (!= 0)


How to make a calendar tab for every user showing user's events?

Clone the default view "OG all user group content" provided by Organic Groups. Filter content type based on events and thats it. This displays all the events from all the groups the user is subscribed to.

You can also change the display style to calendar and add a bunch of other settings.


Solved this by creating a Menu showing processing message and redirect it using :

      window.parent.location = "thankyoupage";


Calling Module function from jQuery and Ajax

Hopefully this will help -- got this code from a Lullabot module development training.

It all revolves around a hook_menu callback.  The value in 'page callback' is the function that will be called, in this case it is: "menu_magic_page"

So Drupal looks for the menu_magic_page() function.

Your jQuery / AJAX call would then reference the value what's in $items['X'] where X is "magic" here.  So hitting http://example.com/magic would run the module function "menu_magic_page"

FWIW: the type/MENU_CALLBACK ensures it doesn't get added to menu's etc.  It just ensures Drupal is ready to process it.

Hope this helps.

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

  /**
   * This is a simple callback.
   *
   * This will create a path at http://example.com/magic. When visited, that
   * URL will trigger the "menu_magic_page" function.
   */

  $items['magic'] = array(
    'title' => 'Menu Magic!',
    'page callback' => 'menu_magic_page',
    'type' => MENU_CALLBACK,
  );

/**
 * Page callback for 'magic'. This is the function that will get called
 * everytime a user visits http://example.com/magic.
 */
function menu_magic_page() {
  global $user;
  return t('Hello, @username!', array('@username' => $user->name));
}


How to use arguments, defined in a custom event, for an action

In your action you might have something like

function mymodule_rules_action_info() {
  return array(
    'my_action' => array(
      'label' => t('Label'),
      'module' => t('My module'),
      'arguments' => array(
        'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
        'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
      ),
      'base' => 'mymodule_my_action',
    ),
  );
}

The 'base' property indicates the callback for the action. You can also use the key of your action as the callback if you choose not to set a 'base'. In this case it would be function my_action(). The arguments defined in the action will automatically be passed to that function. Now, whether the action is available is dependent upon which arguments your event makes available and which arguments your action requires. So, if I had an event that passes a 'type' => 'user' and 'type' => 'node' then only actions that have arguments 'user' and 'node' would be available. This is how Rules 1 works. Alternatively, by using a simple 'text' data type the actions will always be available because the data type is not unique. You can specify your own data types by implementing hook_rules_data_type_info().

Anyways, I got off track. So, with your base being mymodule_my_action:

function mymodule_my_action($number, $message) {
  // Do stuff here.
  return $number;
}

Another addition you can make if necessary is adding a settings form to your action.

function mymodule_my_action_form($settings, &$form) {
  $form['settings']['my_options'] = array(
    '#type' => 'select',
    '#title' => t('Select an option'),
    '#options' => array(
      'this' => t('this'),
      'that' => t('that'),
      'also' => t('also'),
    ),
    '#default_value' => $settings['my_options'],
    '#required' => TRUE,
  );
}

In this case, you would just add the settings array to your action callback as the last argument:

function mymodule_my_action($number, $message, $settings) {
  if ($settings['my_options'] == 'this') {
    // Do stuff.
  }
}

Hmm... I don't even know if I answered your question, but I tried to provide as much info as possible. If I completely missed it please give me some guidance. I maintain three Rules modules, so I've been around that module for a while and I'm glad to help.


You may find the ThemeKey module useful.  This module allows you to define arbitrary rules to determine when to show each theme.  You can make as simple or as complex a configuration as you want.

From the module page, the following features are supported:

  individually-styled channels
  a front-page / "splash" screen
  a date/time-selected Christmas theme
  mobile themes for different auto-detected mobile devices
  special themes for "limited" or "old" browsers
  content, user, or role -specific themes
  indicating your environment (production, staging, testing, sandbox, … )
  testing your redesign safely on a live server

See the documentation for more details.


How can I change the display settings of the referenced field, programatically?

One option is to alter the build array using entity_view.  You could then add conditional code there, to change image display settings.

/**
 * Implements hook_entity_view().
 *
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityType()->id() == 'paragraph' && $entity->bundle() == 'my_paragraph_type') {
    if (!empty($build['field_image'][0])) {
      // $build['field_image'] =
       // make changes to your image field here
    }
}


I suggest to join roles and role assignements tables togother in your query of RoleMigration class,
in that case you will have these fields as source fields : role_id, user_id, role_name

now in UserMigration you just need to apply the dependency of the role migration on "roles" field :

$this->addFieldMapping('roles', 'role_name')
            ->sourceMigration('Role')
            ->defaultValue(drupal_map_assoc(array(2))); // authenticated user default value

Don't forget also that the key field of migration mapping should be the user_id field :

$this->map = new MigrateSQLMap($this->machineName,
        array('user_id' => array(
                'type' => 'int',
                'not null' => TRUE,
                'description' => 'User ID.'
                )
            ),
        MigrateDestinationUser::getKeySchema()
    );

Didn't test it but should work like that!


I cannot add a new CSS class to the classes_array array

You simply do as Drupal does in its html.tpl.php file. Instead of using <body<?php print $body_attributes; ?>>, you use the following code.

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

$attributes is set from template_preprocess() with the following code.

  // Flatten out attributes, title_attributes, and content_attributes.
  // Because this function can be called very often, and often with empty
  // attributes, optimize performance by only calling drupal_attributes() if
  // necessary.
  $variables['attributes'] = $variables['attributes_array'] ? drupal_attributes($variables['attributes_array']) : '';
  $variables['title_attributes'] = $variables['title_attributes_array'] ? drupal_attributes($variables['title_attributes_array']) : '';
  $variables['content_attributes'] = $variables['content_attributes_array'] ? drupal_attributes($variables['content_attributes_array']) : '';

Also, you don't need the following line in bootstrap_gstt_preprocess_html().

$variables['classes'] = implode(' ', $variables['classes_array']);

template_process(), which is executed after bootstrap_gstt_preprocess_html(), contains the following code.

  // Flatten out classes.
  $variables['classes'] = implode(' ', $variables['classes_array']);

So, what your code is doing is already done from Drupal.

As side note, this what I would change in the code you shown.

$results = _bootstrap_gstt_taxonomy_node_get_terms($node);
$taxonomy_vocab = $results->name;
if (is_array($results)) {
  // Omissis.
}

Since _bootstrap_gstt_taxonomy_node_get_terms() is surely returning an array, you cannot access an object property as you do with $results->name.

$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');

If you are going to use the value returned from $query->join(), then you should use the following code.

$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = %alias.tid');
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

Also, since you are using $key (whose default value is 'tid') in the rest of the code, you should probably use the following code.

$t_alias = $query->join('taxonomy_term_data', 't', "r.$key = %alias.$key");
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

To understand what %alias means, see SelectQuery::join().

  $condition: The condition on which to join this table. If the join requires values, this clause should use a named placeholder and the value or values to insert should be passed in the 4th parameter. For the first table joined on a query, this value is ignored as the first table is taken as the base table. The token %alias can be used in this string to be replaced with the actual alias. This is useful when $alias is modified by the database system, for example, when joining the same table more than once.

If you are sure the same table is not joined more than once, you can simply ignore the value returned from $query->join() and use the following code.

$query->join('taxonomy_term_data', 't', "r.$key = t.$key");
$query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');


ajax_deliver returns json instead of content

You are almost there!

You are opening a serious security hole in your site, allowing anyone who has access content permission to access all nodes bypassing node access system.

Assuming you need to use ctools's Ajax framework extension, you obviously need to have ctools module enabled.

1. Change your menu loader to this:

$items['customNews/%ctools_js/%node']

This will make Drupal pass the second %ctools_js argument to ctools_js_load function that returns TRUE if nojs was changed to ajax.

2. The link.

Ctools won't change all "nojs" occurrences in the page. You need to create a special link using ctools_ajax_text_button function, or by adding classes to the link.

<?php
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  print ctools_ajax_text_button(t('Read more'), 'customNews/nojs/1'); //1 is the node ID. Replace accordingly. You need to use "nojs" here.
?>

3. Almost there!

Your code should work now. However, make sure you have proper node access checks before showing anything. SA-CORE-2-14-005 was touch enough.

if ($js == 'nojs') {
        drupal_goto('node/' . $node->nid);
    }

Can be changed to:

if (!$js) {
  drupal_goto('node/' . $node->nid);
}

The importance of this "special link" is that ctools's JS registers all anchor tags in Drupal.ajax that follows the class name convention. For my own use, I have a small function that returns the proper link so I don't have to include ctools's ajax.inc file.


After several hours, and help from the user spovlot in #drupal-support, we have a working answer for D7:

(edit: this has been tidied up some more!)

Pattern for all forum topic paths:

forum/[node:taxonomy-forums:parents:join-path]/[node:taxonomy-forums:name]/[node:title]

combined with

Pattern for forum and forum containers:

forum/[term:parents:join-path]/[term:name]

This gives a result of:

/forum/container/sub-forum/title-of-a-post

Note that:

/forum is the name of the forum (i.e. no a forum, but a description)
Any number of containers and sub-forums will work. (forum/container/sub-a/sub-b/title-of-a-post)

Hope it helps!


What tpl should I choose for this faq page?

The most simple solution would be to copy all of the 9 templates from the module directory to your theme, and then add a simple output and see where and how they are used. You can later delete the ones you don't need to modify.

The templates used seems to be based on the configuration settings though, so keep that in mind.


How to create Nested Accordion in Drupal 7?

Drupal View Accordion triggers the accordion for the innermost Group Header. Though Nested Grouping can be done but the accordion effect will only applied to inner group.

For this we have to apply our own JS. I have created a module in which current accordion plugin has been extended, which itself was extending view plugin style. And additional setting has been added to it for nested accordion.

I have committed a [D7] Views Nested Accordion module on sandbox for this.


Configure view to display a list of nodes with identical term id/name

You can add a filter to display nodes that has term with name/id = X. This is done through the interface by clicking add filter and selecting either term name or term id.


Default Breadcrumb is not working in bootstrap drupal 8?

The twig code doesn't work and you don't need it for the breadcrumb block to be available in the block layout. It's the other way, first you assign the breadcrumb block in for example the Highlighted region. Then you print the region with the breadcrumbs in page.html.twig:

{{ page.highlighted }}

In D8 it's not possible to access the breadcrumbs in the page template directly. You have to use a Drupal block. See https://www.drupal.org/node/2410773.

BTW Twig Blocks are not connected to Drupal blocks. They are used to extend templates:

  Blocks are used for inheritance and act as placeholders and
  replacements at the same time. They are documented in detail in the
  documentation for the extends tag.


Omega Subthemes, Modernizr, and Javascript placement

I have now done a few Omega based sites, and have some answers about these.

I have not run into any problems with moving the print $scripts to righe before the  closing </body> in html.tpl.php.  That said, this question on SO has a good discussion on wht this may be outdates advice.

I have also had good results replacing the HTML5 shiv in html.tpl.php with

<?php if ($modernizr): ?>
<script src="<?php print $modernizr; ?>"></script>
<?php else: ?>
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<?php endif; ?>

and using this in a template_process_html

if (theme_get_setting('mytheme_use_modernizr')) {
  $vars["modernizr"] = "/" . path_to_theme() . "/js/modernizr-2.0.6-min.js";
}

and then wiring up a custom theme variable in theme-settings.php

$form['mytheme'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('mytheme settings'),
);

$form['mytheme']['mytheme_use_modernizr'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Modernizer instead of HTML5 Shiv?'),
    '#default_value' => theme_get_setting('mytheme_use_modernizr'),
);


How to get the Published or Archived revision of a node

You can do this with a direct database query in your function, then load the specific revision.

$connection = \Drupal::database();
$query = $connection->query("SELECT vid FROM {node_field_data} WHERE nid = :nid",
    [':nid' => $node_nid,]);
$node_revision_id = $query->fetchField();

$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

Untested code, but this should put you on the right track.  Might also be worth confirming in your SQL query that "WHERE status = 1" to confirm that the node is still published.


Why dont you just override views-view-table.tpl.php by copying/pasting this to your template folder in your theme, then use $row_count for your classes.

<tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .' row-' . $row_count . '"';  } ?>>


This is not really a drupal question. You are seen the website through a frame
The real url is http://31.186.174.215/~leenkneg/ where the urls work as expected.

To answer your question after the info you gave.
One solution is to add an A record to the DNS of the domain. So every http traffic will land to your site but without the users notice and the can have the emails where they want.

So you will have the hosting and the can keep the emails.


How to put a comma between city and state in addressfield display?

This is actually pretty simple, once you know the hooks and have some example code. You're correct that you need to use the ctools plugin api. So in a custom module, add:

/**
 * Implements hook_ctools_plugin_directory().
 */
function mymodule_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/addressfield/' . $plugin;
  }
}

Then you drop plugin files in the directory you specified, within your custom module. In this case, plugins/addressfield. A file that will do what you're looking for would contain something like this:

<?php
/**
 * @file
 * city-comma.inc
 *
 * Adding comma after city.
 */

/**
 * Plugin definition for address field format.
 */
$plugin = array(
  'title' => t('Comma after city.'),
  'format callback' => 'mymodule_city_comma',
  'type' => 'address',
  'weight' => -80,
);

/**
 * Callback for plugin definition.
 */
function mymodule_city_comma(&$format, $address, $context = array()) {
  if (in_array($address['country'], array('US', 'CA'))) {
    if ($context['mode'] == 'render') {
      // Add comma after city.
      $format['locality_block']['locality']['#suffix'] = ',';
    }
  }
}

This file would actually go in a directory called 'formats' inside the directory defined in the hook. So: mymodule/plugins/formats/city-comma.inc.


How to hide all tabs (local tasks) except the user account tabs?

I wouldn't recommend not doing this by code, this can be achieved using built-in configuration settings, by using a second block with proper rules. Try this:

Go to Structure > Block layout
Select your theme
Place a second tabs block where-ever you want it
Limit the visibility on the block fitting your requirements

Most likely limit Pages to something like user/*
and by Roles, e.g. Authenticated user
(remember that administrators are authenticated users too, so you might need more specific roles to to prevent admins seeing tabs block twice; or add the "hide"-option on user-pages for the first, original tabs block )


Is it safe to delete the /module folder?

Yes, you should be able to delete the versions of the modules directly under /modules, and clear cache; in theory that should be enough to get the system to re-register the same modules from their new locations.

Take a backup of the files and database first, and if you want to play it safe, delete one module folder at a time, running drush cr and checking that the version Drupal now sees is correct after each deletion.

It's probably wise to run drush updb after this, in case any of module versions have incremented and there are updates.


ended up using subqueues, was not quite what I wanted.


Display specific nodes on specific pages

Create a block display mode for that view (the view that display ads) and place that block on basic page node types.

In the view you should add a Contextual filter (under Advanced settings) and validate it as the node ID from URL. Then add a filter that selects only ads for that node ID.


Error with Node_load() - : Base table or view not found

Maybe you should define on the test class what profile are you using. Somehow simpletest does not detect it automatically. Without knowing which profile to install, it will not know what is a laptop node, because this content type has not been created. You can try to define on the test class the attribute:

protected $profile = 'labdoo';

See as an example: https://github.com/dashohoxha/oauth2_client/tree/7.x-1.x/tests

In particular, the shell script can be interesting: https://github.com/dashohoxha/oauth2_client/blob/7.x-1.x/tests/run_tests.sh


Creating Views rows with specific classes?

You need to modify views-view-unformatted.tpl.php.

In your views, in the third column click on theme and choose the how specific should be you file, for the full view or for that display. Copy into your theme folder and rename it.

You can find more info here http://api.drupal.org/api/views/theme%21theme.inc/group/views_templates/7

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

<?php print $title; ?>

    <?php endif; ?>
     <?php
     $i = 1;
     $num_rows = count($rows);
     $num_rows = $num_rows -2;
     ?>
    <?php foreach ($rows as $id => $row): ?>
    <?php
     if ($i == $num_rows){
       $classes_array['YourCLass'];
     }
     ?>
     <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
      <?php print $row; ?>
      <?php $i++;?>

    <?php endforeach; ?>

Flush cache


Why don't I get any CSS after deploying my Drupal site?

In addition to @acrosman:

Make sure that your files and temporary files directories are writable by the server.


Nope, Drupal Services just return the node object by default. Looking at the end points in node_resource.inc, it would seem it would not be hard to build thou.


Menu block is not being displayed on the front page

This sounds like a bug that I ran into myself and has been brought up here: http://drupal.org/node/1468420 (submenus of a parent menu item that links to the front page (<front>) do not show when viewing the site's front page). At the time of writing the bug has not been fixed, but there are 2 workarounds that might help you out:

Set the menu link with the <front> path to 'show as expanded'.
Do not use <front> as the menu link path, but instead use your actual front page path (same as in 'admin/config/system/site-information').


Howto print out the pagination for EntityFieldQueries?

The ->initializePager() part is wrong; why would you do that?
Kill that line, and call execute() as usual.
Just calling theme('pager') should be enough; I am not sure why it fails. (Maybe because of the call to initializePager().)


There is a function called menu_save that looks like it will help you out (I assume drupal 7)


How to extend ArgumentPluginBase and have it recognized by Views?

register it with hook_views_data_alter() in mymodule.views.inc

Something like this:

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {

  $data['node_field_data']['my_custom_taxonomy_validation_argument'] = [
    'help' => t('Hello world'),
    'real field' => 'title',
    'argument' => [
      'title' => t('Hello world'),
      'id' => 'my_custom_taxonomy_validation_argument',
      'accept depth modifier' => TRUE,
    ],
    'filter' => [
      'title' => t('title'),
      'id' => 'my_custom_taxonomy_validation_argument',
    ],
  ];

}


How to get a referencedEntity field value in current node language

The code for your problem (You need to use getTranslation to get a translation and hasTranslation to check is is it actually has a translation or not):

$lang_code = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
$node = \Drupal::routeMatch()->getParameter('node');

// Paragraphs/referencedEntities
$paras = $node->get('field_paragraphes')->referencedEntities();
foreach ($paras as $para) {
  // Remember to check if translation exists
  if ($para->hasTranslation($lang_code)) {
    $para = $para->getTranslation($lang_code);
  }
   $goodValue = $para->get('field_test_in_para')->getValue();
}

Eventhough this code will work and fix your problem, you might consider if you are doing things right. Most of the time, when doing things the proper way, you wont need to handle translations. A lot of modules/systems does this automatically when rendering stuff or using modules like views. Most of the time, when you need to handle translations yourself, there would be a simpler way to do this.


How to export a Field's Allowed Value List in a feature?

Turns out this is a bug(?) in Drupal 7.

The Dropdown list field's values are not saved in Features on a per-instance basis.

This can be fixed by using hook_field_widget_form_alter in the Feature's .module file, eg:

/**
 * Implements hook_field_widget_form_alter().
 */
function my_colors_field_widget_form_alter(&$element, &$form_state, $context) {

  if ($form_state['build_info']['form_id'] == 'my_colors_node_form' &&
    $context['field']['field_name'] == 'field_dropdown_text_single' &&
    $element['#entity_type'] == 'node') {
    $form_field_wrapper = entity_metadata_wrapper('node', $element['#entity']);
    $default_field = $form_field_wrapper->field_dropdown_text_single->value();
    $element['#default_value'] = !empty($default_field) ? $default_field : '';
    $element['#options'] = [
    'Red' => 'Red',
    'Blue' => 'Blue',
    'Green' => 'Green',
    ];
  }

}

...drupal is so great...


You can create a Custom block type (admin/structure/block/block-content/types/add) and then add fields to it (admin/structure/block/block-content/manage/YOUR_BLOCK_MACHINE_NAME/fields).

You will see that you have the Manage form display and Manage display tabs too like the content types, you don't need to create a content type. In Drupal 8 you can use blocks in more than one region.

Check The Block System is Finally Useful in Drupal 8 and see the video.


How can I get multiple values in a RESTful endpoint from a field who points to other resource?

I haven't used this module in a while, so I'm not sure if there's a major difference in the approach between 1.x and 2.x.

I would just implement a custom function for getting the single resource, so that you have full control over what is ret

/*
* Overrides \RestfulEntityBase::controllersInfo().
* Allows us to specify custom functions for different HTTP actions.
*/
public static function controllersInfo() {
  return array(
   '^.*$' => array(
     \RestfulInterface::GET => 'customGetSingleExample',
   ),
  );
}

/**
* Return custom data for getting single resource result
*/
public function customGetSingleExample() {

  //grab request values
  $request = $this->getRequest();
  static::cleanRequest($request);

  //do stuff with request (EntityFieldQuery etc)

  .....

  return $result;
}

This is within a custom resource class, which extends RestfulEntityBaseNode

class RestfulCustomResource extends RestfulEntityBaseNode {


How to add a Login / Logout link in Main navigation menu?

We don't need to depend on Bootstrap theme or our programming skills to move system "Log out" link on any other menu. Drupal allows us to make it easily.

Additionally we can just create two custom "Log in me here please" and "Get me out of there" links with /user/login and /user/logout paths relatively. This is better because unlike the system "Log out" link it gives us to create as many log in/out links as we want with custom attributes. As the user logged in they'll see only "Log out" link and vice versa. The only caveat is that you will see probably both links together because you are logged in at the time of testing the links. And this is normal as you have "Link to any page" permission as administrator. Disable this permission and try again.


Create taxonomy 'add terms' form into block

Every block must have unique delta, so in hook_block_info first $blocks change 'Vocab Two Block' to 'vocab_block_first', second $blocks 'Vocab Two Block' change to 'vocab_block_second', then in 'switch' change first 'case Vocab Two Block' to 'case vocab_block_first' and second 'case Vocab Two Block' to 'case vocab_block_second'. Then show these two blocks on the same place.


Why does this rule not appear in the UI and how can I clone it?

I don't think it's possible to delete this Rule. Even if you delete it from the database directly, it is recreated the first time Commerce gets called (because it's in the defaults .inc file).
Are you sure it's not just disabled?
Your module directory structure is non-standard; Commerce should be in sites/all/modules/contrib.

Here's a copy of the Rule in case you need to import it again:

{ "commerce_checkout_order_email" : {
"LABEL" : "Send an order notification e-mail",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [  ] },
"DO" : [
  { "mail" : {
      "to" : [ "commerce-order:mail" ],
      "subject" : "Order [commerce-order:order-number] at [site:name]",
      "message" : "Thanks for your order [commerce-order:order-number] at [site:name].\u000A\u000AIf this is your first order with us, you will receive a separate e-mail with login instructions. You can view your order history with us at any time by logging into our website at:\u000A\u000A[site:login-url]\u000A\u000AYou can find the status of your current order at:\u000A\u000A[commerce-order:customer-url]\u000A\u000APlease contact us if you have any questions about your order.",
      "from" : ""
        }
      }
    ]
  }
}


How to check if the problem is of clean url when migrating the database from one server to another?

It is advised to turn off the CLEAN URLs before migrating the database from one server to server.

Reason behind you were not able to see errors on white screen of death may be error reporting being turned off, if that is the case than you may try adding the following lines in setting.php to turn on error reporting:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

  Also check the entry's of "watchdog" table if you are getting white screen of death upon migration.


How can I add arbitrary placeholder text to form fields?

It seems that this functionality is now in the Drupal core – placeholders can be added from the widget settings on the content type's form display page.


How do I handle exceptions in a service class?

When using unqualified class names like Exception and Error, and in the absence of a use statement to qualify the names, PHP assumes those classes are in the "current" namespace. The namespace of your service class appears to be Drupal\my_custom_module\Api, so that is where PHP will look for Exception and Error. When PHP does not find those classes, you will get an error.
To avoid this error, add a backslash before the class name for classes that are in the global namespace. So use \Exception and \Error instead. You do not need a use statement for either of these.
The error Fatal error: Trait 'Drupal\my_custom_module\Api\Exception' not found in /app/docroot/modules/custom/my_custom_module/src/Api/Clientname.php on line 66. is because you probably said use Exception; within the body of your class. The error Error: Class 'Drupal\my_custom_module\Api\Error' not found is because you referred to Error and not \Error.
Note that all these problems are just basic PHP issues - they are not caused by Drupal and do not involve Drupal at all. Specifically, it does not matter that you're in a service class, or that you're doing exception handling, etc.


The AMP module requires the PHP AMP library

This module requires the use of Composer to install its libraries. You can learn more about Drupal and Composer on drupal.org's documentation hand book Installing modules' Composer dependencies in Drupal 8. The AMP module project page also has a brief description of how to install on Drupal 8.0.5.


Programmatically build module permission list

You can list all available permissions with PermissionHandler:

$permissions = \Drupal::service('user.permissions')->getPermissions();

You'll find the module name in the provider property of the permissions:

$permissions_by_provider = [];
foreach ($permissions as $key => $permission) {
  $permissions_by_provider[$permission['provider']][] = $key;
}


Query that converts a timestamp to a date

$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(submitted), '%d.%m.%Y %H:%i')", 'submitted_formatted');

http://www.w3schools.com/sql/func_date_format.asp

then in your loop, reference it as $row['submitted_formatted'];


If you like you can add to the hook_field_widget_form_alter and then add a validation callback:

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

Then create a my_validate_function($form, &$form_state) which contains a check on the values and calls a form_set_error($name, $message) if a value is wrong or missing.

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $context['form']['#validate'][] = 'my_validate_function';
  }
}

/**
 * Require description to be set.
 */
function my_validate_function($form, &$form_state) {
  if ($form_state['values']['description'] == '') {
    form_set_error('description', 'Description must not be empty.');
  }
}

This may need to be changed above:

$form_state['values']['description']


How to configure the YouTube Field and Mediafront modules?

Edit your textfield (admin/structure/types/manage/media/fields/[YOUR_TEXT_FIELD]).  Under the Mediafront settings Field type, set field type to 'Media' and Media Type to 'Media Content'.

You must create a mediafront preset (admin/structure/mediafront) before you can associate the textfield to mediafront player.

After your preset is setup, go to manage field of your content type (admin/structure/types/manage/[YOUR_CONTENT_TYPE]/display).  For the testfield that stores your media url, set the Format to Mediafrontplayer and set set the player settings to the Mediafront preset that you created.


Drupal 6: Move the 'Add new comment' link to the bottom

Since Drupal is such a highly configurable system, there are a few ways to accomplish what you want. Here's just one example.

The first part of the equation is to remove the link from the node's links array. This approach removes it during the theme call.

<?php
/**
 * Override theme_links() so we can remove or alter any links we don't need.
 */
function MYTHEME_links($links, $attributes = array('class' => 'links')) {
  unset($links['comment_add']);

  // Rather than include all the original theme_links() code in this function,
  // we can just call it directly here.
  return theme_links($links, $attributes);
}
?>

After that, you have a few options of where to readd the link. The primary function that builds the display for comments and comment controls is comment_render() in comment.module. It builds the comments display using a few different theme calls, so it's up to you where you want to add the link back in. Probably the easiest approach is to copy the file /modules/comment/comment-wrapper.tpl.php into your theme folder and add the code for the link there. Alternatively, you could either put it above or below the comment controls form (by overriding theme_comment_controls), or by overriding any of the other comment theme functions. Whichever approach you take to adding the link back in, you can get the code for the link from the comment_link() function -- open up comment.module and search for "Add new comment" to find the link code.

Good luck!


Note that Features module supports exporting languages.

Answering the question:

// Example language: fr.
$language = (object)array(
  'language' => 'fr',
  'name' => 'French',
  'native' => 'Français',
  'direction' => 0,
  'enabled' => 1,
  'plurals' => 0,
  'formula' => '',
  'domain' => '',
  'prefix' => 'fr',
  'weight' => 0,
);

locale_add_language($language->language,
  $language->name,
  $language->native,
  $language->direction,
  $language->domain,
  $language->prefix,
  $language->enabled);

// Additional params not implemented in locale_add_language().
db_update('languages')
  ->fields(array(
    'plurals' => $language->plurals,
    'formula' => $language->formula,
  ))
  ->condition('language', $language->language)
  ->execute();


How to stop nodes being automatically added to a simple queue in Nodequeue?

In case someone else runs into this, I finally figured it out.

In the settings (admin/structure/nodequeue/[NODEQUEUE_ID]/edit), there's the list of "Type" checkboxes. When I originally set this up, I assumed that I had to check those content types that I wanted allowed into a queue. Turns out, this actually seems to auto-add new nodes of those content types. I unchecked all of the checkboxes, and now things seem to work as they should.


Static vs. Dynamic Queries in Drupal 7 and the Right Syntax to Use

If you're creating a query that will need to be modified by a 3rd party or if your creating drupal.org project code then use things like db_select().

For all other use cases I prefer db_query() as the mental overhead is a lot lower.


Trying to rewrite url for a custom module with an extra custom variable using PathAuto

You have a 2-step problem.

1) User friendly URLs

Pathauto is the wrong solution. Setting URLs in custom modules is the job of hook_menu.

function mymodule_menu() {
  $items['product'] = array(
    'page callback' => 'mymodule_product_view',
  );
  return $items;
}

function mymodule_product_view($id = 0) {
  //Do database call here for product id = $id
}

Using this simple example, you can visit the page product/50. Drupal will then call the mymodule_product_view function with the second parameter (in this case 50) as the arguement.

2) Creating a block to show product information

What you need to get is the product name or id. If that is already in the url you can use arg(2) assuming your URL is "examples.com/product/50". Here is the api page for Drupals arg function.

Ideally you would then do database calls etc. with this arguement within a custom modules block. You can find out how to create a block in custom code here


Is it possible to create a menu item and leverage path aliases?

You'd have to extend the pathauto system to handle your specific pattern, like it does for node/x/feed items.


Is there an easy way to move user data between 2 sites?

You could possibly use views to output the data you want into a csv file (with views data export module) and then import the data into the destination site using Feeds module. This technique has worked well for me on a number of occasions.

Additionally, you could try the Features module but this is quite complicated and may be difficult to get your head around initially.


Loading cck fields from nodes of a content type

Try changing print $nodes to print_r($nodes) and also move it to the outside of your while loop.

Your code should look like this:

$nodes = array();
$result = db_query("SELECT nid FROM {node} WHERE type = 'insert_item'");
while ($row = db_fetch_object($result)) {
  $nodes[] = node_load($row->nid);
}
print_r($nodes);
//If you use Devel, uncomment this next line and comment out print_r above
//dpm($nodes);

This will give you an easy to read value.

Another option is to use the Devel module, and instead of using print_r you can use dpm() which uses Krumo to pretty print the contents of your array.  There are some basic instructions for that dpm() here and here.

Information on print_r here.

  If given an array, values will be presented in a format that shows
  keys and elements. Similar notation is used for objects.


Creating a content type with dynamic fields

There is Conditional fields module, but stable version is available only for D6.


Module to convert a decimal amount of US Dollars to an equivalent amount of BitCoin

It seems you're looking for the UC Bitcoin module

This module provides an alternative 'payment gateway' that enables your clients to pay in the equivalent amount in BTC (Bitcoin currency)
It does this by doing a current market exchange rate lookup of your stores default currency and then allowing an option to let people pay in the equivalent BTC amount.


Converting hard-coded menus to using the Menu module

You only need to create a new theme if the site in question is in production and you are not able to set up a development version of the site make your changes to the existing theme. In that case, you will want to create a copy of your theme with a different theme name and make sure to update the name of your MYTHEME.info file as well as any function names in your theme's template.php file.

Whether or not you do the above, the rest of the process should be the same either way.

Create a backup of the template file where the menu is hardcoded.
Create a block region where the menu currently is. There are two parts to this step: First you will need to add the following line to the MYTHEME.info file to let it know that the region exists:

regions[menu] = Menu

You'll want to make sure that there is not already a region with the same machine name. If there is, you may want to change it to something like:

regions[menu_top] = Top Menu

Next, you'll need to replace the hard-coded HTML for the menu with the code to display the region, something like:

<?php if ($menu): ?>
<?php print $menu ?>
<?php endif; ?>

Clear caches. This forces the theme registry to be rebuilt and your new region will be show up.
Add the menu block to the newly created region. Visit /admin/structure/blocks and find the block that is automatically created for the menu that you have recreated using Drupal's menu system and drag it into the "Menu" region that you just created.
Superfish. This is one of the better drop-down menu solutions, IMO. You'll want to follow the module instructions for getting it set up. This module creates additional blocks that you can assign your menu to. This will alter the previous step because you will add the superfish block and then assign the menu in the superfish block settings.
Profit!


How can I run javascript code after an item added or removed from an unlimited value field?

Create a Drupal behavior. It will be attached to each field when the page loads as well as to new fields added after any ajax calls (adding or removing).

Here is a basic example that will log a click on the text boxes in the field field_fieldname

(function ($) {
  // Logclick is an arbitrary unique behavior name
  Drupal.behaviors.logclick = {
    // Context here allows your function to run on ajax calls
    attach: function(context, settings) {
      // Your custom jQuery goes here
      $(".field-name-field-fieldname input.form-text",context).once('logclick',function() {
        $(this).click(function() {
          console.log('text box clicked');
          return false;
        });
      });
    }
  };
})(jQuery);

logclick can be changed to whatever you want to call your behavior.


How to attach a module to a drupal article?

For example, my module named custom2, so:

<?php

function custom2_random_text(){
    return 'random-text';
}

function custom2_node_presave($node){
    //check for our node type if needed
    if($node->type == 'article')
        //assign value
        $node->body['und'][0]['value'] = custom2_random_text();
}

hook only works for Article content type
custom2_random_text - returns random text
custom2_node_presave - implementation of hook_node_presave

  function hook_node_presave

  7 node.api.php    hook_node_presave($node)

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database.

Note how hooks in Drupal works. You are implementing hook_node_presave in your_module.module via replacing hook word by your module's name.

If you in doubt about structure of some entity on your site I should recommend you to use Devel module.

For first step you can implement hook_node_view and in code of your implementation use dpm($node) - it is Devel module function that will display node structure when node is displaying.

For my example:

function custom2_node_view($node, $view_mode, $langcode){
  dpm($node);
}


How to grant Userpoints after adding a comment once?

I solved my problem with the Flags module: I created the flags called 'Commented on this node' & 'First reaction'* and rule called 'Commented on a node'. These are my rule's settings:

EVENTS: After saving a new comment

CONDITIONS:

Content is of type Parameter: Content: [comment:node], Content types:
Article
NOT Node is flagged Parameter: Flag: Commented on this node, node:
[comment:node], User on whose behalf to check: [comment:author]

ACTIONS:

Grant points to a user Parameter: User: [comment:author],
Points: 2, Points category: Reaction, Entity: [comment:node],
Description: New reaction, Operation: Add,
Display: false, Moderate: Automatically approved
Flag a Node Parameter: Flag: Commented on a node, Node:
[comment:node], User on whose behalf to flag: [comment:author], Skip
permission check: false
Flag a Comment: Parameter: Flag: First reaction, Comment: [comment],
User on whose behalf to flag: [comment:author], Skip permission
check: false

So, every time a user adds a comment to a certain node for the first time, the node is flagged as 'Commented on a node', the reaction is flagged as 'First reaction' and the user who added the comment is rewarded 2 points.

**I use the 'First comment' flag in a related question.*


Displaying non-empty fields in full node view

If, when you edit the node, it displays correctly, this makes me think that the import may have added whitespace into the fields? Is that possible? I would recommend using Migrate for importing data. Even from files.

Either way, Views will not work for a node view ie, node/nid. You could use Views to create a landing/index page and hide empty fields pretty easily.

Rather than change the display, I would be more concerned with the quality of data in the fields (ie, whitespace) and would look at using something like VBO for cleaning the data. Are there many nodes? You could even just write a simple SQL update statement, something like;

UPDATE {field_data_field_blah} SET $value_col = NULL WHERE $value_col = '';

Note, pseudo query. :)


Panels "Page not found" when using required wildcard argument

The problem was that my taxonomy terms had dashes, e.g. "Early skills for non-training grade doctors".  When used in conjunction with views contextual filters and the option to "Transform spaces to dashes in URL", it doesn't match properly, so no value for the context is provided.  This is related to the following views bug - https://www.drupal.org/node/672606 (no solution as yet for panels but there is a solution if you're just using a view page in comment #16).  My solution was to remove all dashes from my term names.  Not ideal but fixes the problem.

Here is how I set things up to pull a taxonomy term name contextual filter into a View Pane, in case it helps someone.  If anyone knows a better way to go about this then please let me know and I will update this answer:

View Setup - Contextual Filter

View Setup - Argument Input

This part is counter intuitive, you have to choose "No argument input".  Providing a context from panels will prevent the default filter value from being used.  Thanks to the following comment for helping me figure this out: Views contextual filters taxonomy name

Panel Setup

N.b you have to use a panel page here (structure > pages), so that you can make use of the wildcard feature.  I tried this by panelizing a node initially but couldn't get it to work.

Basic settings:

Argument settings:


$result = $query->fetchAll();

This will store the records in $result as an array. You then need to store it in the computed field, which is something like this:

$entity_field[0]['value'] = $result;

References:

https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7

https://drupal.org/node/126522


How can I set up RNG Conflict with a multi day event

This is my interpretation of your multi day seminars:

I think for your first scenario where there is no conflicting sessions, there is no need to enable RNG Conflict.

For the second scenario where you have multiple (3-5) sessions potentially running at the same time. You should have some field on the event nodes that uniquely identify each. You could do this by:

Adding a integer field representing the timeslot number (timeslot 1, 2, 3 etc). Or,
Add a date field on each event with the start datetime for each session. Then set RNG Conflict to use one of these options.

You may also want to add a field representing the overarching seminar. Resulting in something along the lines of:

Your site only needs a single event type (a node type, etc), and a single registration type no matter how many seminars you have. If you are customising your registration form then you may want to add more registration types, but this would be unusual.


How can I display a custom form in a popup?

You can do it with the Lightbox module, for example using the following.

Don't forget to add rel='lightframe'. See this page at the bottom, and click on "Mortage calculator."

The other option is the Popup Filter module which allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and PHP-generated content. Even you can mention the block to appear in popup window. And it has the option to popup the login form, register form etc.

Also look at the Popups API (Ajax Dialogs) module.

  API for building modal ajax dialogs. Its focus is on putting forms inside of ajax popup dialogs.
  Current example can present pages as popups (of the lightbox type). This is amazingly useful for things like confirmation pages. And the best part is it can be applied retroactively to a page without needing to modify the generating module, and (of course) it degrades gracefully.


How to list all nodes attached to a vocabulary?

Are you sure that you are using the tags field for this?

You're filtering on the term name, but you want to filter on the term vid instead:

 $query = \Drupal::entityQuery('node')
  ->condition('type', 'health_posts')
  ->condition('status', 1)
  ->condition('field_tags.entity.vid', 'healthcare_terms');
$ids = $query->execute();

If you have a standalone field that only allows terms from your healthcare_terms vocabulary, which is usually the better approach, then you can just look for ->exists('field_something').


Value modified with form_alter revert after check_cache

Submitted form values are stored in $form_state['values'], and can be modified in a custom validation function.

So in your custom module, implement hook_form_alter() and add a validation function:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'id_of_form_to_alter') {
    $form['#validate'][] = 'mymodule_custom_form_validate';
  }
}

/**
 * Custom form validation handler.
 */
function mymodule_custom_form_validate(&$form, &$form_state) {

  // Append value to submitted field.
  if (!empty($form_state['values']['myfield'])) {
    $form_state['values']['myfield'] .= ' append this string';
  }
}


Display a custom field of a content type in template with PHP?

$node->field_widget_position['en'][0]['value']

This is a bad solution.

The right solution is

render(field_view_field('node', $node, 'field_widget_position'));

or

render(field_view_field('node', $node, 'field_widget_position', array('label' => 'hidden')));

if you don't want to print a label.

See http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way for more info.


Is there a means to pass some php.ini settings to the drush command?

First, remember that php.ini for Command Line Interface is separate and has nothing to do with php.ini your webserver is using. To find where that file is, follow this question on SO as this is not really on-topic on Drupal Answers.

If you want to set some php.ini values in drushrc.php, you need to use ini_set() PHP function. Just remember that not all values are changeable like that, only the ones with PHP_INI_USER (or PHP_INI_ALL, of course) on this list.


Is it possible to add folders in config/install?

No, you can't put config in sub-folders, those are reserved for config collections (e.g. language overrides/translations).

The only option would be submodules as you already said, and it's up to you to decide if that's something that makes sense for you.

  For some background, I wrote a Python daemon that does server monitoring, and the module handles communication between the monitors and a central reporting server. Each content type corresponds to a plugin for the monitor, so someone could turn on only the plugins that they want.

Not sure I fully understand that and it's not exactly the same but our project https://www.drupal.org/project/monitoring might still be interesting? it uses plugins and a single config entity for a sensor, it is about monitoring things about a single drupal site and not other servers (We do then use sensu to collect the data and alerting).

And without having the full picture, using content types/content for something that doesn't really sound like content seems like a strange idea. In Drupal 8, it's pretty easy to create your own entity type with support for bundles, then you could make all the shared fields base fields and would probably get rid of 90% of your configuration.


Changing user picture HTML output on user profile

Hmmm, it sounds like you likely left the following line of code in user-profile-tpl.php:

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

Remove the above line of code.

The duplicate image will go away. And so will anything else in the profile.

You'll need to add back each individual item that you actually want via the same method you used to add just the pic, but for other fields in the profile:

<?php print $user_profile['user_picture']['#markup'];?>

If you are using the Panels module, this is trivial to do without touching any code or needing to dive into the $user_profile array.