Why does my Rules Condition about registration code seem to fail?

The typical Rules Condition doesn't seem to work here

Typically when using Rules, you can always give it a try to see if you can add, as a FIRST Rules Condition, a condition like "Entity has field". Or any other variation of a condition that informs the Rules module that you want to test the value of that field in a subsequent rules condition. Without that, Rules has no clue about which data to make available for subsequent processing ...

But, that doesn't seem to work/help for this particular case. For more details on that (if you really want to know why it doesn't work), you may want to look at the active Major task (not bug!) about Make better use of the Entity system ... (from Fago, who has quite a Rules "reputation" ...).

Rules debugging

If that doesn't help, I typically add a (temporary) Rules Action to just "Show a message on the site" (eg to show the value of a field ...). That might result in other unexpected results, to help you further debug it ...

But that doesn't seem to help either (grrrr), so time to move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Try to find (and read) the documentation

Too bad, this module doesn't seem to have a lot of documentation, and the README.txt is not of much help either.

If anything else fails, read the sources

OK, the advantage of open source ... lets go read the sources ...

Aha, I see the regcode.rules.inc (regcode in this filename is the machine name of the Registration code module), so let's see what this module's Rules integration has to offer:

A Rules Event with machine name "regcode_used" and label "User has used a registration code". Fine, that's also what's used in the rule in the question here (nothing new).
A Rules Condition with (a loooong) machine name "regcode_rules_condition_regcode_available" and label "User has used a registration code". Huh??? That's the same label as in the Rules Event, confusing!!! But that Rules Condition is what intrigues me. Time to fabricate a variation of the rule in the question.

Rule prototype (1st attempt)

Have a look at this variation of the Rule in the question (also in Rules export format, use the Rules UI to import it in your own site):

{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } },
      { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

The only difference in this rule (as compared to the original rule in the question) is the very first (confusing labeled) Rules Condition with machine name regcode_rules_condition_regcode_available.

That additional Rules Condition seems pretty close to the typical Rules Condition as I mentioned in the beginning of my answer (and Fago's issue I mentioned before makes a lot of sense to me now). And since the question states "... badly in need of the condition ...", I thought I'd leave the QA-testing of this variation of the rule in the question to the OPer of the question ...

Too bad, but that 2nd Rules Condition can never work, since the "[regcode]" token is not the token we're looking for (ie something that is a string, and which we want to check if it yes or no matches the registration code we're interested in to assign that special role). Read on for a new (2nd) attempt ...

Rule prototype (2nd attempt)

With some additional eyeballing and experiments, I noticed that within "Rules Actions" (not Rules Conditions!) there is the token [regcode:code], apart from all sorts of other regcode related tokens. So that opens another opportunity to get it to work anyway: let's just grab that [regcode:code] string and pass it on to a (new) Rules Component, in which we're going to do our thing (ie verify the registration code and grant the role if the code is what we want it to be. Below is the adapted rule from the previous attempt, and the (new) Rules Component:

a) Adapted Rule:

{ "rules_grant_a_role_after_using_a_registration_code" : {
    "LABEL" : "Grant a role after using a registration code",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value of token \u0022regcode:code\u0022 is: [regcode:code] and will be used as parm for the subsequent Rules Action, which invokes a Rule Component." } },
      { "component_rules_grant_role_for_specific_regcode" : { "actual_regcode" : "[regcode:code]" } }
    ]
  }
}

b) Rules Component:

{ "rules_grant_role_for_specific_regcode" : {
    "LABEL" : "Grant role for specific regcode",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "actual_regcode" : { "label" : "Actual Regcode", "type" : "text" } },
    "IF" : [ { "data_is" : { "data" : [ "actual-regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "10" : "10" } }
        }
      },
      { "drupal_message" : { "message" : "Since you used registration code \u0022[actual-regcode:value]\u0022, you have been granted a special role that corresponds to it." } }
    ]
  }
}

Note the 2 extra "Show a message" actions I added (to simplify QA testing).

Curious to hear if with this 2nd attempt it does work, or if you can MAKE it work from here on ...


drupal 7 error: table blocked_ips not found

The blocked_ips table is created unconditionally by the system module...it should be there in any standard D7 install.

The process goes like this:

drupal_boostrap() calls drupal_bootstrap_page_cache() when in the DRUPAL_BOOTSTRAP_PAGE_CACHE bootstrap phase.
drupal_bootstrap_page_cache() calls drupal_block_denied()
drupal_block_denied() calls drupal_is_denied()
drupal_is_denied() contains the following line of code:

$denied = (bool) db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();

So Drupal is expecting that table to exist. The only caveat is that if you have a variable called blocked_ips in the variable table the value from there will be used instead of the database being queried. Maybe you have that variable on the local version, and not on the live, and the issue is being masked by that fact?

If you didn't have any data in that table then it would be safe to copy the schema from an empty Drupal install and just create the table.

However, it might be worth checking the integrity of the rest of your data as it sounds like something's gone wrong either on your local copy or during the migration.


How to do arithmetic on a contextual filter

In Views for D7 (not sure about D6) you can add a field of type "Math expression" to do this sort of thing.  Enter the expression [!1]+1 (or maybe [%1]+1) in the Math expression field, and then later text fields can refer to this value (in their Rewrite sections) as [expression].


This is fairly easy and covered well in the Javascript API section of the drupal docs.

Effectively you want a Javascript file that creates a Drupal behavior (this is automatically fired when the document is ready). Inside the behavior, just call curvycurvy();.

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

So, for starters...

Drupal.behaviors.initCurvy = {
  attach: function (context, settings) {
    curvycurvy();
  }
};


In order to move information for popup from the page we have to use options: RMT callback path in a view.

It allows to make AJAX request to load content and so you do not need to put it on page with map. It's big performance improvement.


How to add a select menu to a form with the ability to insert new values?

As a first step, You can use Select or Other module to collect values from user if not available...

Project page says

  Provides a new Forms API element which is a select/radios/checkboxes
  element that has an 'other' option. When 'other' is selected a
  textfield appears for the user to provide a custom value.

As a second step, You need to read this values on hook_node_presave and insert it into select list available options using code like below..

// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);


You can setup Views to cache the query. This will probably be globally, (meaning the every one will see the same list for X time). It's not bulletproof but it's an easy solution. Alternatively you need to do some cache per user, which could be quite tricky or some custom code.
Update
By default Views allow you to clear the cache every 5 min (and other predefined values), if you add the cache actions module, you get rules based clearing of cache. With the use of rules you are able to setup the clear cache event to fire at a specific time of day (triggered by cron) and other special conditions that you are able to build with the power of rules.


Yes, the aptly named Menu Block module.

  ...provides configurable blocks of menu trees starting with any level of any menu.


It looks like your image table field_data_field_image is not having the field_image_alt column. Which is strange, since Drupal creates that by default.

Are you sure you ran update.php after migration? Do that first. If so, then try these steps.

I guess the best thing to do would be installing devel module and then with devel reinstall the image module. (Make backups as you might lose data!)

If that doesn't work you could add the column manually, and hope it was only this column that was off. See the following image for the fields you should have.


Site adds "he" to the URLs of all the Hebrew nodes automatically

Try deactivating the URL detection method under admin/config/regional/language/detection.


In a nutshell, there is no way that I know to do this with a token. You need to create a custom module that implements hook_form_alter() to set the default value of your minimum deposit field before the form is rendered. You'll set this default value using the value of the field in the pre-existing node (you'll need to load the node programmatically within the hook function and get the value of the field).

I could give you more details if you let me know what type of form you are using: are you creating a form programmatically with Form API? Using Entityform module to create the form? Using Webform module? Using the "Add to Cart" form provided by the module Drupal Commerce? Post a comment below and I'll edit this answer.


Will changing the value of $drupal_hash_salt in settings.php file break site

Disruption should be minimal -- the salt value was designed to be changeable. As it says, it will invalidate one-time login links when the salt is changed. But if you suspect that you've been hacked, this is precisely what you want to happen.


Managing custom aliases on translated content

I had to create a custom path based on a field. I was able to use hook_pathauto_pattern_alter(). If you need custom path per node then this should work. You will need to add a field. It can be a plain text field.
Pathauto conditions. Here is an example of the hook. code review for hook_pathauto_pattern_alter


Using Feeds Tamper to convert one list to another?

For like http://www.census.gov/2010census/xls/fips_codes_website.xls use Feeds or Migrate modules to fill-in a Content Type with the Fields in the Excel file. The are many tutorials online of importing data from a csv or excel sheet to Nodes.


Normally the collapsed and collapsible properties are used on fieldsets.
It looks like field_group is expecting for an undefined property on the vertical tabs object.

You could try adding them to your definition as such:

$verticalTab->collapsible = FALSE;
$verticalTab->collapsed = FALSE;

That should keep the field_group module happy.


How to add link to custom module configuration form in Drupal 8

Well it turned out to be a stupid mistake!

All of my filenames and syntax were correct, but my *.links.menu.yml accidentally was saved into the src/ directory of my module instead of at the root of it. I moved it where it should be and cleared the cache and it works fine.


Views: Ranking users by pageviews this month, last month

Take a look at the "archive" example view, which is provided by default (though disabled) as part of the views module.  It can be found under "Archive" on the admin/structure/views page.

This view groups the content created on the site by year and month; the contextual filter, filter criteria, and sort criteria are already configured and working correctly.  Study this example view and hopefully it will help you create what you want to do.


The fault turned out to be that a lot of modules had become de-selected. A good procedure would probably be to print off a module list with all the selected ones shown, this could then easily be checked by future webmasters.


I have managed to fix this issue by reverting the module to an older version.As I see in the release notes

  Issue #3037177 by itcrowd72, omrmankar, troybthompson: PHP 7.2 each() function is deprecated

The php version I am still using is 5.6. It looks like the new module version is not ok with 5.6, or at least with my setup.


How to translate entity in the views footer

With views php module you could add php in footer instead of entity. Sample untested code:

global $language;
if ( $language-> language='en'){
$n=node_load(22);
echo $n->title; //or any other field
} else ...

A more elegant way is to use a view attachment and put another view in the footer


Views Taxonomy Term argument to represent "no term"

Just in case anyone else stumbles upon this answer, we solved this problem with the following approach:

function MODULENAME_views_query_alter(&$view, &$query) {

  if($view->name == 'your_view_name')){

    //Flip the term table join to a LEFT join
    $view->query->table_queue['term_node_value_0']['join']->type = 'LEFT';

    //CLear the extra condition (removes a where clause on the join limiting only matching term ids)
    $view->query->table_queue['term_node_value_0']['join']->extra = null;

    //Look through the where clauses and add a null condition clause
    if($index = array_search('term_node_value_0.tid = %d', $query->where[0]['clauses'])){
      $query->where[0]['clauses'][$index] .= ' OR term_node_value_0.tid IS NULL';
    }
  }
}

It changes the JOIN type to a LEFT join, removes the limiting clause from that join and adds a condition to match against null values.  It's obvious limitation is that it should be using aliases instead of hard coding the field name.

The function should go in your modules views.inc file where Views expects to find this hook.


I've successfully used a combination of the following modules to do similar migrations:

feeds (for import)
feeds_tamper (data normalization and mapping)
views_rss or views_bonus (RSS feed of nodes or CSV export)

I can see (although I've never used) a patch for the Feeds module to maintain aliases as found here http://drupal.org/node/1284522

One big bonus with using the Feeds module for import is it understands (through a hashing system) data that has already been imported. So, if you used the ViewsRSS module you can setup a timed event for Feeds to grab only the new or update existing content without having to initiate a transfer on the production server -- they just stay in sync. I've also implemented a workflow where nodes are only published in the RSS feed after they have been reviewed by an editor ...

Cheers,

Rob McCrea


How to access existing data in the row during Migrate?

Answer lies in PrepareRow() method you will implement... You always have access to source where reference to destination is given.. For example if you are importing a node you will have nodeid reference.. From node id you can get destination details using node_load api function..

Similarly for any other entity if you are updating you will have a reference in source using which you can load destination details...


How can I remove the space between fields show in a view that are output with a custom template?

I just created a quick View here that had three fields:

1.  Node title.
2.  Node type.
3.  Global Custom Text Area

I changed the HTML Element and Wrapper HTML Elements to SPANs for the first two fields and also set them both to be excluded from display.

For the Global Custom Text Area, I rewrote its output to be [title][type] and got the titles smashed right up next to the node types without a space.

ADDITION:

You could also copy views-view-field.tpl.php to views-view-fields--smashed.tpl.php (or whatever your Views name is :) and then remove all the whitespace from there, eg, this template looks nice like this:

 <?php something ?>
   <?php something else ?>
   <?php something else again ?>
 <?php yadda yadda ?>

and each of those lines and indents puts in the whitespace that is causing your grief.

If instead this is saved as

 <?php something ?><?php something else ?><?php yadda yadda ?><?php one really big long line of code without any intervening tabs or new lines or spaces ?>

and your view will be created with the <divs> or <spans> smashed right up next to each other in the row.  Then CSS it up the way you want.


A better solution to make image field into div background?

There is also the Background Images module suite:

  Background images is a collection of modules that allows users to add
  background images to html elements on pages of the site.

There is also a Field Group sub-module for background image support called Field Group Background Image:

  This module creates a field group display formatter that consists in a
   wrapper with a background.

  The background can be set from:

  An image field of the entity being displayed
  A color field (of Color Field or jQuery Colorpicker modules)

  This module can be used alongside
  Display Suite, and is particularly useful for creating custom
  Fieldable Panels Panes bundles.

You mention parallax scrolling ... I know what that is, I've never had to implement it -- you may want to try to use Parallex Background:

  This a simple module that allows to set a vertical Parallax effect on
  the background of any element on the DOM.

I kindly suggest you work more on your Google-fu skills.


What is the correct way to document the schema for a YAML file?

There is no "documenting" of hooks in D8 except the mymodule.api.php as you've already mentioned(+ impleneting hook_hook_info).

The YAML files are only for:

services
routes
menu local tasks
menu local actions
libraries
module info
simple configuration
simple configuration schema

Now you've mentioned "info" hooks. In Drupal 8 these are Annotations and their implementations are Plugins. If this is assumption correct then see the documentation in here https://drupal.org/developing/api/8/plugins for plugins - what they are, how they work and how to use them.


How to add custom user fields to their comments?

I haven't tried this out for sure, so this is kinda just spit balling, but the way I would do this would be to write a small little custom module. So, example:

You could have the date/avatar field stored as a field in the user table. Then in the comments, add both a date/avatar flied to the comment (under /admin/structure/types/manage/[node type]/comment/fields). So now you would have to two places to save the info.

To hook them up, I would write a custom module that uses hook_comment_presave to intercept the date and avatar field before the comment is saved, load the user info from the commenting user, and then replace the comment date/avatar from the user date/avatar. That way, the information that was with the user at the point of commenting will be forever with the comment.

You will of course need to theme it, and you will need to hid those comment fields from the user in the comment form. Your also gonna want to make sure the avatar is persistent, but I think this should be a workable solution. At least, that's where I would start.


Sounds like you're looking for the Edit Limit module.

Edit Limits adds certain limits to editing nodes and comments. This can set the number of times a node can be edit. This can also set a time frame for nodes to be edited, as well as a different time frame that comments can be edited.
Comments can be set to only be limited within a given time frame. Site administrators can set the number of seconds after a comment is initially posted before it can no longer be edited. Time remaining will be displayed to the user.

Unfortunately, the module is not well documented, but here is an example of how you may use to provide a three minute grace period for editing own comments:
First navigate to Administration » People  » Permissions. Under Comment, enable the permission "Edit own comments" for whatever role you want to have this permission (typically "Authenticated user").  Scroll down to the bottom of the screen and press "Save permissions".
Then, navigate to Administration » Configuration » Content authoring » Edit Limit and configure the module to enable comment limits, to three minutes, and select the content types you want this to apply to.  Press "Save configuration" when done.

This is how it looks like when working:

At the time of writing, it does not work for RTL languages.  See this issue: Edit Limit doesn't show edit link for RTL languages for the current state of this bug.


Image module custom image style changes image link

I found a fix by adding

$conf['image_allow_insecure_derivatives'] = TRUE;

to my settings.php file

I found the solution from this drupal stack exchange posting:
Drupal 7.20 Image Styles return a url with Access Denied

I'll hold off on accepting my answer here as the accepted answer for a bit in case someone informs me that I should not be solving the problem this way.


Show and hide form element based on values of other form elements

Why the in-between form element? You can use the states API to check for a value in a select as well. Just check the student form element and it's value all.

$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      ':input[name="student"]' => array('value' => 'all'),
      // Use multiple lines here for an AND condition. eg:
      // ':input[name="other-field"]' => array('value' => 'all'),
    ),
  )
);

This way you can remove the AJAX callback, and the bookpage_toggle element.

If you want to support multiple conditions, you can wrap the jQuery selectors in another array  to function as an OR:

$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      array(':input[name="student"]' => array('value' => 'all')),
      array(':input[name="student"]' => array('value' => 'other value')),
    ),
  )
);

Finally if you want exclusive OR (XOR) you can do it like this to toggle on one of the elements, but never both of them:

$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      'xor',
      array(':input[name="student"]' => array('value' => 'all')),
      array(':input[name="student"]' => array('value' => 'other value')),
    ),
  )
);

See this comment for AND, OR and XOR and a combination of those.


How i change scripts in my custom theme in drupal 6

It's been a while but I think this is the way to do it in Drupal 6:

function MYTHEME_preprocess_page(&$vars) {
  // Add your JS
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/my-tableheader.js'));

  // Get the cached JS
  $js = drupal_add_js();

  // Remove the core tableheader file
  unset($js['module']['misc/tableheader.js']);

  // Change the scripts var to reflect the new array
  $vars['scripts'] = drupal_get_js('header', $js);
}


How do I display self-hosted video content

A learning process for anyone who makes the same mistake.

I found that the files had be uploaded with role based content access as part of our file repository. That meant anonymous users would get a 403 error.


Inline CSS stripped from Global: Custom text in Views

It's still not wise but use a custom PhP field : Views PhP (it's "Views custom field if you're on D6).


Does user_is_logged_in() check if there is at least one user logged in?

By looking at the Drupal API, you can see the function itself:

<?php
function user_is_logged_in() {
  return (bool) $GLOBALS['user']->uid;
}
?>

Which shows that it returns TRUE if the current session is a logged-in user, or FALSE if the current session is an anonymous user.


How to display a views slideshow placeholder?

Your slideshow is a View. So:

Go to edit page of your view
Expand "Advanced" field set
Add new item into "NO RESULTS BEHAVIOR"
Choose "Global: Text area"
Add your placeholder html there. E.g.
NO-IMAGES

Save View


Drupal 7: Database select query FROM cache_bootstrap brings server down

If you can get memcache properly installed, that will help the most as it will shift queries from the cache tables in the db to your memcache server.

Try these 3 things (in order of importance):
Set the transaction isolation level to Read Committed - https://drupal.org/comment/8437127#comment-8437127 (look in your settings.php for the insertion point; it will be after the $databases variable has been set with the database credentials). This is helpful even if using memcache.

$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

Change your semaphore table to memory - https://drupal.org/comment/8469889#comment-8469889 (use the first code block "Have the name value be a primary key"). Note that this might not work if you are using MySQL 5.0 or lower due to BTREE indexes not working in Memory tables. Also noted that if you are using the memcache version of lock.inc this will not help.

ALTER TABLE semaphore ENGINE = MEMORY;
ALTER TABLE semaphore DROP PRIMARY KEY;
ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE;
ALTER TABLE semaphore ADD UNIQUE name (name) USING BTREE;
ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;
ALTER TABLE semaphore DROP INDEX expire;
ALTER TABLE semaphore ADD INDEX expire (expire) USING BTREE;

Apply this core patch - https://drupal.org/node/2193149 This will help to reduce database deadlocks from occurring only after the above 2 have been done. If using memcache this core patch will not help as this fixes an issue when using the database as a cache backend.


With a view template file it was possible to place the grouping field at the bottom of the View.


drupal identify which content type is not used

Just go to http://example.com/admin/content as user 1 and filter content by content type. If there is nothing, then content type is not used. Note that there may be views or modules that expect some content types to exist, even if you are not using them at the moment, so always make a backup before dropping them.

For fields, go to http://example.com/admin/reports/fields - you will get a nice list what is used where.


I found a solution to my problem. There were two changes I needed to make.

The first was in the .htaccess file in the "files" folder there was the line:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

When I commented out this line I could see the images again.

However, I was still having problems generating new ImageCache images. I managed to fix this by adding the line below to the settings.php file:

putenv("MAGICK_THREAD_LIMIT=1");

I find out this last solution from my hosts (1&1) technical support.


How to create Ubercart recurring order with initial $0.00 charge

If you look at ubercart subscription it offers the ability to create a subscription product with an initial trial period of x days/months and then the amount to charge per day/month following the trial period.


How to use the D3.JS library for data visualization?

There are at least 3 contributed modules which may help to use the D3.js library (open source, released under the BSD license) in a Drupal 7 site:

Charts and Graphs:

  Charts and Graphs is an API for developers. It can be extended by third-party modules that want to add their own charting implementations. It does nothing by itself. It should only be installed if some other module requires it.

D3 (Alfa release only):

  creates visualizations as libraries (alpha version only) which allows one to add/remove visualizations, share them between modules, and integrate them with (for example: Views) through library .info files.

The Basic module configuration presentation provides a short intro about how to use the module in combination with Views.
Forena

Comment 7 in issue 2364427 contains an example of a custom module to use the Forena module for creating charts using the d3.js library.
Issue # 2383509 describes the approaches for using D3 with Forena.

If you decide to not use any of these modules, it may help to get started with D3.js integration in Drupal by just looking at the code of these modules. Either to roll your own D3.js cookies via a custom module, or at least to get an idea of the required effort.

The D3.JS Tutorial is a great place for documentation about how to use this library.


why drupal webform form setting shows mysql errors in dblog?

INSERT INTO {webform} (nid...

tries to insert the nid of the webform (got from auto-increment in the node table) in the {webform} table. So, every nid inserted in nid column of webform table should be unique. But it seems that the newly-created webform node got a nid that already exists in webform's nid column.

So I guess there's something wrong. Find that nid in webform table, see if it exists in node table, that must be the trick.


How can I build an accordion without Javascript using the Field Group module?

Yes, you can use the HTML 5 details tag.
On the content type display administration page, create a field group.
For the Format, chose HTML element.
For Field group label, enter the text you want to show to click to display the rest of the text.
For the Element, enter details.
For Show Label, select Yes.
For Label element, enter summary.
To style with CSS, add extra CSS classes as needed.


move $messages div to inside the form tag

Copy your webform-form.tpl.php from the contrib webform module folder (under templates) to your themes templates folder and make the modifications there.

Default code:

if (isset($form['preview_message'])) {
  print '
';
  print drupal_render($form['preview_message']);
  print '
';
}


Suggestion tpl help for NiceMenu markup?

Why can't you just position your li's absolutely? Generally, you should be able to position li's the same way as separate ul's using CSS.

Anyway though, to answer your question, have a look here: Customize Drupal 6 Nice_Menus Output

(Ok, you're asking for D7, but the general idea should be the same/very similar.)


I'd prefer to avoid editing templates for such simple things as adding just classes. I'd recommend to edit templates only if you really need to make changes to the markup.

For adding a simple class to your image all you need is the following snippet placed in your custom (sub-)theme's *.theme file. (Replace MYTHEME with the actual machine name of your theme). This one identifies the image by its image style (so ensure to have an unique image style applied to your image):

/**
 * Implements template_preprocess_image().
 */
function MYTHEME_preprocess_image(&$variables) {

  // Check the image style.
  if ($variables['style_name'] == 'img_fluid') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}

If you are fine with adding the class not to the img tag directly, but to its wrapping container you could also use the following snippet. You can broaden the if-request as you like to only fire on certain content types (as you maybe use the same field in other content types as well), p.e. check for $variables['element']['#object']->bundle(). Replace field_MYIMAGE with your actual field name.

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  // Check for your image field.
  if ($variables['element']['#field_name'] == 'field_MYIMAGE') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}


Try using Total Subscription which says :

Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.

Or you can try Simplenews module as well, which has feature of rules integration so that you can customize it with taxonomy.


How can I apply node template file only to node view page but not revision page?

I don't have a D6 site around with revisions enabled so I can't test this, but the following code should disable the custom template for the revision pages:

function MYTHEME_preprocess_node(&$vars) {
  $template_name = 'node-content-type-name';

  // Work out if we're on a revision page
  $on_revision_page = arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions';

  // See if the rogue template file is available as one of the suggestions.
  $template_index = array_search($template_name, $vars['template_files']);

  if ($on_revision_page && $template_index !== FALSE) {
    // Remove the rogue template file from the suggestions.
    unset($vars['template_files'][$template_index]);
  }
}


Call to undefined function db_affected_rows()

As it happens UpdateQuery::execute() returns

  The number of rows affected by the update.

So instead of:

$result = db_update('uc_dependent_attributes')->fields(array(
  'enabled' => 0,
))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
$affected_rows = $result->rowCount();
if ($affected_rows!=0) {

use:

...
$affected_rows = db_update('uc_dependent_attributes')
  ->fields(array('enabled' => 0))
  ->condition('nid', $form_state['values']['nid'])
  ->condition('combination', $value['combo_array'])
  ->execute();

if ($affected_rows == 0) {
...

(there's also a small fix to the conditional logic)


Getting session variable in view contextual filter drupal 8

You'll need to create a custom module and pass the value Group ID value using hook_views_pre_view

Example:

/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for my_special_view.
  if ($view->id() == 'my_special_view') { // target a specific view
    // if you want you could make it even more specific by adding ex: "&& $display_id == 'block_1')"
    $group_id = $_SESSION['groupbysession']['group_id'];
    $args[0] = $group_id; // set argument
  }
}


How to theme output of node_view_multiple()?

The return from node_view_multiple is supposed to be a dumb collection of node render arrays, it's not meant to be themeable in and of itself (at least not on a generic level, obviously case-by-case you can do it). The function sepecifically doesn't get involved with the theming, as that should be up to the caller to determine. So using #theme or #theme_wrappers on the outer array is the correct thing to do.

There isn't anything you can do to target other modules' use of node_view_multiple() in this respect, short of:

Patching the module code
Patching node_view_multiple itself so it has a default theme function, which you can then hook into.
Use a broader attack like hook_page_alter() to make specific changes to specific arrays when it makes sense to.


By checking the drush code itself, we discovered the possibility to add contrib_destination on specific project level.

projects[views][] = ""
projects[views][contrib_destination] = "sites/site1"

However, as it would had quite a lot of lines to the makefile (we must add the contrib_destination line to all modules used by site1 only) we decided to not use the includes feature and to keep to separate makefiles.

To build our docroot, we then have one "global" makefile to prepare the sites/all modules and another ones for each subsites (sites/site1). Then we launch the drush make command for each makefile (using a shell wrapper to handle it).

This is not perfect and would probably be easier to have something build-in (I don't know what would be the best syntax for that).


How capture video thumbnail , when video is uploaded under media video type file?

You can use https://www.drupal.org/project/media_thumbnails_video for this.
It has a dependency (php-ffmpeg/php-ffmpeg) that requires both the FFMpeg and FFProbe binaries to be installed on your server.


Users cannot login. The username field is highlighted red, but there are no error messages. There is no password reset link

Perhaps User 1 (if that's the admin login you're using) is blocked somehow. There could be a module, or custom code somewhere that is blocking this account's login.

I'd try looking through the list of contrib (contributed/non-core) modules for any who's name looks like it might be responsible for limiting login access.

Also, look for any custom modules and look through their code for any hints that it may be limiting logins also.

If you find a suspect then try disabling the module to see if this resolves the issue.

Another place to look for possible culprit code is in the active theme's template.php file (usually located in /sites/all/themes/THEME_NAME/template.php)


Try this piece of code from a similar question

global $theme;
$all_regions = system_region_list($theme);
$blocks = array();
foreach (array_keys($all_regions) as $region) {
  $blocks += block_list($region);
}


Is there a way to limit / enforce permissions on image style downloads?

This is not really possible. The module the create this doesn't care or know where the image comes from, so you can't make any permission checks like that. It would be possible to display such images through custom theming Views and many other ways which makes a 100% failsafe permission check more or less impossible.

You can make sure nothing like this will happen based on how you setup your site, and you could add some extra security by overwriting the settings/rendering for image fields, but it won't be 100% fail safe.


Can't acces my site and without login and drush clear cache

Make sure your database connection to the DB server is correct. I was using an older local password for DB which caused a similar issue when moving to live hosting.


I've done some tests using an Entity Reference field, and setting its default value in a hook_form_alter implementation. Everything is working fine - when I upload a single or multiple image files, the default value that I set in the hook for the Entity Reference field is preserved, and is saved fine when I press Save.

Please notice the way I'm setting the default value in my implementation of hook_form_alter(). This is different from what you have:

$form['field_reference_to_page'][LANGUAGE_NONE]['#default_value'] = 'trip (189)';

(My field is called field_reference_to_page. In your case, you 'll need to replace with field_boardgame). Notice that the arrays are different from what you have. Basically there is no [0] or ['target_id']. The value 'trip (189) is the title of the node and the node ID that this field is referencing. I made sure that the node really existed, and the node ID was correct.

I put together a short video proving that it really works.

By the way, Image fields cause an AJAX call when an image is uploaded - the form is rebuilt but not reloaded. But as I said, the default_value is preserved if you implemented the form alter correctly.


setting template file using template_preproccess_page not working

Assuming D6 then, in template.php:

/**
 * Implements hook_preprocess_page
 */
function THEMENAME_preprocess_page(&$variables){
 if (strpos($_GET['q'], 'value/abc') === 0) {
   $variables['template_file'] = 'testing';
 }
}

Clear theme registry, or all caches at admin > config > performance to apply.

More info:

  There are two special variables that these hooks can set:
  'template_file' and 'template_files'. These will be merged together to
  form a list of 'suggested' alternate template files to use, in reverse
  order of priority. template_file will always be a higher priority than
  items in template_files. theme() will then look for these files, one
  at a time, and use the first one that exists.
  https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme/6


An example

    use Drupal\Core\Url;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

Its not working in Form validate.

Its working un submitform

public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('route.path');
        $form_state->setRedirectUrl($url);
}


How can I add paragraphs to a translated node?

If I remember this right this is by design (or maybe more a technical necessity). And you can only circumvent this by having multi-value fields inside a paragraph type. Like a node reference field for example. This then can have a different number of items per language and even in a different order.

You could also add a new untranslatable "Visibility" field to each paragraph type, like Paragraphs Collection is offering it, see 2846682#comment-11887724 for example. Then you add different paragraphs in the original language but set them to be displayed only in selected languages.

And regarding Paragraphs Asymmetric Translation Widgets you may file a bug report in its issue queue.


How can I render a field based on the value of another field

Try this:

$logo = render($content['field_logo']);
hide($content['field_logo']);
// ...
<?php if ($content['field_boolean']['und'][0]['value'] == '1'): ?>
  <?php print $logo; ?>
<?php endif; ?>

At the moment you're hiding the logo field, which will probably prevent it from being rendered at all, even the second time you call render(). Taking a copy of the rendered logo field and outputting it later should work instead.

You could also do it this way:

<?php if ($content['field_boolean']['und'][0]['value'] == '1'): ?>
  <?php
  show($content['field_logo']);
  print render($content['field_logo']);
  ?>
<?php endif; ?>


What is the best method to customize the display of author information on a node of a certain type?

In your code at

 $node->field_blog_image['und'][0]

this is still an array so you need to access the value of the field one more level deep in to that array you can access it as follows.

$node->field_blog_image['und'][0]['safe_value']

Rest of code looks good to me.


js-header and js-footer are not loading drupal 8

You may be over-complicating this. HTML5 shiv is already in core, so you can just depend on it without any extra work. There's no js-header or js-footer keys, just use js as normal:

portfolio-library:
  version: 1.1
  css:
    theme:
      assets/css/main.css: {}
      #assets/css/font-awesome.min.css: {}
      assets/css/ie9.css: {IE: 'lte IE 9'}
      assets/css/ie8.css: {IE: 'lte IE 8'}

  js:
    assets/js/skel.min.js: {}
    assets/js/ie/respond.min.js: {IE: 'lte IE 8'}
    assets/js/main.js: {}

  dependencies:
    - core/jquery
    - core/html5shiv

If you need your own version for whatever reason, declare the shiv separately:

html5shiv:
  header: true
  js:
    assets/js/ie/html5shiv.js: {IE: 'lte IE 8'}

and depend on it:

portfolio-library:
  ...
  dependencies:
    - core/jquery
    - mytheme/html5shiv


You could start by setting the number of items to index per cron run at 1000, and set the solr index cron hook to fire every 5 minutes using a drupal cron management module such as Elysia cron, which will allow you to set different intervals for all the other cron jobs on your site.

That's a reasonable setting to start with, which would be a big win over what it's currently set to, and would complete overnight. From there you could monitor for errors while tuning those 2 settings to see what the overhead on your system is.

Or you could just set that cron batch size variable on your Solr index to "-1" which is the magic setting that tells cron to index everything at once. Obviously, this has performance implications. Apache Solr Search in Drupal also has an "Index items immediately" option to force update the entire index as soon as you save the setting, and not wait for a cron run.


How to check the Webform submission values in a twig template

Adding :raw to your webform submissions value has worked for me.
{% if webform_token('[webform_submission:values:airports_to_radio:raw]') == 'Heathrow' %}


Is there any convention about the form IDs?

Drupal core doesn't use the dot in the form IDs because, as the documentation for FormInterface::getFormId() says, the form ID should be a unique string that can be a valid PHP function name, since it's used in hook implementation names such as hook_form_FORM_ID_alter().

The form IDs Drupal core uses follow the <module name>_<form name> schema, so you will find form IDs like the following.

user_admin_settings
action_admin_manage
layout_builder_add_block

As long as the form ID is unique, any scheme would work. The convention to prefix an ID with the module name (i.e. the module machine name) has been used from Drupal since many years.


Why JQuery 2.x was removed since jquery_update-7.x-3.0-alpha2?

Version 2.1 has not been removed; its files are still present in the 7.x-3.x-dev development snapshot.
What eventually was done is updating the version 2.1 files to version 2.1.4, since they don't keep multiple 2.1.x versions (e.g. 2.1.0, 2.1.1., 2.1.3).


Drupal cron will unserialize array and add extra characters

Thank you for your input. I open the PHP file with Notepad++ and there was the hidden tilde character. I remove it an everything started to work again like a charm.

For people having a similar issue, I will recommend opening the file in a different text editor.


Where do I specify the URL of the incoming XML?

You make the linkage to the XML input in feeds instance definition.

The D8 Feeds module follows the entity module with definitions and instances.

There are the feed type definition which defines the processors and mappings.  These are created in the configurations feeds admin screen.

And there are the feeds instances.  These are where you define the input and it's basic settings for a feed type.  They are created under content / feeds.

This is an improvement over the prior versions as it lets you use the same feeds mappings over different inputs.


How to attach a database of data to a content / entity type

I would use a custom content type that stores the primary key (pk) of an instance of Foo as text, integer or whatever you need, just that one field.  Let's call the content type Bar.

Then for display create a node template for Bar that:

Queries your database by sending Bar->pk and returns the Foo row/object
Iterates through the fields in the row and displays them where and how you choose

In case you haven't already come across it, if you're intending to use an external database, it is best to define it in your settings file and call it when you need it as described here.


I have often been advised to just save my Views as a Feature. Any reason this won't do the required?


How can show block when mouse over icon in menu

That looks like a "Megamenu" type menu configuration.

You could try using a module like

om_maximenu
menu_minipanels

To acheive that design effect.


It seems that you're asking more than one question, but let me try and address the paths one. If you organise your taxonomy to be hierarchical then using the token [catpath-raw] will give you the path you require.


Point visitors to directory depending on Drupal site visited

If you used a drupal multi-site installation for the various websites. Then each site may have it's own dedicated Files directory which may be set in Admin -> Media -> File System per subsite.


Commerce checkout does not work when loading from AJAX

I had exactly the same Problem, i think this page should help you: Loading a form by ajax.

I have solved this problem, but I think its a little bit ugly. The Problem was that I have loaded the checkout form, but not the scripts which are necessary on the checkout page. So i have loaded the scripts from the checkout page, too. After that i have done a

Drupal.attachBehaviors();

So all scripts can attach there functionality to the checkout form.


Check if field is empty in Views field Template

You can use the Views Conditional module. With it, you can add a conditional field that would evaluate the value of your 'Price on application' field. You can then add the other two fields in a personalize text excluded from display and use you conditional field to display it or not depending on the condition you want.


How to setup custom 404 page that will ignore the path?

In my case, the main problem was that there were blank landing pages for the parts of the URL.  For instance, there was a blank US page for /US/Training/page-title.  So, Drupal was finding /US and just redirected the visitor to that page.  Because of this, no 404 was being registered, therefore never redirecting to the 404 page.  None of the 404 modules helped for this.

Because I have a Taxonomy term for the Country that is used to set the URL, I simply removed the blank landing pages.  Now, it will properly register a 404 and will go to my custom 404 node.


Is it important to assign CSS injector and JS injector code snippets to specific pages instead of site wide?

For those amount of lines, it's no biggie, specially if you're caching, as those lines gets cached as HTML.

An alternative, the good practice, would be to add the css to your theme's style.css file and the JS to your theme.info file. That way you can aggregate and compress them along with your other files.

Aggregating and compressing makes a huge difference. You should do that if you aren't already. (speaking of all your css and js files).


I fixed this by using hook_search_api_solr_query_alter() and solr function. Here is my code:

function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if ($_SESSION['language'] == 'en') {
    $call_args['params']['sort'] = 'termfreq(ss_field_name,EN) desc';
  }
}


Action to be triggered on Comment Approval

Currently there is no rules condition to do this but there is a patch in the rules issue queue.
You can try using that, and if you do you can report back to that issue and help it get committed to the rules module.
http://drupal.org/node/1421058#comment-6532372


Alternative themed forms for a single custom content type

My first thought (in Drupal 6) would be to use hook_form_alter to set a different #theme value in the form depending on the path.

eg

mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id = 'my_form_id') {
  if ($_GET['q'] == 'somepath') {
   $form['#theme'] = 'function_one';
  } elseif ($_GET['q'] == 'someotherpath') {
    $form['#theme'] = 'function_two';
  }
 }
}


Programmatically save image together with its ALT

As far as Drupal 8 is concerned, there is another solution :

//    $file : my File Entity
//    $node : my (Node) Entity having an Image File field associated
$node->field_my_image_field[] = [
 'target_id' => $file->id(),
 'alt' => 'Alt. text',
];
$node->save();

Well, I think that 'width', 'height' and 'title' are also available in the setting array (but target_id seems required).
cf: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldType%21ImageItem.php/class/ImageItem/8.2.x
(look at the source code, generateSampleValue() method).


Media module is bring contextual links with it into the middle of WYSIWYG content - how to remove?

You'll have to change the sort order of filtering within your text format, admin/config/content/formats/full_html (for Full HTML text format).
Just place the "Convert media tags into markup" before the "CKeditor Link filter".


3 reset button with auto submit for each and reset all

This following post has a nice hook_alter function that adds a reset button to exposed filters on views. It lists both code for 6 and 7.

http://fleetthought.com/blog-post/adding-reset-button-exposed-views-filters


Spam registrations even after adding domain to Mollom blacklist

Try using Honeypot, it's a module specially designed for spambot filtering...


DatabaseScheme Error when trying to install Jabber

Run database update then try reinstalling the module.

Also do keep backup of your database before running the update.


How to declare @font-your-face local fonts in CSS?

There is an option to apply the CSS in the theme in the drop down of the @font-your-face UI.


The issue is not about the form rebuild, the form is being automatically rebuilt on every AJAX call.
The issue here is of the wrapper is not being defined in the '#ajax' array and the wrapper attribute should be given to a "container" type of field and then all of the updated fields should be part of the respective "container" field.

or some ajax command should be called on $response object in the ajax callback method above.

e.g.

public function blockForm($form, FormStateInterface $form_state) {

$form['link'] = array(
  '#type' => 'container',
  '#attributes' => array('id' => 'link-wrapper'),
);
for ($i = 0; $i < $this->configuration['linkNum_submit']; $i += 1) {
    $form['link'][$i] = array(
        '#type'          => 'textfield',
        '#title'         => 'Link',
        '#default_value' => '',
    );
$form['add_link'] = array(
  '#type'     => 'button',
  '#value'    => $this->t('Add link'),
  '#ajax'     => [
    'callback' => array($this, 'addLink'),
    'event'    => 'click',
    'wrapper' => 'link-wrapper',
    'progress' => array(
        'type'    => 'throbber',
        'message' => t('Adding link...'),
    ),
],

);

and then in the ajax callback

public function addlink(array&$form, FormStateInterface $form_state) {
  return $form['flipper']['front']['settings']['link'];
}


With help from Lennert at gettingsocial.nl I was able to solve this. The trick was to not use the drupal method to load the jquery.rating.pack.js as the script needs to be loaded after the checkboxes have been added. (the drupal_add_js() function will put it in the header).


Try to change:

if($form_state['input']['field_departure_tid'] === 'All')

in

if($form_state['input']['field_departure_tid'] == 'All')

And inside _form_alter function add this string to see the content of field_departure_tid

var_dump($form_state['input']['field_departure_tid'])

because if I don't wrong remember field_departure_tid is a number not a string.


How to add a javascript field to custom content type

First things first: a warning.
This sounds like an extremely dangerous idea. If you do this, please at least make sure that you're only opening this up to trusted users (as allowing people to place javascript on your page could lead to some very, very bad things, much like the php filter.)

That being said, if your sure you want to do this, your gonna need to add the js to your page programmaticly. You could easily do this through your theme functions of template_preprocess_node.

Find that function in your template.php file. You'll want to add a condition to check for the content type, then grab the js file and use drupal_add_js to grab the attached js file and attach it to the head.


How to prevent users from adding content without putting the site into full maintenance mode?

I would uncheck the "add [type] content" permissions checkboxes on the roles that have it, and re-check them after. However, depending on the updates, having people attempting to log in or use other features of your site may be problematic during updates.


Creating a form where users can edit their own submissions

In the
Home » Administration » Structure
and in the content type
add new content type and create your forms as you need

You can edit every content type i.e. node and
for editing own submissions you can set appropriate permissions like 'edit own content' in the
Home » Administration » People  under permissions tab

For multistep forms
you can in the hook_form_alter() create

$form['redirect'] = 'your_next_form_path';

By using redirect as soon as the form is submitted you will be redirected to other form (only thing is proper path for node or form needs to be mentioned).


How to show the count of members that belong to a group?

I finally figured it out:

(enlarge image)

The steps are:

create a view for "content" type "group". Use "fields" and show "content:title", that's the name of your group
add relationship "Group: Node group" (required), then "(group) Organic groups group: OG membership" (required).
add filter "(OG membership) OG membership: Entity_type " and set to "is equal" to "user"
"use aggregation"
add field "(OG membership) OG membership: Entity id" and use "count distinct" option. That's your count of members.

If you want the count of nodes that are "linked" to a group you would just change the filter from "user" to "node".


Fetching title of articles with taxonomy terms which are its siblings

Can you create contextual filter in Views -> taxonomy parent term ID.
This should work.


I think you are asking how to save user picture. Users table holds the place for picture.

$account = user_load($new_user->uid);
user_save($account, array('picture' => $fid));

EDIT

Profile2 module is based on entities using Entity API module. You can use entity_metadata_wrapper('profile2', $profile->pid) to get a metadata object. This object will hold the properties (native profile2 fields) and Fields (additional properties plugged in via field api or Field Admin UI)

$profile = profile2_load_by_user($account, 'main');
$profile_w = entity_metadata_wrapper('profile2', $profile->pid);
$proflie_w->field_myfield->value(); // This is a read operation
$proflie_w->field_myfield->set('new value'); // This is write operation
$proflie_w->save(); // Finaly save the things

You can bypass metadata wrapper.

$profile = profile2_load_by_user($account, 'main'); // Loading existing profile instance
OR
$profile = profile2_create(array('user' => $account, 'type' => 'main')); // Providing a new profile instance
$profile->field_myfield = "new value";
$profile->save();

NOTE: you can check all your listed properties using foreach operation on the wrapper object.
e.g.

$profile_w = entity_metadata_wrapper('profile2', $profile->pid);
foreach($profile_w as $key => $obj){
   debug($key) // give you name of your property


D8 requires more resources and yes, you should have hosting with opcache enabled, which is included by default in PHP 5.5.

Drupal 8 has so many files because it includes symfony and other projects and everything is a class.

FTP is a very bad idea for D8 and web in general in 2015. Look for a better way to do web hosting.

That said, it should not take that long. I suggest you open a bug report  and provide as many details as you can about your specific PHP version, hoster, the errors that you had, ..


send user registeration mail in html format

I recommend using PHPMailer module.
https://www.drupal.org/project/phpmailer

It is used to send HTML emails with Mime Mail.


Why does d7_user_role need a db connection configured when migration group already defines it

The section of migrate_plus.migration.mysite_user.yml that reads this:

roles:
      plugin: migration_lookup
      migration: d7_user_role
      source: roles

has to be edited by switching "d7_user_role" for the id of your user role migration, which in your case is "mysite_role"

roles:
      plugin: migration_lookup
      migration: mysite_role
      source: roles


Error occurs every time I try to log in after updating

Call to undefined function Drupal\commerce_price\bcmul() in Drupal\commerce_price\Calculator::multiply()

Drupal Commerce requires the BC Math PHP extension - you don't have it in your current environment.

To fix, rebuild PHP with support for the BC Math extension.


It follows the same pattern in the POST request with relationships section of the docs you linked to.

Your endpoint will be /jsonapi/comment/$MY_COMMENT_TYPE.
Your data payload will need to contain both the data property (the  comment's properties) and relationships property (which will contain the comment's author & the entity reference commented on). To get a more concrete example of your data payload, perform a GET /jsonapi/comment/$MY_COMMENT_TYPE to see examples of existing comments.


There is a module that replace some tokens accepted from the Token module (or implemented using hook_token_info() and hook_tokens() in Drupal 7) in the body of a node, the Token Filter module.

  Token Filter is a very simple module to make token values available as an input filter.

There is then the Token Node Tokens (TNT) module that allows to define new tokens without implementing a module.

  TNT (Token Node Tokens) is a very simplistic module that allows you to create arbitrary tokens without having to create a custom module (i.e. /node/add/token). This was primarily created for use with the tokenize module so that through the UI a user could create tokens for use with CCK.

Unfortunately, this module has been declared unsupported, but looking at its code, you could create your custom module for doing the same thing.

An alternative is the Custom Tokens module.

  It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.

  Versions 7.x-1.x and previours relied on PHP evaluation to build custom tokens.

  The new 7.x-2.x relies on input filters. While still allowing for PHP tokens through the D7 core PHP filter module, administrators can permit only HTML or plain text custom tokens.


Alternative to creating large number of fields via UI for a content type

There are two ways you can accomplish this:

Write a custom field, with the 50 necessary fields compounded into the field's columns (this will create 50 columns in the field data and revision tables, but obviously you've got to store your data somewhere). There's an excellent example of writing a custom field in the Examples module.
Write a custom entity. This is probably more work, but using this method you can make your 50 fields entity properties (rather than fields in the Drupal sense), and the data will all be stored in the base table for the entity. Again, that's a large-ish number of cols for a table, but your data needs to live somewhere.

Both methods give you the flexibility to create the input forms yourself, so either will let you achieve whatever UI you think is most appropriate for inputting that amount of data in one go.

Note that using the standard field API is considered best practice, which is probably why you're struggling to find modules that do it differently.


What is the most drupal-like way to bring the title of a single node page into the rest of the content?

It is valid to do it the way you are doing it and it would also be valid to not print the title in the page tpl for certain nodes and instead print it in the node template.

It's subjective as to which is preferable (if one is even better than the other) and the preferred solution may change based on your specific requirements for a given project.

One thing to consider is anything that usually prints out between the title and the content in your page template.
Will moving the title into the content (in this case the content is essentially the node template) mean these nodes will be inconsistent to the rest of the site (for example, will messages/tabs/help/etc. be in a different place on these nodes)?
If they were to be different would it matter to you?

Yes, you can still use hide($content['field_doc_cover']); in your node template in this case.

There are also alternatives depending on your site and requirements. For example the Panels module allows you to assign specific fields to different regions and there are a number of ways to get a block to show parts of a node so that you can assign that to a different region using Drupal core or the Context module or similar.


Enumerate content in custom view template

Welcome to Drupal!

Use row level templating in template suggestion and follow exactly the same markup so your code should look like the following

<?php print $fields['title']->content; ?>

It will follow the same markup for each row.


I believe you are experiencing a problem that Plupload has with PHP 5.3.x. I built a site for a client that uses photo galleries (Media and Media Gallery), and via the Pupload Integration Module galleries could be built by simple drag-and-drop of multiple image files. The site is hosted on Rackspace Cloud, which recently upgraded from PHP 5.2.x to PHP 5.3.14. That's when the problems began.

There is a bug report for the Plupload Integration module that shows the error I'm now getting. If you're getting the same error message, I'd recommend that you also take part in the thread, as I just did.


latest zen theme make the admin drop menu failed to work

Is it possible you've confused the Drupal 7 "Toolbar" module (which is enabled by default on D7) with the behaviour of the familiar "Admin Menu" module?

If so, then you can get the behaviour you want by

Install Admin Menu module
Visit your modules page and disable "Toolbar", then enable "Admin Menu" (and if you like, "Admin Menu Toolbar"

Or, with Drush -

drush dl admin_menu && drush -y dis toolbar && drush -y en admin_menu_toolbar

(Enabling Admin Menu Toolbar style implicitly enables Admin Menu also.)


In Drupal Commerce, what is the difference from a product, product type, and product display?

Okay after reading a bit and messing around with the commerce module, its a bit more clear now. Don't even try to just read the documentation without clicking around and testing Drupal commerce as its very confusing if your not messing with the site. It's best to install just the Drupal Commerce module and not the Commerce Kickstart module so you can get a CORE knowledge of how it works from the ground up. Kickstart has too many other modules installed and will make it confusing of how thins are built.

Hopefully I can explain it a bit easier than the documentation. When starting out with Drupal Commerce and your coming from Ubercart, its good to know that there are no Options or Attributes as a configuration option as you have it in Ubercart. The idea of how Drupal Commerce was constructed was that every type of options within an attribute is its own product. (This is something I had to get my brain used to.)

Let's say I am selling T-shirts and I have SIZE and COLOR as an attribute. Now I have 5 difference sizes (X-Small, Small, Medium, Large, X-Large) and have 5 different COLORS (Red, Blue, White, Black, Green). YES, I know its a crap load of products to deal with compared to Ubercart which would have been only ONE and you just set attributes and options for it!

In Commerce, a product page is constructed in this way:

Product Type > Product > Product Display

Product Type
You can think of Product Type as you creating a new Content Type under structure, but it just has its own section for it. Which is why this is called an Entity! Structure > Content Type is a type of Entity. And Product Type is just another Entity. Hence the different page to set this up.

Product
You create a product out of a product type. Same as if you create a new content type called "Basic Page", you would create a new page when you click on basic page under structre.

Product Display
Now here's the tricky part to wrap your head around. When you create a product, there is no page where you can view it as its not a "DISPLAY". Its just a record in your site saying you have this product, but you cant view it. Now you create "PRODUCT DISPLAYS" via the regular structure menu as if you were creating a new content type. You can call it whatever. You know what, just use the default "Basic Page" and add a new field to it. That new field will have to be a type of "Product Reference", which you select under the type option when you add new fields. Once you add a product reference option. Your BASIC PAGE is now considered a "PRODUCT DISPLAY".  When you first install commerce without anything else, you will have to make your own product display, so don't expect to see a product display option under structure. Once that is done, create a new BASIC PAGE and add a few products you already made and it will pop up with the add to cart forms and stuff.

I hope this was clear, if not let me know and I'll try to be a bit more precise.


Two Drush bam-backup errors: Command not Found & Could not find a Drupal setting.php file at

Where is the settings.php file for your Drupal installation?

The problem Drush is having is that it cannot figure out where your settings.php file is.  By default, Drush only looks in sites/default.  There are a few ways that you can select the site you want if it is not in sites/default.  One is to cd to the directory that contains the settings.php file, then run your command.

cd /path/to/drupal/sites/mysite
drush status

The other way is to specify the site you mean via the --uri parameter:

drush --root=/path/to/drupal --uri=mysite.com status

Once the status command works per the above advice, try calling bam-backup again.


Warning: Cannot use a scalar value as an array in _block_get_renderable_array() on hook_block_info / hook_block_view

I changed the _banner_get_bannert() code to the following one:

function _bannert_get_bannert() {
    return "
push me
";
}

The error is gone, and the block is created.


How do I send verification mail from my drupal custom module?

I am not sure about what kind of verification emails you are sending, though I believe if you peep inside drupal core user module you can get hold of function which does the same,as for user registration process we have email verification option also.

A very simple straight custom way might go in the following way

How you will be generating the verification code?

while sending the email create a link something like www.mydomain.com/email-verification/%random_string%

Create a custom table with column as email,random_string,verified
once you have generated it, make a db query to insert the link you created a point back against the email user entered and set verified to 0 in the custom table.
send the email
In your custom module implement hook_menu() with menu entry fir "email-verification" .
In the page callback using wild card check if the random_string exists in you custom table, if so set verified to 1

Not exact but close to what you may need.

Update:

global $base_url;
$random_string = substr(str_shuffle(md5(time())),0,10);
// Link
$email_link = $base_url . "/email-verification/" . $random_string;


Build out a complete main nav menu for a module - not just adding one menu link

I've decided to go with the default_content technique in which it is possible to save off the menu items to a 'custom_module' then reload them into a new instance.


How to use tokens in data selectors in Rules and how to get autocomplete to work?

Note: This is not an accurate answer of this problem, as by this time, the Rules module is still in development. This is what I did to solve my problem:

Download PHP Module, as it is removed from Drupal core and is a contrib module now. In Rules, create a new condition known as "PHP execute" and write a php segment which checks user role.

This is probably the easiest way around this problem and will work fine if you are trying to fiddle around. But for production site, I won't recommend this.


Ensure the i18n_menu module is enabled and the menu to which you're adding links is configured to "Translate and Localize" on the Menu edit page:

For example, the setting for the main menu would be found at the following url:

/admin/structure/menu/manage/main-menu/edit

The configuration option looks like this:


Automatically translate double field select value, but not free text

Here is a simple workaround:

/**
 * Implements hook_field_widget_form_alter().
 */
function HOOK_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['instance']['widget']['type'] == 'select_&_textfield') {
    foreach ($element['first']['#options'] as $key => $label) {
      $element['first']['#options'][$key] = t($label);
    }
  }
}


I haven't found a way to do it in a THEME.theme file but I found a way to do it in a MODULE.MODULE file. The magic hook is MODULE_views_post_execute:

function feature_carrousel_views_post_execute(\Drupal\views\ViewExecutable $viewExecutable){
  /** @var \Drupal\views\Entity\View $view */
  $view = $viewExecutable->storage;
  if($view->id() == 'carrousel'){
    /** @var \Drupal\views\ResultRow $row */
    foreach($viewExecutable->result as $key => $row){
      $nid = $row->nid;
      /** @var \Drupal\node\NodeInterface $node */
      $node = \Drupal\node\Entity\Node::load($nid);
      if($node) {
        $country_filter = $node->get("field_country_filter")->getValue();
        $country_filter_tid = (reset($country_filter))['target_id'];
        /** @var \Drupal\taxonomy\Entity\Term $term */
        $term = \Drupal\taxonomy\Entity\Term::load($country_filter_tid);
        $name = $term->getName();
        $countryCode = getUserCountry();

        if(strtolower($name) != 'all' && strtolower($name) != strtolower($countryCode)) {
          unset($viewExecutable->result[$key]);
          $viewExecutable->result = array_values($viewExecutable->result);
        }

      }
    }
  }
}

Cheers


I found out what was wrong. There was a missing JS file. Installed the missing JS file and now it is working.


What's a good way to split a 'item_list' into two columns?

You can do this just using CSS by giving the list items a width and floating left:

.list-class li { width: 50%; float: left; }

You might need to adjust the width to a static number depending on the padding you have on the <li>s.


It's too late to change the field object, because the field is already prepared for rendering. You have to find the field value inside of the render array, for example in #markup, and change it there. Where you find the value depends how your field display is configured in the view mode.

  While possible, there's often a better way. You could make your own
  formatter that returns the structure that you want. #text is a
  formatted text field, you could make a filter that transforms the text
  the way you want. Depends on what you want to do exactly.

(Comment from @Berdir)

See the drupal docs how to create a custom field formatter:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter


return message after hook_form_submit without Ajax

The form API and message system are not the same thing, even though there are helper functions in the FAPI to produce messages - you don't return a form with a message, you set a message when it's appropriate to do so. That might be when the form is being built, when it's being validated, after it's been submitted, and so on.

Generally speaking, if you're setting a validation error, use form_set_error() in a validate callback:

function MYMODULE_form_validate(&$form, &$form_state) {
  if (something_wrong_with($form_state['values']['foo'])) {
    form_set_error('foo', 'Run away, bad things happening');
  }
}

If you want a confirmation message on form submission, use drupal_set_message() in a submit callback:

function MYMODULE_form_submit($form, &$form_state) {
  if ($form_state['values']['foo'] == 'bar') {
    drupal_set_message(t('You chose: %foo', array('%foo' => $form_state['values']['foo'])));
  }
}

There's no point returning anything from a form submit callback - it will be ignored. If you want to rebuild the same form again after submission, use:

$form_state['rebuild'] = TRUE;

It may or may not be necessary depending on your final goal.


Additional Configuration to disable anonymous session cookies?

Make sure the $cookie_domain is set properly in settings.php, often if it's not set to the correct domain, particularly in proxy situations, you'll see inconsistent login behaviour.


Drupal for Firebug does not work in FF> Works fine in Chrome

There are some issues with the Drupal for Firebug plugin depending on which version of Firefox/Firebug/DrupalForFirebug you are running.  See the following issue on DO Extension breaks with version 14 of Firefox

It works for me on:

Firefox - 18.0.2
Firebug - 1.11.2
Drupal for Firebug Module - 7.x-1.4
Drupal for Firebug Firefox Plugin - 2.2


Multilingual Paragraphs fields are not present in node content

Turned out, that there was a conflict with the field_layout module. Just uninstalled it and voilá!


Composer killed when installing a module

You ran out of memory. This happens all the time with Composer.
Composer is a huge memory hog, especially when used with Drupal because of all the external interdependencies. And Drupal's requirements continue to grow with every new release, so the memory needed to use Composer with Drupal continues to grow. 4Gb of available memory should be enough, currently, but 2Gb is not enough in my experience. I find this problem can be avoided if you configure your system with sufficient swap space (2x physical memory is usually sufficient). This is for a development system of course - you won't be using Composer to install modules like that on a production system, you should be using a .lock file instead, so Composer's memory requirement will be much smaller.


How do I display real names instead of usernames for referenced users?

As with most problems this one too can be solved in more than one way.

Probably the easiest, common, and "most Drupal" way is through using View modes.

View modes

View modes are different ways of displaying entity content, depending on the context. Don't confuse them with Views module that is used for building lists of entities, they are completely different things.

An example of a View mode: you want the user profile page to show all user user fields, but in a lot of other places on the site you need the username and their geo-location, so you keep the Default User View mode for profiles, and create a new View mode where you only enable the username and geofield. Then activate the new user view mode in all places where you need to show the user with their geo-info.

In your case you have a User Reference field in Content Views and you want to change how the user info from that field is presented:

Create a new User View mode under People Manage display (/admin/config/people/accounts/display) > Custom display settings
Enable the newly created View mode. After you enable it and Save the page will reaload and a new Drupal tab will appear named after your new View mode.
Visit the page of the newly created View mode (click on that tab) and adjust which user fields you want to show under that View. In your case that might be firstName and lastName, disable all others by dragging them down to the Disabled list (and Save).
Edit your Content Views (this is now the list of content you mention in your question, not the View modes), edit the User reference field and change the View mode option to the one you created in step 1.

Now your User reference field will show only the user fields you have enabled in the View mode on People account configuration.

You can use this View mode in other places too where you want any User data to display only as the Display names.

Through Views

Alternatively, you can achieve the same result with Contextual filters within a Views Block Display to show only users referenced by the article you're currently viewing, and only showing that Block on the pages of that specific Content Type.


I wonder how you embed the View in your site.
(I'm aware of views_embed_view() or any other PHP method. We good people don't even enable the PHP module do we?)

Block caching. Views exposed the Views to the blocks system, so they can cached, altered, and just about anything regarding blocks can be done.
If you want to have multiple blocks/displays out of the same View, you do have to create blocks. More views = more headache.


According to this the problem, was that a div container pushed the menu away.

The old and wrong container was:

It could be fixed by adding additional bootstrap classes:


What is this operator:content value mean?

The operator shown in the screenshot is Contains. Since that is a filter for Content: title, it will show nodes whose titles contain the string you put in the Value field.

To make a summary, that view will show nodes, where:

The node is published
The content type is Webform
The node title contains style 2


You can try LoginToboggan

You will get a screen like this in example.com/admin/config/system/logintoboggan


How to execute some js code after click on exposed filter AJAX enabled submit?

You can use the ajaxStart() function, to execute something before  Ajax request begins:

 Drupal.behaviors.<themename/modulename> = {
  attach: function (context, settings) {
    $('#edit-submit-phrases').on('click', function() {
      $( document ).ajaxStart(function() {
        alert('check');
      });
    });
  }
};


Drupal Content Admins for specific Language

In Drupal 8 its part of the core but for Drupal 7 try using Administration Language.


I will get so downvoted for this but are you sure this is the last thing you need to make your site awesome? You are wasting your time on microoptimization.


As coded in autocomplete.js file inside misc folder, popup is wrapped inside

You can able to set width using above id. If you want to disable hide popup option for time being to style the popup results, then try commenting lines shown below in autocomplete.js file inside misc folder of your drupal root.

/**
 * Hides the autocomplete suggestions.
 */
Drupal.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed.
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = $(this.selected).data('autocompleteValue');
  }
  // Hide popup.
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function () { $(popup).remove(); });
  }
  this.selected = false;
  $(this.ariaLive).empty();
};

NOTE: Remove commented code once styling is done. Clear the cache after making javascript changes and make sure changes are reflected in autocomplete.js file using firebug. Clear browser cache.

Hope it helps :-)


.bash_profile has to be resourced every time

You need to put these commands in your ~/.bashrc file, which is sourced every time a new shell is started.

You might also want to try the new drush init command, which should do this setup for you.  Be sure that you are using Drush 8.0.1 or later.


You need to define a Behat step for it. A possible way would be to define a method to be executed before creating a node (labelled with @beforeNodeCreate), to upload the file first and then to attach its fid to the appropriate file field of the node or term.

A possible way of doing it (for Drupal 8) is explained in detail here: https://webscope.co.nz/testing-image-and-file-fields-with-behat


Domain administrator role that can only see users of that domain

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

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

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

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


I am looking for a friend's list  for the Organic Groups module

You might give User Relationships module a try.

Basically, you can create one way and two way relationships, such as friends, manager.


Put all your theme images in a directory in your theme; let's call it img.

Then you can load them like so:

<img src="<?php echo drupal_get_path('theme', 'THEME_NAME'); ?>/img/flags.png">

Hope this helps.

(More info at drupal_get_path();)


Let users download entire folders (zip first) or individual files?

I suspect that the functionality that you are looking for exist in the elFinder file manager module. It allows downloading individual files and whole folders after compressing them first.

You can manage the roles that you allow to download specific files with the native drupal permission system. Just make sure that you don't give your users access to sensitive files in drupal installation.


Is it normal that Organic Groups group creator is not automatically "Administrator member"?

I should have seen this myself.
In fact the answer is in the slightly obscure "OG Settings" (Config > Organic Groups > OG Settings).

In this there is an option called "Group Manager default roles" which is applied to every OG content type. This allows you to "Select the role(s) a group manager will be granted upon creating a new group"

Problem sorted!


Cannot set form #default_value when altering Views Exposed Filter forms

Try overriding the whole element, like this:

...
if ($form_id == 'views_exposed_form') {
    $options = array(
      'All' => t('All'),
      '$' => '$',
      '€' => '€',
      'тг' => 'тг',
    );

  $form['field_price_second'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => '$',
    '#size' => 1,
    '#validated' => TRUE,
  );

    dpm($form);
  }
 ....


What "access argument" or permission-string to use for a custom module?

If you set a custom permission for your module you get finer control over who can configure your module's features. If your module is strictly related to Taxonomy you may stick to Administer taxonomy. You may find this link useful for your decision.


If you are familiar with drupal module development, I would recommend to write custom code. You may have 3 user roles - editor, client and subscriber. You can create user fields at admin/config/people/accounts/fields, but you cannot have separate set of fields by role. You can manage (hide/show) those fields upon user role selection from your custom module.

Please check this answer.


Prevent node from being saved in hook_node_presave

How do i prevent saving that node?

If you want to prevent that the node is saved in a presave method or hook you have to throw an exception:

throw new \Exception(t('Fields are not unique!'));

More user friendly would be to check this in the form first and give the user a chance to correct the input before you throw an exception.

Double checking this in presave is still a good idea to make sure, that no incorrect node content gets saved, no matter which form, Rest API or code is used. If someone gets past the first level of checks in the form you have no other option than to throw an exception.

Edit:

In case an exception is raised, you can replace the default 500 response with a custom error handling in an exception subscriber, see Handle database connection exception via custom handler


Is there a way to show a page dynamically when hovering on it's link?

Beauty Tips is a drupal module and a jQuery plugin that will allow you to display content tooltip style via hover, click or a range of other events.

It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.

Most importantly, it allows developers to add their own custom beautytips popups to their site without having to delve into jQuery.

You can use this module and fetch the data which do you want to display in tool tip.