How do I define the default cache and cache settings programmically in a Kernel test?

Take a look the Memcache module.
The module has tests, and seems you need write

  protected function setUp() {
    $this->config = [
      'memcache' => [
        'servers' => ['127.0.0.2:12345' => 'default'],
        'bin' => ['default' => 'default'],
      ],
      'hash_salt' => $this->randomMachineName(),
    ];
    $settings = new Settings($this->config);
    $this->settings = new MemcacheSettings($settings);
  }


Integrating Drupal into an existing site to manage comments

Though this is an old question, and it probably depends on what your project is using other than Drupal, from what I hear there are some decent "hybrid" CMS options out there.
You can combine Drupal with NodeJS or AngularJS.
Since you said you don't want Drupal for the design, that is called "headless/decoupled Drupal".
Here is some more information: Headless Drupal: The What, Why and How


Need filter on value of a field in a specific node of different content type in Views

I don't know of a way to do this all in the interface, but if you add a contextual filter in the view for the topic field on the article content type, you can programmatically set the contextual argument in hook_views_pre_view.

First, load your pick_topic node like:

\Drupal::service('entity_type.manager')->getStorage('node')->load(PICK_TOPIC_NID);

Then load the field value. See How do I access a field value for an entity (e.g. node) object?

Then set the view argument.

function MY_MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'MY_VIEW_ID' && $view->current_display == 'MY_VIEW_DISPLAY_ID') {
    // Load your pick topic node.
    // Load your pick topic field value.
    // Set the view argument, term id.
    args[] = $my_pick_topic_field_value_tid;
  }
}


There is a page at admin/reports/fields that lists the field name (the machine name), the field type and which module it came from, along with all of the bundles (content types, in the case of nodes) that use that field.


It was a cookie issue. When I deleted all the cookies from browser it was fine.


The code you are using is not outputting any value; the PHP code you are writing is supposed to output 1 if the actions associated to the condition need to be executed, and 0 when they don't need to be executed.

The correct condition is the following one:

<?php echo ([node:author-uid] != 1); ?>

Alternatively, you can use the following one:

<?php echo ($author->uid != 1); ?>

Verify the token you are using is the correct one; the one I see with Drupal 6 is [node:author-uid].
The operator != already returns a boolean value; there is no need to convert it to a boolean, as you do with the code you have written. The "Truth value" field accepts also 1 and 0 as values; there is no need to convert a value to a boolean.

The description reported for "PHP Evaluation" is the following one:

  PHP code inside of <?php ?> delimiters will be evaluated and replaced by its output. E.g. <? echo 1+1; ?> will be replaced by 2.

To notice that the user with ID equal to 1 is a particular user to whom Drupal always give any permission defined from any module; this is the only user account that is treaded in this particular way. Administrator users don't have their user ID always equal to 1; if you are checking the user ID to verify if the user is an administration user, then you are doing it wrong. In Drupal, you usually check the permissions the user has with user_access().


Migration issue: Drupal markup isn't rendered on CiviCRM pages

Ah, I think I've seen this before, did you by chance mess with your CiviCRM settings file?

Double-check your CIVICRM_UF setting, Civi might be tripping up if it thinks the CMS is something other than what it actually is.

For Drupal 6 you want CIVICRM_UF = 'Drupal6'


How to mass copy the title of each node to a taxonomy term?

You could use a combination of the Rules module and the VBO module to create a custom rule component, which you then use as a custom VBO action.

For way more details on this combination, have a look at my answer to "How to bulk update select list fields?".

In your case, the custom Rules Component should look pretty similar to this:

{ "rules_set_an_initial_value_for_a_term_field" : {
    "LABEL" : "Set an initial value for a term field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_yourfield" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-yourfield" ], "value" : "HereGoesTheTitle" } }
    ]
  }
}

Some more details to further explain the above example:

adapt the machinename of field_yourfield to the machine name for your taxonomy term field.
replace the (hardcoded) HereGoesTheTitle value in the Rules Action by the token like node:title (which for sure wil be available).
I'm assuming your taxonomy term is a single value field, if it is a multi value field, then replace the action with a similar one to "Add an item to a list" (related to your multi value field).

PS: no need at all for any custom PHP code when using this approach.


Module config page linked on Management Toolbar

It is because you have added a MENU_NORMAL_ITEM under the admin menu, so it will automatically put it in the admin toolbar (that is also the default so if you exclude that parameter it will also be a menu normal item).

If you change it to MENU_CALLBACK, that will create the link between that url and your page callback, but it will not create an item in the menu.

See hook_menu() for all the menu item types.


Is it possible to use Drupal with CouchDB?

There are a few things to keep in mind.

Even though Drupal support multiple databases (mainly MySQL,  PostgreSQL, and now anything supported by PDO), this is only true of the core files.  There are contributed modules that use database specific syntax and/or functions.  In addition, there are some functions that show subtle differences when run on different database servers (for example, see Does db_affected_rows() works well with PostgreSQL?).

The modules for non-SQL databases are primarily for offloading some core tables from the primary database. You still need an SQL database when using these.

Personally, I don't mess around with any of these other databases. I may start experimenting with MongoDB, but I can't really use it with client's projects as its support on commodity hosting is limited. Setting it up for them would eat into their budgets, and clients would rather have me do Drupal work than IT work.


What if you rewrite the title field of your node results with HTML so that each title links to the view you have created? Your view already displays all nodes with category "issue".

Edit:
To link your titles to the view, I assume that in your view fields you are able to see a filed that looks like "Content: Title (Title)". Click on the field and on the field edit for visit the section "Rewrite results" and check "Output this field as link". In the "Link path" field, fill in the path to your view. I think this will work

Now for your blocks you can configure them to appear only when your view is being displayed, e.g.

Configure block
Show block on specific pages:
Check "Only the listed pages":
In the field below enter "path_to_your_view/*"


Sounds like you should enable template file suggestions in your site, this will help you to identify the right target name for a template to override the core files. You can read more about this feature in the docs at https://www.drupal.org/docs/8/theming/twig/locating-template-files-with-debugging


URL alias with taxonomy term (multiple vocabularies). How do I choose one?

[term] -- Name of top taxonomy term

Top taxonomy term is the term with the lowest weight from the vocabulary with the lowest weight.

Reorder vocabularies at admin/content/taxonomy, move the desired one to the top and you should be good. :-)


Is there a module to provide node access based on Ip address?

The Restrict IP  module is what you're looking for.

This module allows administrators to restrict access to the site to an administrator defined set of IP addresses.
Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page with the message "Your address is not in the list of allowed IP addresses". No blocks will be rendered, and no javascript will be added to the page. This will happen for any and all pages these users try to access.


Naming conventions for Drupal permissions

AFAIK there's no official recommendations.

Given that all permissions share the same namespace it's a good idea to avoid generic names. You can include the name of the module that defines the permissions to minimize collision risk.


Can I add and edit a custom entity from the same URL?

You can create a controller in its simplest form.

In my_module.routing.yml :

my_module.profile_controller_profile:
  path: '/user/{user}/my-profile'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProfileController::profile'
    _title: 'Profile'
  requirements:
    _permission: 'edit profile'
    user: \d+

In ProfileController.php :

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\my_module\Entity\Profile;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ProfileController.
 */
class ProfileController extends ControllerBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ProfileController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    EntityFormBuilderInterface $entity_form_builder
  ) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFormBuilder = $entity_form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('entity.form_builder')
    );
  }

  /**
   * @param \Drupal\user\Entity\User $user
   *
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function profile(User $user) {
    $profiles = $this->entityTypeManager->getStorage('profile')->loadByProperties(
      ['user_id' => $user->id()]
    );
    if ($profiles) {
      $profile = array_pop($profiles);
      $action = 'edit';
    } else {
      $profile = Profile::create([
        'user_id' => $user->id(),
      ]);
      $action = 'add';
    }
    return $this->entityFormBuilder->getForm($profile, $action);
  }

}

You can choose to redirect after submitting the form, etc.


Display nodes that reference the same node than current page

It can be tricky to orient yourself around this, but it is a fairly common request to list sibling nodes according to whatever criteria (usually Taxonomy and Entity references).

The solution involving Entity references is to use two Relationships, one pointing to the common node (C), then another to point to the nodes that reference it (A) and then a Contextual filter that feeds the Views context on what node you're currently on (B).

Create Views listing your content A
Add a Relationship Content referenced from field_ref_C
Add another Relationship Content using field_ref_C, and set it to use the Relationship from the previous step field_ref_C: Content
Add a Contextual filter ID (from Content Category) and set it to use the second Relationship (field_ref_C the one from the previous step) with these options:
When the filter value is NOT available:
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria (optional)
Content
[your appropriate types - B]
Add another Contextual filter ID  but this time Do not use a Relationship:
When the filter value is NOT available:
Provide default value
Content ID from URL
More: Exclude

This will exclude the node you're currently viewing from the list.

If you want to check the output in Views Preview at this point enter the same node ID both times, for example to see what the block would output on node 14 enter 14/14.

The first argument is taking the current node of type B and navigating through the connections, to the country C and back to content A you want to show, the second argument is excluding the current node from the list.
Place your block in a region shown only on content B, don't forget to set the option Node from URL on block settings.


To make sure you have the content types that you want in your sitemap, you can enable xmlsitemap_node.  After enabling, visit each content types configuration page and select "Include" under the xmlsitemap tab.

After setting each content type, you can check the Included/Excluded status for all content types under the xmlsitemap module config page.

Once that is complete, you can run cron manually to regenerate the sitemap links.  Check www.yoursite.com/sitemap.xml to view the newly generated sitemap.


What is the procedure for deleting a project in drupal.org?

If your project contains code usually it is not deleted. In that case, you can select as Project classification Unsupported and as a Development status Obsolete.

You can always create a post in the Drupal.org webmasters issue queue explaining your situation and requesting the project deletion.

But I can tell you that if you have people using your module, they will not delete the project.


How to make User Picture a required field?

You can do it by using these modules :

Register with Picture

  Install and enable the module
  Navigate to: Configuration -> Account Settings. (admin/config/people/accounts)
  Check Enable user pictures if it isn't checked already.
  Confirm Enable pictures on registration is checked.
  Use the Registration Picture Field Weight field to adjust the display order of the picture field on the registration form. It can be
  a negative or positive number.

user picture field

  1, Add a image field to user, for example "field_user_avatar"

  2,config this field,and make it show on user register form.

  3,install this module, navigate to
  "admin/config/people/user_picture_field", here you can config the
  "Machine name of source field that used as user picture"

  When user register an account, he/she upload an image through image
  field "field_user_avatar", this image will be used as user's
  picture(avatar).


How to use the Menu Badges to show the number of recieved messages via Privatemsg?

After peeking into the database, it appears the path /messages/received does not exist. This is probably due to the fact that the inbox being the first tab (default tab,) the path defaults to /messages. This path is also the path of the main menu tab. The Menu Badge module does not have an uninstall file, therefore uninstalling it does not clear up the database.

The work around I used is by putting the badge on the All Messages tab (/messages/list) The count of unread messages is the same as with the Inbox tab. Then, I used a little css to move the badge 222px to the left (position: relative) so that it falls on the Inbox tab instead.

It's like using scotch tape, but it works. :)


Programmatically node update while saving node

You can use hook_entity_presave

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

    if ($entity->getEntityTypeId()=='node'){
        $value="099545";
        $entity->set('name_field', $value);
    }
}


Views autocomplete with aggregation (and panels)

So the way to address this is actually easy, so sorry for having posted it.

In case anyone else is having this issue...in the panel, instead of using the exposed filters for the view with aggregation, I used the exposed filters for the view that just provided a list of Funding instances.

Then, in the settings for the view with aggregation there is no need to use autocomplete (just use Contains) - because I'm not displaying this exposed filter anymore.


Just adding an extra module with a similarly-named function won't guarantee that gigya will call that function. If Gigya's module has hooks (Google doesn't seem to be able to tell me at a glance), then that's the source for how to do what you're trying to do.

Also, you never need to put your .module file in files[]. That's only for files in the module that declare classes.


Is there a way to provide the login provision for anonymous user when anonymous commenting is enabled?

Since you want to edit something in the contact form, you can use the same  hook_form_FORM_ID_alter of my previous answer to alter the comment_form.

As you can see in the comment form all author details are in an array $form['author']. So you need to add an item to this array and move it to the top.

function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  // Any code you already have here

  // Check if the user was not yet logged in. (It would be useless to show this otherwise.)
  if (!user_is_logged_in()) {

    $form['author']['login_url'] = array(
      '#type' => 'markup',
      '#markup' => t('Login or create account', array('@login' => url('user/login'), '@create' => url('user/register'))),
      '#weight' => -10, // Play with this value to control the height.
    );
  }
}


Limited access to 'Edit' Commerce Order & limit line items to only 1 type

While it is possible for you to add those fields to the order, you should really create a new review content type and then use those for your reviews and then use an entity reference to connect the review content to the order. In the future, if you did want to allow line items to have reviews, you could then just add another entity reference field to the line items and you can reuse all of the UX you've built for the main review form for anywhere else.

Furthermore, by using a reference, you're not limiting yourself to a particular type of form. If you ever wanted to differentiate between certain types of services and provide different review criteria, you can much more easily do that with new content types + entity reference.

Brief overview of steps:

Create a new review content type with your fields and fivestar info.
Create an entity reference field on your Order. I believe you can use Entity connect to have it show a "create link" if no reference exists.
If that doesn't work, you can use Views to make it so that a user can only connect the entityreference field to orders that they own.


In views, add class depending on the user input in a checkbox.

Create your boolean field (my case the name is field_no_overlay),  The checkbox should have the values for the classes you want to use and apply to your field.

In the views, rewrite your value .
Create the style for each class.


OG Subgroups - call function _og_subgroups_get_inherited_users

I was able to solve this by creating a custom og_subgroups.rules.inc file. For details of this see my answer in: Email all Organic Group members when a subgroup is created

The line in question above needed to be:

$inherited_users = _og_subgroups_get_inherited_users("node", $nid);


Share and update the structure (content types, vocabularies/tags, views, rules, …) for several sites

We use the domain access module, https://drupal.org/project/domain

Everything is or can be shared on the multiple sites ... we choose to have different themes for each domain and we only have a few nodes that are common to multiple sites, most of our nodes are only on one site, but the content types and taxonomies and blocks and views are shared.

There are some current domain views filters that allow exactly the same view to be used on multiple sites but show different content on each.

It is working really well for us, our only issues are that

There are some reports that combine all domains when we would like to have them separate (e.g. ubercart)
Users have to login to each site separately
All relative path links are rewritten to the correct domain automatically but if someone for some reason requests a path on the wrong domain they are not redirected and they see an access denied message.


Node Edit Form and twig template - confusion on where some values come from

When you xdebug $variables in a preprocess hook

function mymodule/mytheme_preprocess_node_edit_form(&$variables) {

}

you find $variables['form']['actions'] and the other form elements. You can also install a module to set a breakpoint in the twig template directly, see https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

What you now have is probably the form build $form in a different place.


Services 3: How to retrieve the current logged in user ID

To do this you can use the system resource "connect".  Enable that resource:

to go admin/structure/services/list/serp/resources
expand "system"
check "connect" Hit save

Then, you post (posting nothing) to /system/connect and it returns the current user info and session id.


You can't render an entity like a field and vice versa. These are two entirely different things. However if you in a field loaded a related entity and rendered as a way of rendering the field, there could be some common ground.

That being said, your reason for asking this question doesn't really make sense. If you have a field on an entity and want to render the field. No matter how you render it, (through views, by viewing the entity etc.) you will have to use a field formatter to render that field.

Also regarding entities there is no common way of rendering them. The module defining them can render them any way it would like to and it's up to that module to make a way to render the entity. That being said, the entity API module does create some apis for doing this in a generic way, but that is not a part of Drupal 7 core.


The placeholders are not supposed to be substituted in the database.

This is because the watchdog() function can be called from anywhere, for any user, with any language.
Mid you call t() function, which usually does the placeholder substitutions and translation, that function used the current language to translate to. Now, if you call watchdog() to log an error for user A, whose language is de, the message should not be saved to the database as the de-translated string. That is why the english untranslated strong is stored.

When an administrator views the log (From Admin -> Reports -> Recent log items), Drupal does the translation call (t()) at that very moment. All entries will then be translated to the language the current user has configured.


This can be changed on the Detection and selection page of the Language settings: /admin/config/regional/language/detection.
This page lists the detection methods, and by default, Drupal 8/9 prioritizes the path.
But, here you have two options.
Option 1: You can enable User (Follow the user's language preference) and then drag User above Path, which should give the admin pages in the admin language. This is simple, but the drawback to this approach is that users on the site will see content based on the language set in their account, not the site, which may not be what you want.
Option 2: You can enabled Account administration pages and then drag Account administration pages above Path.  This will create a new setting on the user account edit page to set the admin language, so you may have to check all the admin accounts and set the language appropriately.  This approach is more complex than the first, but limits the change to admin content only, which is probably what you want.


How do I use dpm() or kint() to debug a block plugin I created?

dpm() definitely works within a custom block; I just tested. Since it calls a service, you may need to clear your cache before it shows up, for example with the command line with drupal cache:rebuild all or drush cr.

To test if the service is available, you could use this code.

dump( \Drupal::service('devel.dumper')); die();

Another thing to consider is that blocks are cached in Drupal 8 by default.  Make sure your build() is actually executing. You may want to turn off the rendering cache while developing, in settings.php or settings.local.php.

$settings['cache']['bins']['render'] = 'cache.backend.null';


How to get a field value of multiple nodes?

You can use field_attach_load() which will load the fields for a group of entities. You can also pass in the field_id value so it doesn't load unnecessary fields. I benchmarked field_attach_load() against entity_load() (which is what node_load_multiple will call) and the former was approximately ten times faster.

Here is an example:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'post')
  ->propertyCondition('status', 1);
$result = $query->execute();

if (isset($result['node'])) {
  // field_attach_load() requires entities to be passed on it with the bundle
  // and the ID instead of just IDs. We need to add these values to the result
  // of EntityFieldQuery()
  foreach ($result['node'] as &$node) {
    $node->bundle = $node->type;
    $node->id = $node->nid;
  }
  field_attach_load('node', $result['node'], FIELD_LOAD_CURRENT, array('field_id' => 'body'));
}


OG: How to import 2 related nodes from CSV files using Migrate module?

Okay so I'm assuming that you haven't used Migrate before. If you'd like some background reading take a look at the slides for the presentation I'll be giving at DrupalCon in Denver: http://denver2012.drupal.org/sites/default/files/slides/Migrate_0.pdf It should help you understand some of the concepts.

One thing that's important to point out is that you'll need two migrations:

Using (a) and MigrateSourceCSV as a source and—assuming the groups will be nodes—MigrateDestinationNode as a destination.
Using (b) and MigrateSourceCSV as a source and MigrateDestinationOGMembership (as you noted part of Migrate Extras) as a destination.

The CSV files are actually really easy to use as a source. You can see an example of it in the Migrate docs: http://drupal.org/node/1152158

In your case you could setup the source for (a) with:

// The definition of the columns. Keys are integers, values are an
// array of field name then description.
$columns = array(
  0 => array('gid', 'Id'),
  1 => array('group_title', 'Title'),
  2 => array('group_body', 'Body'),
  3 => array('group_admin', 'Admin'),
);

// Instantiate the class using the path to the CSV file and the columns.
$this->source = new MigrateSourceCSV('path/to/a.csv', $columns);

You'll also need to know something about your source when you setup the Map because it needs to create a field to store the source ids in... since gid's are basically nid's you can just cheat and use that source's schema definition:

$this->map = new MigrateSQLMap($this->machineName,
  MigrateDestinationNode::getKeySchema(),
  MigrateDestinationNode::getKeySchema()
);


You can try to write a custom module that implements hook_views_data_alter() to programmatically define a relationship. See also the example code for hook_views_data().


How to prevent multiple votes in polls of the rate module?

The rate module hasn't built support for this. If you wanted to do this, your best option would be to

Deny duplicate votes, it's up to you to decide how, but you could check the voting api table which stores the IP addresses of all who have voted then use rate_vote_alter hook. Doing it this way would make it impossible to change the vote.
The other option is to use rate_vote_alter to stop the rate module from saving votes and do it yourself with votingapi_set_votes. That would make it possible to set criterias for which (old) votes should be deleted.

This could have been done easier if the rate module was built more flexible. You could consider making an issue and a patch for the rate module, to add this feature for others to use.

Update:
The alter hook is not defined anywhere, but done with drupal_alter('rate_vote', $votes, $context). This means you should be able to do:

function my_module_rate_vote_alter(&$votes, $context) {
  ..
}


Drupal commerce change quantity textfield in cart view to selectbox

<?php
/**
 * Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
   if (isset($form['quantity']) && ($form['quantity']['#type'] == 'textfield')) {
     $form['quantity']['#type'] = 'select';
     $form['quantity']['#options'] = drupal_map_assoc(range(1,10));
     $form['quantity']'#default_value' => 1,
   }
 }
}

?>


How to add content filter into a content page(not in a view)?

You probably want to add the Panels module.  There's an excellent series of screencasts on Panels/Page Manager at NodeOne.

Basically, you can use Panels and Page Manager to override paths on your site.  For example, you can override all taxonomy terms.  You can break this down however you like, such as "all taxonomy terms," "all taxonomy terms from a specific category," "one specific taxonomy term," "users with this role on a taxonomy term in this vocabulary," etc.  Then you can create Variants, which are page layouts that dictate how the content should be formatted.

Using Panels, you can take the views you make and stick them wherever you like on the site.  It will certainly take some time to learn how to set this up, but learning how views and panels work together will allow you to create very complicated sites with little duplication and certainly no "hundreds of pages" created manually.


Some HTML tags are not displaying in body(ckeditor) of content type

Have a look at your configured input format settings. It is likely the input format or a specific filter are stripping HTML tags out.


How to insert table view inside another view?

You should be able to put services view block reference into your members view block for example into Header / Footer. Then by overriding template for this view type view-view--<views_machine_name> you can easily add Bootstrap classes and wrap each table into specific container / wrapper.

In your main view click on button Add at Header section. Add Rendered entity - block and type in your second block block_machine_name (it means your second block needs to be added to some region with specific machine name).


Drupal core search result pages do not listen to URL Parameters or HTTP POST content.
Instead, it takes the third part from the search/node/QUERY URL format, and shows results for QUERY.

This unfortunately makes it not possible to use a standard HTML form created without Drupal's form API. There are of course workarounds.

Basically what we try to do is route the user's search query to the search/node path. I can see you are using Angular. You might be able to make it send the user to the proper path.

Alternately, you can make Drupal listen to URL parameters or the HTTP post request content.

https://www.drupal.org/project/query_parameters_to_url - this module I just found (and did not try personally) appears to rewrite URL parameters to a path query. I'm not sure this will work for search forms though.

If not, you will have to create a custom module, and take over the search result page callback. Then, it can show appropriate results or call the old page callback function with the search query taken from alternative sources.


Migrating disqus comments from non drupal site to drupal 7 site

Disqus offers variety of migration tools depending on your needs - https://help.disqus.com/customer/en/portal/articles/286778-migration-tools. I performed migration of comment threads from static website to Drupal 7 recently. Main change to the pages with comments was new clean URLs, so in my case all I needed to do is to use URL mapper tool. It is very straight forward and comment threads were migrated in minutes.


Combining fields and avoiding duplicate display

I don't think this will necessarily fix your problem, but you're calling the theme_image_style incorrectly, it should be:

theme('image_style', array(
  'style_name' => 'thumbnail',
  'path' => $result['node']->field_image['und'][0]['uri'],
  'alt' => $title,
  'title' => $title,
  'attributes' => array('class' => 'search-result-img'),
));

Your second example is wrong, you can't call path twice.


With a problem like this, you may need to turn on MySQL query logging.  Once logging is enabled, put a noticeable query right before and after your DELETE query (do you can have something easy to search for), check the logs, and go from there.  Just be sure to disable logging when you are done.  It can kill performance and also fill up the disk pretty quickly.


How can I enforce a minimum length for private messages?

You will need to create a custom module to use that hook it will allow you to run custom validation on top of the standard validation done by private msg.

A hook allows you to add functionality to a module without having to hack the module causing issues when the original module needs to be updated. When a module makes a hook available it allows other modules to perform additional processing during the execution flow in this case additional validation
more on hooks here - http://drupal.org/node/292

As a minimum your module will need a info file telling Drupal about your new module and a module file containing the hook with your extra validation code.

You can see what to put in your info file here - http://drupal.org/node/1075072

This page will guide you through setting up your module folder and naming http://drupal.org/node/1074362

Now you have your module structure set up you need to add the hook_privatemsg_message_validate() to the module file

function MYMODULENAME_privatemsg_message_validate($message) {

}

Replace MYMODULENAME with the name of your module.

From looking at this page it looks like the original message id becomes the thread id if its a reply http://api.worldempire.ch/api/privatemsg/privatemsg.api.php/group/message_hooks/7-2

array (
 'mid' => 3517, // message id, identifies a message
 'author' => 27, // author id
 'subject' => 'Message subject',
 'body' => 'Body of the message',
 'timestamp' => 351287003, // unix timestamp, creation time
 'is_new' => 0, // If the message has been read by the user
 'thread_id' => 3341, // thread id, this is actually the mid from the first                          message of the thread
)

My guess is you could do something like this to test:

if($message['thread_id'] == 0 || empty($message['thread_id']) && strlen($message['body']) < 25) {
form_set_error("Message must be n chars long");
}

I'm not that familiar with the module so you might need to investigate by printing out the message array to confirm this.

Putting it all together it would look something like this

function MYMODULENAME_privatemsg_message_validate($message) {
    // Uncomment next line print out the message array if you need to confirm what contiton to use for checking if first msg or not
    // echo print_r($message);
    if (empty($message->thread_id) && strlen($message->body) < 25 /* Change this to whatever length you want*/) {
        form_set_error('body][value', t('Message must be n chars long.'));
    }
}

Hopefully thats enough to get you started


Maybe this will be helpful (in a custom module):

function testmodule_forma($form, & $form_state) {
    $form['im-container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['image_file'] = array(
        '#type' => 'file',
    );

    $form['upload'] = array(
        '#type' => 'submit',
        '#value' => 'upload',
        '#submit' => array('upload_image'),
        '#ajax' => array(
            'callback' => 'upload_image',
            'wrapper' => 'im-area',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );
    return $form;
}

function upload_image($form, $form_state) {

    $file = file_save_upload('image_file', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", FILE_EXISTS_REPLACE);
    if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
        $form['im-container'] = array(
            '#title' => t('Preview:'),
            '#prefix' => '
',
            '#markup' => ' filename.
            '" height="250" width="250" />',
            '#suffix' => '
',
        );
    } else {
        drupal_set_message('No file uploaded.');
    }

    return $form['im-container'];
}


This can be done using Contextual Filters under Advanced Settings of View Edit Page. You can add URL parameters as filters in it. This link will help you in detail

Thanks


How to trigger a rule when clicking on a link?

take a look at Rules Link:

  This module lets you create links which trigger arbitrary
  functionality with the help of Rules.


What should a bilingual site look like from the backend?

I figured out that a correct localized main menu should be bilingual or multilingual and therefore look like this:

Home
About Us
-Team
-Jobs
Start
Über uns
-Mitarbeiter
-Karriere
Infographic (EN: Infographic, DE: Infografik)

The possibility to save localizations inside of the node (my possibiliy 1 in the question) are for pages that are not necessary to translate (e.g. they show only a infographic, as in my example above) but the links pointing to them.

Hope this helps other people with this question.


Arguments in Drupal 7 are the same as contextual filters. Contextual filters are associated with the path of the view (or the view's page). With these, we give a basic determining factor as to how we want to narrow down the view's output. It can be set up on what ever you want it to be. One of the simple ways to do it is by content type or user name.
Check out this page it explains it well. http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments.
I also found these vids while searching  on relationships and contextual filters (arguments). Check them out they put a lot of things in perspective and teach you how to use them both.

Drupal 6:
http://gotdrupal.com/videos/drupal-views-relationships
http://drewish.com/node/127

Drupal 7:
http://vimeo.com/22100751


How do I create a .tpl file for a panel pane?

You can refer Documentation on Panels Pane template, which provides details on how to define a template for Panels Pane. If you want to add your own template name you can also do that by implementing template_preprocess_panels_pane in your theme or module file. Example for same is also available on documentation page.


How can I trigger custom code when some other module is being installed/uninstalled?

You can use hook_modules_installed() to react to modules being installed, e.g.

function hook_modules_installed($modules) {
  if (in_array('lousy_module', $modules)) {
    variable_set('lousy_module_conflicting_variable', FALSE);
  }
}

and hook_modules_uninstalled() to react to the opposite, e.g.

function hook_modules_uninstalled($modules) {
  foreach ($modules as $module) {
    db_delete('mymodule_table')
      ->condition('module', $module)
      ->execute();
  }
  mymodule_cache_rebuild();
}


Node relationships, backwards or forward?

A one-to-many relationship (also in DB design) is typically created by referencing the parent from the child. In the Jobs/Job Applications case, this translates into a reference from Job Application to Job, not vice versa.

In the Project/File case, if each file can only belong to one project, then it's also a one-to-many relationship and so File should reference Project. This is definitely how it should be if we were designing database tables for those entities.

However, in terms of Drupal and node references and given this particular example, Files are almost like properties to the Project node. So I wouldn't be surprised to see Files referenced from Project in a multiple-value node reference field, just for convenience.


Migrate Drupal7 to local, user login link redirect to live, how to redirect it to local?

My guess is your using the secure login module.

Either:

drush vset securelogin_base_url "http://server1/mysitename/user"

or

drush dis securelogin


How to get my Back To Site button to point to the correct location?

You're just stating facts, that is how Drupal works. If you log in, you go to your profile site by default. That might not make sense for most sites, but that's what it does by default, there modules that allow you to change it.

And "Back to Site" takes you back you the last non-admin page you were on. If you are on the homepage, it will point you back to that. Again, that's a feature, not a bug


What I did:

I defined a field entry in the source:

  name: hardwares
  label: 'Hardwares'
  selector: hardwares

In my process:

_products:
    plugin: sub_process
    source: hardwares
    process:
      products:
        plugin: sub_process
        source: products
        process:
          productName: productName
field_products:
    plugin: flatten
    source: '@_products'
_hwIds:
    plugin: sub_process
    source: hardwares
    process:
      hwId: hwId
field_hardware_ids:
    plugin: flatten
    source: '@_hwIds'

In order to get to the 2nd level of my data array, I needed to nest the sub_process plugin. I flatten the result afterwards in order to get a numerically indexed array which resembles the multiple value field structure.


Add scrolling effect to hidden node title

There should be no direct errors if you got it working on a HTML page. I would suggest checking from the html source that your js file is actually loaded (if not clear the caches). Additionally try wrapping the javascript code inside

jQuery(document).ready(function() {
  //code here
});

or a possibly better option with Drupal 7:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // code here
  }
};

You might find additonal useful info about managing javaScript in Drupal 7 here.


OG how to contrain a group to a maximum number of users

Organic Groups join limit
This module allows to set a join limit on a specific group.


Where is the autocomplete function for user/addressfield/autocomplete?

I was using the Commerce Admin Order Advanced module.  This is was providing the autocomplete.


Find specific node to uninstall a module

I figured out how to do it:

Go to content types
Features Article ->Manage Fields
Delete field


Should user input be able to cause an unhandled exception?

No, user input shoulnd't cause and unhandled exception. Not only because is a nasty reponse form server but it reveals an error condition not handled so it may head to security issues. A non-handled error means that developers are not aware of that error (or they are too lazy, what may be worst).

All error conditions should be handled to minimize problems related to that uncontrolled error.

I've tried to reproduce the bug (with two input name fields with name="name[]" as you have shown in your images) without getting reported error. So I think this
particular case you mention seems to be a drupal.org bug or a module bug of a module used in the Drupal site. You can report the bug in the Drupal.org infrastructure issue queue


Does my Drupal 7 site have transaction support enabled by default?

Looking at the construction of the DatabaseConnection_pgsql class, I noticed the following code:

$this->transactionSupport = !isset($connection_options['transactions'])
  || ($connection_options['transactions'] !== FALSE);

The code sets DatabaseConnection_pgsql::$transactionSupport to TRUE when the connection parameters don't contain the array index "transactions," which is one you should set in your settings.php file (it's not "transaction"), or when that array index is used in the connection parameters and it is not set to FALSE.
The same code is contained in DatabaseConnection_mysql::__construct(); in this case, the connection parameters (the ones set in the settings.php file) should be set not to use transactions only when the tables used are MyISAM.
Also DatabaseConnection_sqlite::__construct() contains the same code.

In short, the drivers used by Drupal always set the transaction support to TRUE, and users should set it to FALSE when they are using MyISAM tables, or they don't want to enable the transaction support.


This might help in terms of understanding Rules: https://drupal.org/node/878718

And in terms of flow, I think you could use a rule via the Rules module to direct them to a login page specific to them (people who have just filled out the form), and then the Login Redirect module to redirect them back to the form/submit action after they login. That's assuming the information they entered would remain in the form. You'll probably have to do some experimenting with that.

Jennifer


To overcome the above problem, I have installed the IMCE for FileField module; everything started working.


Assuming you do not have a debugger going (getting XDebug to run for your local development environment is probably the single most useful thing you can do the entire year), you could use debug_backtrace() at the place of the error (i.e. in the two form alter functions) to find out what is calling them. If you shoot its output into watchdog(), hopefully you can cross reference the time of the error with a particular invocation of these functions. Do be aware that these are form alter hooks, which get called for each and every form Drupal is building (and you might be surprised there can actually be several forms on a single page; just think of search and login forms). I.e. not every call will be the offending one.


How to check if the AMP module (Accelerated Mobile Pages) is working?

The first thing that needs to happen is to get it reindexed by Google so it knows about it.  I suggest configuring Google Search Console on your site https://support.google.com/webmasters/answer/4559176?hl=en  You can request it to be reindexed there. It was called Google Webmaster Tools before they rebranded it.
Its as easy to set up as Google Analytics.  It shows a display of what your site looks like on desktop, as Google sees it.

It does show you want it looks like ton AMP.


You can achieve this by creating field tpl file.

Refer field.tpl.php

Create tpl file named as field--field_related_news.tpl.php


How to update failed transaction detail in drupal commerce

You need to load the failed transaction from order id as shown below:

<?php
  $query = new EntityFieldQuery;
  $result = $query
    ->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order->order_id)
    ->propertyOrderBy('transaction_id', 'DESC')
    ->range(0, 1)
    ->execute();
?>

Then load transaction using commerce_payment_transaction_load($transaction_id) & update transaction object as shown below:

<?php
//Use following line instead of loading transaction in order to create new transaction object
//$transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
$transaction = commerce_payment_transaction_load($transaction_id);
$transaction->amount = $charge['amount'];
$transaction->currency_code = $charge['currency_code'];
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
commerce_payment_transaction_save($transaction);
?>

You can set a cron to periodically check failed transaction & check status of same at Payment Gateway & update accordingly.


Error on update from 2.3 to 2.8 and 2.7?

I just copied the files to the new folder

That's not how to update a Drupal 8 project - you need to use Composer.

Run composer update in your project root, and the old version of the address library (commerceguys/addressing), which is causing your current problem, will be upgraded alongside the modules.


How do I make entity reference lookup faster

Ideally you'd use an Entity Query for this, but in principle:

You can batch load the parent nodes

...
$nids = $data->fetchCol();

foreach (Node::loadMultiple($nids) as $node) {

If memory is a concern with thousands of nodes, just implement some simple php logic around the loop to batch it into, say, 50-100 at a time.
If you don't need the child entities, just their IDs, they're available without a DB hit

foreach ($node_load->field_institution_with_date as $item) {
    $the_entity_id = $item->target_id;

If you do need the entities, you could build an array of all IDs using this method, and batch load those using Node::loadMultiple after the outer loop.


Wysiwyg, ckeditor disappers when click "Add another item" button

I had this problem as well. This was fixed in http://drupal.org/node/1155678#comment-5358290 by adding a detach function to the WYSIWYG behaviors. You can apply the patch at the above link (that's what I did) or you should be able to download the 7.x-2.x-dev version (I haven't tested that) since it's been committed already.


Can Commerce be setup to skip Cart/Customer

Yes, it's possible but would need testing out and tinkering.

You could disable the checkout pages, other than payment / offsite payment redirect

Either at

admin/commerce/config/checkout by setting the panes to disabled
or perhaps with hook_commerce_checkout_page_info_alter and removing the pages.

You could then add a Rule

Event: After adding product to cart
Action: Redirect to page "checkout"

Which will hopefully take the user off to PayPal / offsite payment.

Again, needs testing, but theoretically possible.


How to set the access of a menu page for all?

If you set access callback to TRUE, all users will have access to the menu router item. That means ALL users.

 $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access callback' => TRUE,
    'type' => MENU_SUGGESTED_ITEM,
  );

However, setting 'access arguments' => array('access content'), and omitting 'access callback' => TRUE, is the best way - check your permissions settings. You should be getting an access denied error at example.com/node page as well.

If you don't set an access callback, it would be user_access and the access argument will be passed to that function.


Turns out it was removed in this commit to Drush 9 following this issue and follow up.

So archiving no longer exists, or at least not until someone has time to port the logic over to the Composer workflow.


How do I create extra permissions for an eck created entity?

You need to alter the entity info using:

hook_entity_info_alter

and add the access callback

e.g:

function EXAMPLE_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['access callback'] = 'my_entity_access';
}

and then in my_entity_access

function my_entity_access($op, $entity = NULL, $account = NULL) {
  switch($op){
    case 'view':
    // view check
    // e.g return user_access('view my_entity', $account);
    break;
    case 'create':
    // create check
    break;
    case 'update':
    // update check
    break;
    case 'delete':
    // delete check
    break;
  }
  return FALSE;
}

See node_access for more info

You may want to use hook_permission to define your own permissions also.


How can I force a field to be required if another field has a certain value?

With custom code you can do something like this:

add a new validation function using hook_form_alter()

your_module_form_alter($form, $form_state, $form_id) {
  if($form_id == 'the_form_ID') {
    $form['#validate'][] = 'your_custom_validation_function';
  }
}

then check to see if the conditions are met

function your_custom_validation_function($form, &$form_state){
  if( $form_state['values']['your_checkbox_name'] == 1 ) {
    // check to see if tags are set
    // use form_set_error('tags_field_id', 'error message') to set a error message
  }
}


"exceeded the maximum file size" error even when uploading small files

I found a workaround, as this is a tricky one to nail down.

Don't hit the "Upload" button at all.  Just hit the "Next" button directly.  If that works, you ran into the same problem I did.


I figured it out.  I installed pathauto to try and force it to work and realized that the url aliases set on every node had content/ prepended to them as part of a mass import.

I ran this in the mysql console to update them correctly:

update url_alias set alias = REPLACE(alias,'content/node','node');

And problem fixed.


One-to-many and many-to-many relation between nodes of different content types

The Relation module itself provides a block that can be used to create relations, you can create a simple relations by configuring relations and entity collector or can use the Rules module to create relations.

If your want to set up a relationship between entities than you may use the relation_add module: It provides a block that allows the user to add an appropriate relation from an entity page to any other appropriate entities, with a generic autocomplete for each endpoint, and relation fields. Tutorial for relation add module.

Tutorials for creating a relation type (administration toolbar > Structure > Relation types):
https://drupal.org/node/1276284
http://nodeone.se/en/creating-a-first-relation-type-the-entity-collector
http://nodeone.se/en/directional-relations-and-fields-on-relations

Few Tutorials that may be useful for you:
http://vimeo.com/28178686
http://nodeone.se/en/learn-the-relation-module
https://drupal.org/node/1276298
https://drupal.org/node/1276380


Uninstalling modules, specificially ANSWERS

If a module doesn't delete its tables or content in hook_uninstall, then the content is not automatically removed when you disable the module.

You can see here that answers does not clean up after itself when it is uninstalled, probably for good reason.

If you want to purge everything, you will need to delete the nodes, fields, and bundles manually at admin/content and admin/structure/types or by writing some code that uses field_delete_field() or field_attach_delete_bundle().


How to add a block to a region in html.tpl?

You should make a new theme region similarly to how the header section works and add your block through the block admin into your new region. Rather than trying to get a block to come out in any other way

See this for more: https://www.drupal.org/docs/7/theming/assigning-content-to-regions


drush arr (drush archive-restore) says: Missing required argument: file

drush arr is expecting a site archive file as an argument. Its sibling drush command,drush ard, creates a site archive file. (see the drush codebase for more details on how this command works) The /root/.../drupal/ path is a backup drush creates when you run drush up
The /root/drush-backups/archive-dump/ path matches the format of drush ard's default output but if you didn't create this archive file you should inspect it (tar -tvf) to confirm it has the code/files/DB backup within it.
So yes, drush arr will restore from a site backup but you should take necessary precautions since you've inherited an undocumented process.


what is the strongarm variable addititonal_settings_active_tab_*

It is the vertical tab that is "active" when the node edit form loads. Export as needed (I usually don't).

FWIW, i used 'drush vget' to take a look at the variables value and that made it pretty easy to figure out its purpose. (Drush)


How to get rid of "Designed by" in the theme?

You need to edit the page.tpl.php file and remove the line in the footer:

http://cgit.drupalcode.org/business/tree/templates/page.tpl.php?h=7.x-1.x

Its at the bottom.

    <?php if ($footer_copyright): ?>
      <?php print $footer_copyright; ?>
    <?php endif; ?>
    <?php if (theme_get_setting('footer_credits')): ?>
      <?php print t('Designed by'); ?>  Devsaran.
    <?php endif; ?>

However, it seems like there is a theme setting you can just uncheck as well, under Admin > Appearance > Business > Settings called 'Footer Credit'.


I'ld take it from the other side: Attach a view to a node form.

First I tried it with the built-in node form. But this turned out to be quite a hassle. Instead I built a small custom form and created new nodes programmatically. Ajax submit. View refreshed. Happy, happy.

Here comes the code for a custom module. Presuming a fresh D7 standard installation.

Info file

name = MYMODULE
description = Provides cool stuff.
core = 7.x
package = Custom
dependencies[] = views

Module file

First provide a view.

/**
 * Implements hook_views_api().
 */
function MYMODULE_views_api() {

  return [
    'api' => 3,
  ];
}

/**
 * Implements hook_views_default_views().
 */
function MYMODULE_views_default_views() {

  $view = new view();
  $view->name = 'nodes';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Nodes';
  $view->core = 7;
  $view->api_version = '3.0';
  $view->disabled = FALSE;

  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['title'] = 'Nodes';
  $handler->display->display_options['use_more_always'] = FALSE;
  $handler->display->display_options['access']['type'] = 'none';
  $handler->display->display_options['cache']['type'] = 'none';
  $handler->display->display_options['query']['type'] = 'views_query';
  $handler->display->display_options['exposed_form']['type'] = 'basic';
  $handler->display->display_options['pager']['type'] = 'none';
  $handler->display->display_options['pager']['options']['offset'] = '0';
  $handler->display->display_options['style_plugin'] = 'default';
  $handler->display->display_options['row_plugin'] = 'fields';
  /* Field: Content: Title */
  $handler->display->display_options['fields']['title']['id'] = 'title';
  $handler->display->display_options['fields']['title']['table'] = 'node';
  $handler->display->display_options['fields']['title']['field'] = 'title';
  $handler->display->display_options['fields']['title']['label'] = '';
  $handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
  $handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
  /* Sort criterion: Content: Post date */
  $handler->display->display_options['sorts']['created']['id'] = 'created';
  $handler->display->display_options['sorts']['created']['table'] = 'node';
  $handler->display->display_options['sorts']['created']['field'] = 'created';
  $handler->display->display_options['sorts']['created']['order'] = 'DESC';

  /* Display: Block */
  $handler = $view->new_display('block', 'Block', 'block');

  $views[$view->name] = $view;
  return $views;
}

Then do the form.

/**
 * Provide a form.
 */
function MYMODULE_form($form, &$form_state) {

  $form['wrapper'] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'mywrapper',
    ],
  ];

  $form['wrapper']['node_form'] = [
    '#type'  => 'fieldset',
    '#title' => t('Add article'),
  ];

  $form['wrapper']['node_form']['node_title'] = [
    '#type'     => 'textfield',
    '#title'    => t('Article title'),
    '#required' => TRUE,
  ];

  $form['wrapper']['submit'] = [
    '#type'   => 'submit',
    '#value'  => t('Save'),
    '#submit' => ['MYMODULE_form_submit'],
    '#ajax'   => [
      'callback' => 'MYMODULE_MYCALLBACK',
      'wrapper'  => 'mywrapper',
    ],
  ];

  $form['wrapper']['view_display'] = [
    // view machine name && display/block name
    '#markup' => views_embed_view('nodes', 'block'),
  ];

  return $form;
}

/**
 * Do some validation.
 */
function MYMODULE_form_validate($form, &$form_state) {
  // Better do some validation.
  // Here or via #element_validate.
  // @see https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#element_validate
}

/**
 * Form submit. Node creation.
 */
function MYMODULE_form_submit($form, &$form_state) {

  global $user;
  $node = new stdClass();

  $node->type     = 'article';
  $node->title    = $form_state['values']['node_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid      = $user->uid;

  node_object_prepare($node);
  node_save($node);

  // Empty out title field on rebuild.
  $form_state['input']['node_title'] = '';

  // Rebuild form.
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback to return the whole wrapper.
 */
function MYMODULE_MYCALLBACK($form, &$form_state) {

  return $form['wrapper'];
}

I've put it on a sample page to see it in action.

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['example/form'] = [
    'title'            => 'Example Form',
    'description'      => 'A form to mess around with.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['MYMODULE_form'],
    'access arguments' => ['create article content'],
  ];

  return $items;
}


Contextual filter "Allow multiple values" is gone

Found the reason: My site was in maintenance mode and the green message was preventing the block to appear... So it's a matter of css. Super stupid, but it took me a while to figure that out. Might be useful to someone having the same issue.


In Drupal 8 the configuration of a View is stored in an entity, which you can load, modify and save:

use Drupal\views\Entity\View;

  $view = View::load('custom_view');
  $display =& $view->getDisplay('page_1');
  $display['display_options']['path'] = 'example/path';
  $view->save();


How do I make the content of one user not accessible to other

For nodes check Content Access module. It has video tutorials.


Using the Rules module you can implement a rule that looks like so:

{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "my_homepage" } }
    ]
  }
}

It will redirect any path starting with node/ to a path named my_homepage (adapt that path to fit your homepage path).

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function.

Note: A variation of this rule could be to replace the Rules Condition with something like "if the current path is not my_homepage" (in which case the same Rules Action will redirect to my_homepage.


How to make commands invoked by drush_invoke not to fail after adding extra option?

The preferred solution is to use drush_invoke_process() for subtasks. This will execute the command in its own process, completely isolate from the parent.

If you do need or wish to use drush_invoke() (doing so is a little faster, since you don't need to bootstrap again), then you should use drush_set_option('strict', 0); to disable options checking.


There's no such concept as parent and sub/child-modules in Drupal. You'd have to define what you consider to be the parent-child relationship, pick what physical properties of the module you're going to use to describe that relationship, and code a solution from there.

Drupal's own native mechanism for grouping modules is using the package key in the module .info file. In the case of Actions Permissions, for example, the package is defined as "Administration", so you can find it under the "Administration" fieldset, grouped with other modules that are considered to have (loosely) related functionality by their respective authors.

On a slightly un-related note, but you can improve the UI of the modules page using Module Filter if it's becoming unwieldy.


How to obtain a list of JS files from enabled modules, or expose such list from a theme as library?

list_themes() returns an array of objects:

The keys are the themes' machine names and the values are objects having the following properties:

scripts: An associative array of JavaScripts, using the filename as key and the complete filepath as value. Not set if no scripts are defined in the .info file.


How do I go about putting standalone PHP files into Drupal 6?

Your best bet would be to include it via a custom module, and to include it would be as easy as using module_load_include().

As for security, I would advise taking a look at the Drupal coding standards documentation, which is unfortunately tagged as D7 and I wasn't able to find the old D6 version, but generally following standards will help prevent some security issues.

Code not written exclusively for Drupal may not specifically work out of the box either, you may have to write a bridge for the code to integrate it better, otherwise you may need to re-write it completely.


You can use drush sql-connect for this, so you don't need to enter any credentials and/or use mysql's command line:

`drush sql-connect` < my-sql-file.sql

The tildes tell your shell to replace the command drush sql-connect with the command's output. Therefore, when you run this line in your terminal, bash will actually see something like:

mysql --database=dbname --host=localhost --user=username --password=password < my-sql-file.sql

Check out Drush's documentation for much, much more.


How can I send Newsletter in HTML format?

You can use Mime mail along with your newsletter module to enable HTML in your emails. This module will work on the message mime so it should work with almost any mail module


Add another button removes the default values from my fields on node form

Ok. I found the solution. Let me share my code here.

I stored the argument in the $form_state['storage] so that it can be preserved during the ajax call.

if (arg(0) == 'node' && arg(3)) {
    $form_state['storage']['field_test_value'] = arg(3);
}

// Only on node creation.
if (!$form['nid']['#value'] && isset($form_state['storage'])) {
    $form['field_test'][LANGUAGE_NONE]['#default_value'] = $form_state['storage']['field_test_value'];
}

$form['field_test'][LANGUAGE_NONE]['#attributes']['disabled'] = 'disabled';

Hope this will help someone.


How to redirect from URL with trailing slash to one without

Select the Enforce clean and canonical URLs checkbox in  admin/config/search/redirect/settings.

Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing trailing slashes, ensure the language prefix is set and similar clean-up.


Drupal 8 Migrate Plus - CSV Row Number as key

I couldn't find a way to do this, but I found out you can specify multiple keys to make the row more unique for mapping.

keys:
- name
- address

When I applied more keys as a mapping, all the records imported since it was more unique.

Hopefully this helps someone else.


Using views to display content comparing users id

This can be achieved using contextual filters in views. Here are the steps:

In the views edit page click on Advanced section.
Click on the Add button corresponding to "Contextual Filters"
Search for your custom field in your custom content type and add it.
In the configure contextual filter which appears make the following changes.
Under "When the filter value is not in the url" section, select the option "Provide default value". In the type select list, select the option "User ID from logged in user".

Save the changes.


You need add $config['system.logging']['error_level'] = 'verbose';

in file

sites/default/settings.php

or in {example}.com/admin/config/development/logging
you checked in All messages after click to Save configuration


If you're using D7, it ships with the stark theme which is a pretty good example of how basic you can get.


Views Slideshow Menu. Only works with 2.x at the moment.


You can implement hook_element_info_alter() to change the theme wrappers used by the form fields.

If you look at the code of system_element_info(), you will notice the form fields are defined as in the following code.

  $types['textfield'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#autocomplete_path' => FALSE,
    '#process' => array('ajax_process_form'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );
  $types['machine_name'] = array(
    '#input' => TRUE,
    '#default_value' => NULL,
    '#required' => TRUE,
    '#maxlength' => 64,
    '#size' => 60,
    '#autocomplete_path' => FALSE,
    '#process' => array('form_process_machine_name', 'ajax_process_form'),
    '#element_validate' => array('form_validate_machine_name'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );
  $types['password'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#process' => array('ajax_process_form'),
    '#theme' => 'password',
    '#theme_wrappers' => array('form_element'),
  );

You can add a new form wrapper, or change the existing one. Suppose, for example, that you want to add a theme wrapper for the textfield form field; you could use code similar to the following one.

function mymodule_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#theme_wrappers'] = array_unshift($type['textfield']['#theme_wrappers'], 'mymodule_textfield_wrapper');
  }
}

Your module then should implement the theme_mymodule_textfield_wrapper() theme function, and  hook_theme() to declare it.
You can use the code of theme_form_element() as guideline to write your code. The form element is contained in $variables['element'].

Alternatively, if the form fields you want to wrap with additional HTML use all the same theme wrapper, you can override that theme function using hook_theme_registry_alter(). Be careful, as in this case you are also altering every form field using that theme wrapper, including future form fields for which your wrapper could cause issues.


Use a view's result as a javascript setting

It looks like Supersized wants a slides array with the information about each image.  You could build the slides array dynamically from the view.

Two fields in the view:
(1) The image,
(2) The image thumbnail

The slides array wants these properties: image, title, thumb and url.

You could derive the image src, the title and the url from the image field (make sure it links to something).
You could derive the thumbnail src from the image thumbnail field.

And here is some code that with modification should work just fine (taken from Supersized demo page):

jQuery(function($){

  var slidesFromView = [];

  $(".view-supersized .views-row").each(function(){
    var rowImage = $(this).find(".views-field-image img").attr('src');
    var rowTitle = $(this).find(".views-field-image img").attr('title');
    var rowThumb = $(this).find(".views-field-image-thumb img").attr('src');
    var rowUrl = $(this).find(".views-field-image a").attr('href');
    slidesFromView.push({image: rowImage, title: rowTitle, thumb: rowThumb, url: rowUrl});
  });

  $(".view-supersized").hide();

  $.supersized({

    // Functionality
    slideshow               :   1,          // Slideshow on/off
    autoplay                :   1,          // Slideshow starts playing automatically
    start_slide             :   1,          // Start slide (0 is random)
    stop_loop               :   0,          // Pauses slideshow on last slide
    random                  :   0,          // Randomize slide order (Ignores start slide)
    slide_interval          :   3000,       // Length between transitions
    transition              :   6,          // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
    transition_speed        :   1000,       // Speed of transition
    new_window              :   1,          // Image links open in new window/tab
    pause_hover             :   0,          // Pause slideshow on hover
    keyboard_nav            :   1,          // Keyboard navigation on/off
    performance             :   1,          // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
    image_protect           :   1,          // Disables image dragging and right click with Javascript

    // Size & Position
    min_width               :   0,          // Min width allowed (in pixels)
    min_height              :   0,          // Min height allowed (in pixels)
    vertical_center         :   1,          // Vertically center background
    horizontal_center       :   1,          // Horizontally center background
    fit_always              :   0,          // Image will never exceed browser width or height (Ignores min. dimensions)
    fit_portrait            :   1,          // Portrait images will not exceed browser height
    fit_landscape           :   0,          // Landscape images will not exceed browser width

    // Components
    slide_links             :   'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
    thumb_links             :   1,          // Individual thumb links for each slide
    thumbnail_navigation    :   0,          // Thumbnail navigation
    slides                  :   slidesFromView,

    // Theme Options
    progress_bar            :   1,          // Timer for each slide
    mouse_scrub             :   0

  });
});


Possible permissions error with drush make

Problem was that running sudo drush had probably added some unwanted permissions to the cache folder. Deleting the folder solved the problem.


How to list the most popular content for different periods of time with Radioactivity?

You are right.  There is a one-to-one relationship between fields and profiles.  Since one field cannot represent multiple profiles, you will need 3 fields.

In answer to your Rules question, it should be possible to create a rule with 3 actions to update the 3 fields at the same time.


Determine whether a field has changed during hook_node_submit

As said from @Clive, the only way is to compare the value in $node with the value contained in $node->original. As far as I can see, that value is only available in hook_node_edit(), hook_node_update(), and hook_node_presave() since entity_load_unchanged() is called from node_save() (which also unset $node->original before exiting). If you need it in hook_node_submit() you could simply add the following code in your implementation.

if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

Since you are checking for field properties, the other, more general, hook would be hook_field_attach_submit().


I found the solution for it.

to reach to the edit button hook_entity_access() is the correct Hook but to provide access to that block content, we first need access to class

Drupal\Core\Access\AccessResult

then to provide access we need to return

AccessResult::allowed()

A complete example where we might want to give access to a block_content would look like this.

Use Drupal\Core\Entity\EntityInterface;
Use Drupal\Core\Session\AccountInterface;
Use Drupal\Core\Access\AccessResult;

function block_user_access_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {

  if($entity->getEntityTypeId() == 'block_content'){
    return AccessResult::allowed();
  }
}


What's difference between "attributes", "title_attributes", and "content_attributes"?

This depends on the template you use. If you use for example the node template

node.html.twig

  {{ title_prefix }}
  {% if not page %}

      {{ label }}

  {% endif %}
  {{ title_suffix }}

  {% if display_submitted %}

      {{ author_picture }}

        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}

  {% endif %}

    {{ content }}

You have four attributes variables

attributes
title_attributes
author_attributes
content_attributes

The difference between them is that they have different targets in the html markup of the template. The main attributes variable in a node is for the
 tag, in a form for the <form> tag or in other templates often a simple wrapper
. If a template defines additional attributes variables they are for that specific part of the template, in a node for the title, author and content.

Always add attributes to the existing variable like explained in the linked documentation. Never replace it with your own attributes, because a lot of code depends on that the template is actually using the attributes variables.


Rendering field with the help of functions

The correct syntax for your approach would be:

function mymodulename_getText($entityId,$field){
    return $entityId->$field['und'][0]['safe_value'];
}

I suggest to sanitize that with a isset().


How to alternate image on left/right using "Views Parity Row" module

You can just set all view-rows to be left and then do like this in your css:

.views-row:nth-child(2) {
   float: right;
}

UPDATE:

.views-row:nth-child(odd) {
  float: left;
}
 .views-row:nth-child(even) {
  float: right;
}

As @No Sssweat pointed out you can use nth-child odd and even to style every second element. You don’t need to style on the parent just use above code.

I actually wrote something wrong you can add nth-child on the .views-row elements


Cannot alter output of a view under any circumstances

When you use Custom Text, you are telling Views to override anything it does and display only what you have provided it plus the addition of your placeholders. So what you should do here is exclude the original field from the display and write your HTML with the class into the custom text field. Then, include the field placeholder.

Like this.

  [field_link_title]

I am pretty sure this gets you the intended result. Note I am making up those placeholders and you should see what your available replacement patterns are. :)


How to set the ordering of a taxonomy term's listing page

Using the Views module, enable the Taxonomy view. You can customise the content of the tag results page by adding/ordering fields, just as you would any other view.


The function drupal_write_record() uses the database schema defined from the module. Check your hook_schema(), and see if it has the right length.

Post your hook_schema() implementation too, if this doesn't help.


Try next:

// ...
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
$form['#redirect'] = 'CHANGE_VIEWSPAGE_HERE?page=' . (int)$_GET['page'];
print render($form);


What should I enter as "Database file" for a SQLite database?

This configuration dialog is for SQLite-type databases only, it might be that your installation only has activated the PHP modules for this type of databases (for MySQL databases, you need pdo-sql, see here: https://www.drupal.org/node/2219779).

If you wish to use a SQLite database (which should work fine for testing purposes), you can either indicate a location for your SQLite database file, or leave the default, which should work fine. The Drupal installer will create the SQLite database for you in that location; you don't need to create it separately.


Media module is almost certainly the reason.

There are patches in both http://drupal.org/node/1307054 and http://drupal.org/node/1343022 that you may find useful.


Dragboxes in a page (Dashboard kind of display which is clickable)

I would check into jQuery UI/Drag & Drop.
http://jqueryui.com/demos/

After you get the hang of this, create a template file for your homepage.
Create blocks with different content and render them in your homepage template file.
Apply the drag and drop interface to the blocks you rendered on your homepage.

This is just a quick look on your question, but it should get you in the right direction.


Change the theme used for the user reset password page

You can use a RouteSubscriber to do that but it will also affect your user edit form and render it with the default site theme since it uses the same route name. The RouteSubscriber can't alter a route based on a query string parameter such as pass-reset-token
yourmodule/yourmodule.services.yml
services:
  yourmodule.routesubscriber:
    class: Drupal\yourmodule\Routing\YourmoduleRouteSubscriber
    tags:
      - { name: event_subscriber, priority: 1 }

yourmodule/src/Routing/YourmoduleRouteSubscriber.php
<?php

namespace Drupal\yourmodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Custom route subscriber.
 */
class YourmoduleRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.user.edit_form')) {
      $options = $route->getOptions();
      $options['_custom_theme'] = 'yourthemename';
      $route->setOptions($options);
    }
  }

}


How to print username into url after user logs in?

I am not sure how and where you append the username, but I assume that you try something like this:

$url = $current_url . '?user=name';

Instead you should try something like this:

$url = url($current_url, array('query' => array('user' => 'name')));

This will produce this URL: current_url?user=name

Another thing: You have %5B and 3%A in your URL. I am not sure, but you want to have your URL look like this: url[user:name]. Queries in URLs should rather look like I did that and how Drupal's query options creates them: url?user=name

If that does not solve it, you could post some code ;)

Cheers,
j


Look at the settings for your theme. There is a check mark to include the user pictures or not.
There are settings for the individual theme, and generic settings.


From reading your question, I take it you have zero integration with Drupal. You simply hardcode your entire slideshow in a block.

What I would suggest is that you start with creating a new content type, and then apply either Field slideshow or Views slideshow onto it.

  Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.

  Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


why is the node id missing from the comment:edit action?

@Denford: You are right in saying that comments do have ids. They are just called cids and not nids :-)

What is the trigger that you are firing? My guess is that for a new comment posted, you are not seeing the 'cids' because they would be available only to the trigger 'after saving a new comment' and not the trigger 'when either saving a new comment or updating.. blah blah'.


Give permissions to a specific role to edit specific terms

The access callback for a term edit page is taxonomy_term_edit_access($term). You need to replace it with a custom one in order to allow gardeners to access the page for fruit terms.

/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term/edit']['access callback']
    = 'MODULE_term_edit_access';
}

/**
 * Access callback for taxonomy edit term page.
 */
public function MODULE_term_edit_access($term) {
  if (MODULE_term_is_fruit($term) && user_access('edit fruits terms')) {
    return TRUE;
  }
  return taxonomy_term_edit_access($term);
}

/**
 * Returns whether or not a term is a fruit.
 */
function MODULE_term_is_fruit($term) {
  // ... implement fruit detection here ...
  foreach (taxonomy_get_parents_all($term->tid) as $parent) {
    if ($parent->name == 'Fruit') {
      return TRUE;
    }
  }
  return FALSE.
}

/**
 * Implement hook_permissions().
 */
function MODULE_permissions() {
  $permissions['edit fruits terms'] = array(
      'title' => t('Edit fruits terms'),
      'description' => t('Allows the user to edit Fruits terms.'),
  );
}


Swiftmailer module installation fails although the swiftmailer external library is installed

That's 7.x/outdated information unfortunately.

You should use composer to manage your Drupal 8 site, using the drupal-project starting point: https://github.com/drupal-composer/drupal-project. It will be a bit of work to switch an existing site to that but after that, installing swiftmailer including all its dependencies will be as easy as running composer require drupal/swiftmailer. That will automatically include all dependencies.


Put this code in your theme's template.php file:

function THEME_preprocess_views_view_fields($vars){
  dpm($vars);
  if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] == 4){
    $vars['fields']['title']->content = 'blahblah';
  }
}

Clear the cache.

Replace VIEWNAME, DISPLAY and 4 with your appropriate values.

Then inspect the $vars['fields'] with dpm output and rewrite the output how you want for the field in question. You may use 'raw' value, but remember to sanitize.


Webform 8 - How can I make a text field value be A if a select value is 1?

You have to use JS, go to settings - CSS/JS tab, write code in CUSTOM JAVASCRIPT textarea.

Some code for reference. I got a text input (id is edit-name), a select (id is edit-gender), the id you find enter 'F12' to see. ID is automatically generated by Webform.
When I select male, the text input will appear male.

(function ($, Drupal) {'use strict';$(document).ready(function(){
  'use strict';
  var name = $("#edit-name");
  var gender = $("#edit-gender");
  var duty = $("#edit-duty-select");
  function ab() {if (gender.val()==='male'){name.val("male");} else {name.val("girl")}};
  gender.change(ab);  // add a Listener to select
});
})(jQuery, Drupal);


Regular Drupal 7 site users do not see new tabs added by hook_menu_local_tasks_alter

You have to use hook_permission

So in your module file something like this will do the job. (taken from the hook's page).

function hook_permission() {
 return array(
  'administer my module' => array(
  'title' => t('Administer my module'),
  'description' => t('Perform administration tasks for my module.'),
  ),
 );
}

When you do that you will get a new entry in your permissions page (admin/people/permissions). Enable that for the anonymous users and it will show up ok.


Create block programmatically based on node content

Found a few modules depending on your need:

Node field block

  An easy way to create blocks with a collection of node fields. Focused on letting customers manage most of the content on a page in just one node. You can create multiple blocks for a node with one or a combination of fields and move them in different regions.

Field as block

  Field as Block provides an easy way to display one or more fields of the current node in a block.

There's a custom way also if you want. You can use below function for this purpose.

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


Insert code in to field or center of content type that already has 1000's of nodes

https://www.drupal.org/project/eba inserts a block in to the manage display area of each node or entity, this has allowed me to add a google ad in the middle of the content between any fields I want on any entity I want and to 1000s of already published nodes.


How to convert a complex select query to Drupal dynamic query?

Give a try to Query coder module ( https://www.drupal.org/project/query_coder ): Convert SQL query to Drupal Database abstraction layer code.

Otherwise to debug the error turn on the error reporting, and check the error log which will point you to the suitable path.


How do I display the latest post related to another?

I ended up using the views field view to get the job done.


How can I embed a node inside on another node?

You can use entityreference together with display suite and have the display of the entityreference field set to rendered entity. Using rendered entities you can can render any entity with a view mode you need for your display. See this question if you want to create a custom template for the output of that node: How to provide template for particular view mode?


How to count webform radio button submissions

If you want do the number count after submit is done

Login as Admin
open your webfrom
Click Result
From webfrom menu click Analysis

It will give you the most complete Analysis of your form.


Commerce Fee not being added to order total sent to payment processor

Take a look for the issue https://www.drupal.org/project/commerce_fees/issues/2191191, maybe a patch can help you.


how to make a custom entity multilingual

You need the translatable = TRUE line in your @ContentEntityType annotation. You also need the setTranslatable(TRUE) line in your BaseFieldDefinition::create fields.


How to display the calculated priced of commerce products?

When a price field is rendered using the "Formatted price" display formatter, it has a setting for you to choose between displaying the original price as loaded or the calculated sell price for the current user. That second one is the default, so as long as you are using product pricing rules properly (as indicated in the comments), this should just work for you.

If for some reason it isn't you'll need to find and review your display settings for the price field on your various product types. Because the price field that appears on a product display comes from the product entity directly, you have to adjust its field display settings there instead of on the relevant node type. You should find them under Administration > Store > Products > Product types. Click the manage display link beside your product type and see what it says.

If you get stuck, feel free to join us in the #commerce channel in the Drupal Slack!


How to have on-page comments in Drupal 7?

It seems you're looking for the AJAX Comments module

Features:

  Provides ajax comments to Drupal sites. Features:

  Makes AJAX submits
  Allows replies to comments on the actual thread page
  AJAX comments deleting
  Works with CAPTCHA
  Cool jQuery sliding
  views integration


how to insert a search form in custom content

I was close but needed to declare the variable.  I still don't really understand what's happening here, but it works.

<?php global $search_form; print render(drupal_get_form('search_form')); ?>


Undefined offset: 1 in gcm_action_send_message()

I found the answer by looking the code used from the module.

function gcm_action_send_message($tokens, $keyValues, $delay_while_idle, $time_to_live, $collapse_key) {

    $gcm_message = array();
    foreach (explode(",", $keyValues) as $keyValue) {
      $temp = explode("=", $keyValue);
      $key = $temp[0];
      $value = $temp[1];
      if (isset($key) && isset($value)) {
        $gcm_message[$key] = $value;
      }
    }
    gcm_send_message(array_unique(explode(',', $tokens)), $gcm_message, $delay_while_idle, $time_to_live, $collapse_key);
}

So we need to use for key-values a value like 0=[site:name], 1=[site:mail].


Display custom output if field doesn't have value in hook_field_formatter_view

I am able to do this as below in hook_field_formatter_view().

switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (empty ( $items )) {
      $output = generate_custom_output();
      $element[]['#markup'] = $output;
      $element ['#items'][] = array('value' => $output);
      $items[] = array('value' => $output);
    }
  break;
}

If anyone have better solution please provide.


How can I prevent "zend_mm_heap corrupted" when adding Views programmatically?

There are several bugs reported to php.net about this error (search "drupal zend_mm_heap corrupted). Indeed it turned out to be a PHP bug with php 5.3.

I upgraded to php 5.4 and the error goes away.

The issue is not necessarily Drupal related. However, it does seem to be related to how php includes and processes large files. In that respect, since Drupal can end up dealing with massive amounts of files and php data, this is probably the reason that many of the reported PHP bugs involved Drupal sites.

So, if you are getting this error, quite possibly you need to upgrade your PHP to 5.4


Which releases are supported with semantic versioning of modules?

You got an email because the 2.0.0 version has been marked as unsupported by the project maintainer when, on the Releases edit form, the Supported checkbox for that version has been deselected.

On Drupal.org, 2.x, 2.0.x, and 2.1.x are considered like three different branches, and have each the setting to make them supported or recommended.
It's not just a matter of version number, but also what the project maintainers mark as supported. Probably, if you had version 2.1.0 installed, that were marked as unsupported, and version 2.0.0 were marked supported, you would get an email telling you the version you installed got unsupported.


Drupal duplicate filename throws AJAX error

As per Drupal structure you need to add option "FILE_EXISTS_RENAME" during save file for example :
 $file_temp = file_save_data($attachment->data, 'public:///' , FILE_EXISTS_RENAME);


How can I trigger a javascript function when a Drupal ajax call is complete?

I ended up adding some additions commands to the page that is being returned by the ajax handler like this:

$commands = array();
$commands[] = ajax_command_invoke(NULL, 'grid_content_loading', array('argument1', 'argument2'));
$commands[] = ajax_command_append('#grid-content-target', $html);
$commands[] = ajax_command_invoke(NULL, 'grid_content_loaded', array('argument1', 'argument2'));
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

And on the client side I created 2 javascript funtions through jQuery:

(function($) {
$.fn.grid_content_loading = function($argument1, $argument2) {
   ...
};

$.fn.grid_content_loaded = function($argument1, $argument2) {
   ...
};
})(jQuery);


Take a look at the Omega base theme.  I haven't used this with D6, but the D7 version handles all of the media queries and makes it pretty easy to customize them via the UI settings page.


How to set paragraph margin when editing in CKeditor?

In your example you have:

...</style>

I'm assuming that should be:

...

In general in terms of controlling the space between paragraphs I think the best way to do that is your CSS stylesheet, not really HTML.

Drupal and CKEditor do some HTML manipulation that you may want to checkout - admin/config/content/ckeditor, then choose your profile and click edit.
Under appearance you can select/deselect some plugins that you might not need.

In terms of a quick fix though I would think that this would work:

...

But it also depends on what is in your site's stylesheet and your theme.


How can I get the Register form on the front page?

The correct form id shoud be Drupal\user\RegisterForm. However, because the register form is attached to an entity, you can't use getForm directly. You need to create an entity and then get the register form for that entity.

The role of the preprocess function is to add / modify / delete template variables via the $variables parameter, so you need to add the form to that array rather than return it.

Something like this should work:

function themename_preprocess_page(&$variables) {
  $entity = \Drupal::entityManager()
    ->getStorage('user')
    ->create(array());

  $formObject = \Drupal::entityManager()
    ->getFormObject('user', 'register')
    ->setEntity($entity);

  $form = \Drupal::formBuilder()->getForm($formObject);
  $variables['register_form'] = $form;
}

Now you should be able to print the form via {{ login_form }} in the page.html.twig template.


Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs?

Yes, the arg() function can do this.

https://api.drupal.org/api/drupal/includes%21path.inc/function/arg/6.x

At the end of Drupal's .htaccess file, you can see how Drupal makes those URLs work by rewriting them to ?q= if they are not real files or directories. Without this, they would cause a 404 too.

In http://api.drupal.org/api/function/arg/6 you can see how it handles them.


l() is not being called correctly in menu.inc

According to my experience, this happens when the third argument passes to l() is not an array and you are using PHP 5.3. See http://api.drupal.org/api/drupal/includes%21common.inc/function/l/6 as to how the third parameter $options is being used.

Then it is time dwelve into what is causing your $parent['localized_options'] not to be an array.


Query and print out random nodes in drupal

Not sure where you are doing this, but this would be one dull ax way of doing it:

$query=db_query('SELECT nid, RAND() as _random FROM {node} WHERE status = 1 ORDER BY _random ASC LIMIT 1');
$result=db_fetch_object($query);

and then you can do whatever you want with $result->nid, another dull ax:

drupal_goto('node/' . $result->nid);

or

$node=node_load($result->nid);
// do whatever you want with it

etc


You may want to have a look how the field_collection module itself renders field collections in the field_collection_field_formatter_view function. I think it's important to note that is uses field_collection_field_get_entity() to load a field collection.

Looking at the code (not tested) I think you can do something like this:

if ($field_collection = field_collection_field_get_entity($line_item->field_paxsup['und'][0])) {
  return $field_collection->view('full');
}


The $string argument to t() should not begin or end with a space

The correct way of using variables in t() function is using placeholders.

Example of a correct usage:

$string = t('Role Limit @value', array('@value' => $value));

There are three types of placeholders for t() function.

@variable : The variable will be checked through check_plain() function before it is inserted, so you don't need to check it in your script.
!variable : The variable will be inserted as it is.
%variable : The variable will be checked through check_plain() and highlighted with drupal_placeholder()