How does Feeds decide if it is going to create a new (or update an existing) entity?

The Feeds module uses the FeedsProcessor object to define what it calls mapping targets for an entity to determine what fields are unique and what can be optionally be set unique in the feeds importer mapping settings UI. It then uses the method existingEntityId to determine if the mapping targets are unique.

In the case of users, the hook_feeds_plugins method for the feeds module tells feeds to use the class FeedsUserProcessor. This class has a method named getMappingTargets to say that the optional unique fields can be name and mail. In the mapping ui for the user feeds importer (admin/structure/feeds/user/mapping), you can set name and/or mail to be unique. The existingEntityId method in FeedsUserProcessor.inc determines if it has found a unique value. If so, and the importer is set to replace or update existing users, then the feeds record will be updated.

If you really wanted to work with telephone number as a unique field attached to a user, then you use implement hook_feeds_plugins, define your own FeedsProcessor and extend FeedsUserProcessor, and overwrite the getMappingTargets to add the field as an optional_unique entry, and overwrite existingEntityId to find other users with a matching telephone number.

However, it sounds like you don't need to do that. Make sure your user feeds import is set to update existing users, and that it is reading the csv file properly.

I went ahead and enabled telephone, installed the patch you mentioned, and was able to see a user be created, and then be updated with a different telephone number. My import file looked like this:

name,mail,telephone
demo,demo@demo.com,1234567890

and then this:

name,mail,telephone
demo,demo@demo.com,4567890123

And here is an export of the feed import:

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'user';
$feeds_importer->config = array(
  'name' => 'User import',
  'description' => 'Import users from CSV file.',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'direct' => FALSE,
      'allowed_extensions' => 'txt csv tsv xml opml',
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsCSVParser',
    'config' => array(
      'delimiter' => ',',
      'no_headers' => 0,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsUserProcessor',
    'config' => array(
      'bundle' => 'user',
      'roles' => array(
        3 => 0,
      ),
      'update_existing' => '1',
      'status' => '1',
      'mappings' => array(
        0 => array(
          'source' => 'name',
          'target' => 'name',
          'unique' => 0,
        ),
        1 => array(
          'source' => 'mail',
          'target' => 'mail',
          'unique' => 1,
        ),
        2 => array(
          'source' => 'telephone',
          'target' => 'field_telephone:url',
          'unique' => FALSE,
        ),
      ),
      'defuse_mail' => 0,
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);


Using searchapi module on a drupal multisite installation

You declared that searchapi is the solution but actually Solr Multisite can do this.


Failed opening required 'sites/all/modules/og/og.field.inc

Your file at least needs to have 755.

With 644 it is readable, but is not executable so the file cannot be managed as a php file (executable).


Inside drop-down menu child menus are not working

Bootstrap 3 and 4 have dropped support for nested (multilevel) menus

One has to include the relevant code (that was excluded) in their own custom theme to make it work.

Check this stackoverflow answer for relevant code to add to your theme

NOTE: the reason the support was dropped is that multilevel nesting is problematic in mobile or smaller screens so you have to implement solutions for small screens on your own.


Change font color in unsorted list in Views Drupal

Views supports tokens to generate CSS classes in the HTML output of a field. Below a screenshot depicting an example where I have added the fields 'Tags' and 'Title' from the default Article content type. In this way, the chosen taxonomy terms are added as CSS classes and you can apply the appropriate styling using CSS.

In order to see the list of available tokens in your View, checkout the section 'Rewrite results' -> 'Rewrite the output of this field' -> 'Replacement patterns' in the configuration screen of the field (you don't need to actually rewrite the output, however, this is the location where you can find the list of supported tokens for the particular field).


How to access from node template a field added by module

I managed to figure it out. I found a location in the module with this code.

function theme_featured_node_image($variables) {
  $fid = $variables['element']['#db_values']['image'];
  $file = file_load($fid);
  $url = file_create_url($file->uri);
  return theme('image', array('attributes' => array(), 'path' => $url));
}

Then I wrote

$file = file_load($featured_node[0]['image']);
$url = file_create_url($file->uri);
print '<img src="'.$url.'">';

Which allowed me to print the image.


Does Google crawl Drupal sites in maintenance mode?

When you put a Drupal site in maintenance mode, non-administrators see the standard maintenance mode page (assuming you clear caches after doing so).  If you examine the response, you will see that it is sent back with a HTTP status code of 503, which from RFC 2616 is:

  503 Service Unavailable
  The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

And from the Official Google Webmaster blog:

  If my site is down for maintenance, how can I tell Googlebot to come
  back later rather than to index the "down for maintenance" page? You
  should configure your server to return a status of 503 (network
  unavailable) rather than 200 (successful). That lets Googlebot know to
  try the pages again later.

So, that gives evidence that Drupal does the right thing, and that Google will revisit your site and index pages the next time it gets back a non 5XX status code.


How to translate inline entity form nodes (or, product variations in kickstart)

I'm not 100% sure on the setup, but I just finished a site that dealt with a similar circumstance. It uses String Overrides to perform targeted text changes, and if it doesn't support Internationalization by default then there's a module that provides additional tabs at /admin/config/regional/stringoverrides for each enabled language.

For reference, here's the translation module list currently enabled on the site:

Locale
String Overrides
Entity Translation
Entity Translation Upgrade
Block languages
Contact translation
Field translation
Internationalization
Menu Translation
Multilingual content
Rules Translation
Synchronize Translations
Translation Sets
Views Translation
Variable

Not all of these modules are required to make this happen, but perhaps you can compare your own setup to this list and find some differences. Apologies for not remembering how to set this up.

UPDATE :: Process for enabling translation within String Overrides

== Modules ==

Internationalization :: link | download
String Overrides :: link | download
Variable :: link | download

Enable Modules:

Locale
Variable
Internationalization
String Overrides
String Translation

Add a new language

/admin/config/regional/language/add
Select, click "Add language"

Add translations for alt language strings

/admin/config/regional/stringoverrides, click desired language in top right
Add rows for each desired string, place original language text in left box and translated string in right box
Save, view on front end

The final interface should look something like the following cap:


how to add a terms to a vocabulary by form?

Check this link taxonomy_term_save($term)


View Taxonomy Term List with Exposed Has taxonomy terms (with depth) filter

There is a issue as you ask the question.
The current answer is that Drupal 8 does not yet support this feature besides node content type.
I'm also following this issue.
more details at:
https://www.drupal.org/project/drupal/issues/2915933
https://www.drupal.org/project/drupal/issues/1040786


How to use the Time ago view formatter when you have an end date collected in your date field?

This not will solve the "realy" problem with the bug, but is a way:

If you are in a early stage of your project and you don't want use the patch you can delete the field and create two separated fields:

initial_date
final_date

I test it and this works fine.

If you want, you can read this: When should I use collect an end date for a field, instead of using 2 separated date fields?

I will add an explanation in the question about this bug.


How to add a custom icon or symbol to a flag link?

Option 1: Show an image beside the Flag text

You can use CSS to add padding to the left of the text and in it show a background image, as shown also in the community documentation about How to show an image beside the text. Here is an excerpt from it (replace "bookmarks" with the machine-name of your flag):

.flag-bookmarks a {
  padding-left: 20px;
}
.flag-bookmarks a.flag-action {
  background: url(images/i-dont-like-it.png) no-repeat left center;
}

.flag-bookmarks a.unflag-action {
  background: url(images/i-like-it.png) no-repeat left center;
}

Refer to the Flag Theming guide for (way) more details, i.e.:

Theming flag links using CSS, which provides a "map" of the HTML that makes a flag link.
Theming flag links using Templates, which explains how to use the flag.tpl.php file in the 'theme' folder that is located inside Flag's own folder, and which is used to generate the HTML for the Flag links. It also explains how you can theme different flags differently, using a flag specific flag--FLAGNAME.tpl.php file (whereas FLAGNAME is the flag's machine-name).
Theming examples, which contains solutions to some common theming tasks.

Option 2: Transform Flag link into a button

You can transform the Flag link into a button, by adding this CSS (quote from that link):

.flag-wrapper.{flag-name} a.flag-action {
  background-image: url('path to the button image');
  display:block;
  text-indent:-9999em;
}
.flag-wrapper.{flag-name} a.unflag-action {
  background-image: url('path to the button image');
  display:block;
  text-indent:-9999em;
}

Notes:

text-indent:-9999em hides the element (by placing it off the screen).
Replace .{flag-name} with your flag's machine-name.


Pathauto like pattern setting for creating menu link titles

You could use the Automatic Node Titles module to create the titles including the DEV string, which depending on your other settings could appear in the menu:

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

EDIT

You could also create a simple module to change the title of the nodes for the DEV content type:

Custom Node Title

  custom_node_title.info

name = Custom Title (DEV)
core = 7.x
description = Appends appropriate titles with DEV
package = custom

  custom_node_title.module

<?php
/**
*   Custom Node Title Module
**/

function custom_node_title_node_presave($node)
{
    /* only run if node type is correct and '-DEV' is not found in title to prevent duplication */
    if($node->type == 'article' && strpos($node->title, '-DEV') === false)
    {
        $node->title .= '-DEV'; /* add '-DEV' to title */
        $node->menu['link_title'] = $node->title; /* reset menu link to new title */
    }
}

In this example, it changes the title of an Article content type to include -DEV at the end.


how to migrate multiple taxonomy terms with entity lookup plugin

The field that you're migrating has multiple values and you're trying to run entity_lookup as though it has only one. I think you just need to make sure you're iterating over the values with the sub_process plugin.
Using this issue post as a reference, along with the docs for entity_lookup:
field_farbzuordnung:
    plugin: sub_process
    source: field_farbe
    process:
        target_id:
        plugin: entity_generate
        source: value
        value_key: name
        bundle_key: vid
        bundle: alle_farben
        entity_type: taxonomy_term
        ignore_case: true

...I think you'd want to do something like
field_states_operating_in:
    -
      plugin: sub_process
      source: field_states_operating_in
      process:
        target_id:
          plugin: entity_lookup
          source: target_id
          entity_type: taxonomy_term
          bundle: states_operating
          bundle_key: vid
          value_key: target_id

I'm not entirely sure that the source and value_key are correct but I think this should get you most of the way there.


If you know the store id and order type then

$store_id = 1;
$order_type = 'default';
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$entity_manager = \Drupal::entityManager();
$store = $entity_manager->getStorage('commerce_store')->load($store_id);
$cart = $cart_provider->getCart($order_type, $store);
$cart->get('total_price')->getValue()[0]['number'];


You have a few options. The quickest solution is to use views and take advantage of its quick and easy, powerful filtering capabilities. Views is a must in using drupal. If I was you and you are expecting to be heavily reliant on search then look into using search_api and views together to create some nice mashups.


How do I enable anonymous users to vote?

Looks like you need to enable the permission for anonymous users and also

Drupal core poll module only allows one vote per anonymous IP address. check this link https://drupal.org/node/866168

The Poll Enhancements Module modifies this behavior to allow multiple anonymous votes from the same IP address.

  This module enables anonymous users to vote on polls without page
  cache troubles or IP address restrictions. It is designed to work on
  top of core Poll module.


View of taxonomy terms that are used giving duplicates, even with distinct

Try using aggregation. Turn on aggregation and try Group Results Together on your term name field.


Registration email showing default mail message as well new custom message

$message['body'][] = $success_email_msg; is appending your variable to the existing array. You'll need to remove the default content from the $message['body'] array if you don't want it
e.g. unset($message['body']['whateverkey']) to remove a specific part. Or $message['body'] = [$success_email_msg]; to reinitialise the variable as a new array


Should I use underscore or hyphenated tokens?

Tokens are just arbitrary strings, Drupal doesn't mind which characters are used to indicate separation of words (some characters are blacklisted, like ], but for the most part that's true). All that matters is the module that provides them, e.g. Entity in this case, knows how to interpret them when it needs to.

The issue you referenced has two key core contributors debating it, without a resolution, so there simply isn't a standard to apply to this.

Both sets of token provide the same data, so it's a matter of personal preference which one you use.

Since the Entity module provides more field tokens than core modules do, you might end up standardising your site better over time if you choose the ones provided by Entity. But YMMV, in real terms it doesn't matter.


I have a solution. Install the Module Entity Reference, then create an multiple field wich is linked to the user Profile, at least you have to add a view to blogs/% and there you have to add an context filter wich filters to the field which refers to the Username.


Display a view of geolocation fields with lat lon on a google (or equiv) map

I used this sandbox module geolocation views with geolocation field module.
http://drupal.org/sandbox/xandeadx/1782036


Block visibility based on the content type

I would use the menu_get_object() function to determine whether or not the block visibility check is being executed on a full node page, then check the field value on the node from there.

EDIT

The other edits were getting a bit long so I've deleted them. I've just set up a site quickly to test this and the following steps have worked for me (this is Drupal 7):

Created a content type called Author Profile (machine name author_profile)
Added a node reference field from the Article content type to the Author Profile
Created an Author Profile node with a title of "vividvilla"
Created an Article node linked to the Author Profile node above
Enabled the core PHP Filter module
Created a block called Author Details with some dummy content in the body, choosing "Pages on which this PHP code returns TRUE (experts only)" for the block visibility settings.
Entered the PHP code below

<?php

$node = menu_get_object();

// Check we're on a 'full' node page.
if ($node && isset($node->nid)) {
  // Check the node is of the right type
  if ($node->type != 'article') {
    return FALSE;
  }

  // Load the author node based on the node reference field value.
  $author_node = node_load($node->field_blog_authors[$node->language][0]['nid']);

  // Check the title of that node
  if ($author_node->title == 'vividvilla') {
    return TRUE;
  }
}

// Default is to not show the block
return FALSE;

?>

The block only shows on an article page that is linked to an Author Profile with the title of "vividvilla" which I'm pretty sure is what you're trying to.

On the off-chance you're using Drupal 6 just change the $author_node = line to:

$author_node = node_load($node->field_blog_authors[0]['nid']);


Is it possible to add java script to webform?

An approach is to use hook_form_alter to alter the webform form and attach the custom JS.

/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webformCustomID')) {

    $form['#attached']['js'][] = drupal_get_path('module', 'custommodule') . '/custom.js';
  }
}

More info:

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7
Adding CSS and JS to form with attachments


In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned_node = $node->createDuplicate(). Calling $cloned_node->save() will save a new node with a different ID.


How do I create a custom search and filter?

I created a very easy month/year filter select box. For that I created a new form class which extends the FormBase class of Drupal 8.

To add filter and search inputs I added following values to the returning array:

namespace Drupal\my_sandbox\Controllers;

use Drupal\Core\Controller\ControllerBase;

class TestController extends ControllerBase
{

public function test()
{

    $form = [];

    //add you custom code here...

    $form['form'] = [
        '#type'  => 'form',
    ];

    $form['form']['filters'] = [
        '#type'  => 'fieldset',
        '#title' => $this->t('Filter'),
        '#open'  => true,
    ];

    $form['form']['filters']['text'] = [
        '#title'         => 'text',
        '#type'          => 'search'
    ];

    $form['form']['filters']['year'] = [
        '#title'         => 'Year',
        '#type'          => 'select',
        '#empty_value'   => 'none',
        '#empty_option'  => '- None -',
        '#size'          => 0,
        '#options'       => ['value1' => 'label1', 'value2' => 'label2'],
        '#default_value' => 'none'
    ];

    $form['form']['filters']['actions'] = [
        '#type'       => 'actions'
    ];

    $form['form']['filters']['actions']['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Filter')
    ];

    //place the table in the form
    $form['table'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => array(
        'id' => 'bd-contact-table',
      )
    );

    return $form;

}

}

The array for the key 'filters' is the container in which all the filter will be placed. I choose the type 'fieldset', you can change the type of container to any element you want.

Afterwards I added the search and filter input and at the end the button to submit the filter-form. If you use the a class that extends the FormBase class the form will be send the the submitForm method of your class.

A thing here to notice is that every "#type" key maps to Drupal element. All elements are located in the DRUPALCORE/lib/Drupal/Core/Render/Element folder. Example: The #type search will map to the file Search.php within the Element folder. Every file includes a comment where all options of the element are explained.

I hope I could help you.

Nicolas


How to embed edit user profile page in a panel

You need 1 context and 1 relationship to get the Form pane

Context: User => current user

Relationship:  User category edit form from user (default?)

and THEN you get the "Forms" category with "General form pane" under it


Common Custom PHP Library: Drupal 8 and Stand-alone Shell Scripts

It's possible to pull custom php libraries into your project with composer. You'll need to define the repository in the repositories section. Checkout handling private packages and repositories in composer's documentation. It's really fairly easy. If you have a single github repo you can include the repository info like below:

"repositories": [
    {"type": "composer", "url": "https://packages.drupal.org/8"},
    {"type": "vcs", "url": "https://github.com/myorg/mypackage"}
]

You should include a composer.json file in your repo as you'd probably expect. Here is a simple one to get you started:

    "name": "myorg/mypackage",
    "description": "My Package is the greatest!",
    "license": "proprietary",

    "autoload": {
        "psr-4": {"Myorg\\Mypackage\\": "src/"}
    }

Now your code can by placed in scr/Myclass.php with a

namespace Myorg\Mypackage;

Class Myclass {}

Choosing which version to pull in is a little but confusing. When you include a branch you need to prefix the branch nave with dev-, e.g. dev-master for the master branch. Otherwise, you can create tags and pull them in by their name, e.g. 1.0.0, etc. I've used this technique successfully with bitbucket.

Some inclusion examples where your composer.json in your repo defines your package name as myorg/mypackage:

// This will pull whichever branch is marked as the "default" branch in your repo
composer require myorg/mypackage

// This will pull the "develop" branch
composer require myorg/mypackage:dev-develop

// This will pull in the "2.1.3" tag
composer require myorg/mypackage:2.1.3

// You can also use "^" and "~" with tags
composer require myorg/mypackage:^2.1.0

You can tell composer where to put your package by adding a new item to the extra.installer-paths section of composer.json. For example, if you want to install your package to web/modules/custom add a line like:

"extra": {
    "installer-paths": {
        "web/modules/custom/{$name}": ["vendor:myorg"],
        ...
        "web/core": ["type:drupal-core"],
        ...
    }
}

If your repos are private, you may have some issues pulling your repo as a package. I've worked around this issue by using my ssh key for access to the repos and making sure anyone who runs composer require myorg/mypackage also uses the ssh key method.

An alternate technique is to create a zip release of your package and include it as a repository as the chosen module's README explains.


What is the relationship between hook menu() and menu_link_save()?

They're slightly different concepts to be honest; the items defined in hook_menu() are saved in the menu_router table, while menu_link_save() saves items to the menu_links table.

They come together in menu_rebuild():

hook_menu() is invoked through the menu_router_build() function to get a list of router items
The router items are saved to the database using _menu_router_save()
The menu links are generated/updated using _menu_navigation_links_rebuild(); the menu router items are passed to this function to build the links.
Finally the caches are cleared.

There doesn't seem to be any way to pass custom data from the router items to the links I'm afraid, and I don't think hook_menu() supports the sort of hierarchy you're trying to build natively.


printing drupal field in comment.tpl.php

I'm not positive about this, but maybe try removing the $content portion and rendering the field directly?

<?php echo render($field_profilbillede); ?>


How do I limit the maximum height of an image in signatures?

Under
Home >> Administration >> Site Configuration
Go to Signatures for Forums
Inside template for signature you can set the height inside the div as follows :

%s

Home >> Administer >> User Management

Go to Picture Support option and enable it

After that you will find a field Picture maximum dimensions: where you can set your image maximum height and width
 check the image link


View block listing nodes with lower/higher Nodequeue position

For sorting the nodes according to their position in a nodequeue follow these steps:

Add a relationship "Nodequeue: Queue".
You might want to select "Limit to one or more queues (recommended)" from the options provided and select appropriate nodequeue.
Save.
Click "add" in the sort criteria. Select "Nodequeue: Position"

Select ascending/descending depending on the positions.
Save.

And as for the other requirement that you posted "Current full node display"; I think this could be handled with adding the fields in the view, and controlling their display using JS.


Well as no one responded, I searched a bit and found a normal PHP function to achieve the same. I know it may not be a Drupal way, but its for them who are looking for a quick solution for now (like me). But would like to add that other answers to achieve this the specially the Drupal way is very much welcome. Also please note, I almost copy pasted the actual function, so you probably may want to modify that as per your UI (for actual function I have given the reference below) :

// This is the menu callback where $data are the records fetched to be displayed in this page, and $total_count is the total number of count of all the records.

$pager = pagination($current_page, $total_count, $record_limit, 2, "url-menu-page?page=%d");

$return_val = theme('my_callback_function', array('data' => $data, 'pager' => $pager));

return $return_val;

And here goes the actual pagination building function :

/**
 * Displays pagination links based on given parameters
 *
 * @param int $currentPage - current page
 * @param int $itemCount - number of items to paginate, used to calculate total number of pages
 * @param int $itemsPerPage - number of items per page, used to calculate total number of pages
 * @param int $adjacentCount - half the number of page links displayed adjacent to the current page
 * @param (string|callable) $pageLinkTemplate - pagination URL string containing %d placeholder or a callable function that accepts page number and returns page URL
 * @param boolean $showPrevNext - whether to show previous and next page links
 * @return void
 */
function pagination($currentPage, $itemCount, $itemsPerPage, $adjacentCount, $pageLinkTemplate, $showPrevNext = true) {
  $pager = '';
  $firstPage = 1;
  $lastPage  = ceil($itemCount / $itemsPerPage);
  if ($lastPage == 1) {
      return;
  }
  if ($currentPage <= $adjacentCount + $adjacentCount) {
      $firstAdjacentPage = $firstPage;
      $lastAdjacentPage  = min($firstPage + $adjacentCount + $adjacentCount, $lastPage);
  } elseif ($currentPage > $lastPage - $adjacentCount - $adjacentCount) {
      $lastAdjacentPage  = $lastPage;
      $firstAdjacentPage = $lastPage - $adjacentCount - $adjacentCount;
  } else {
      $firstAdjacentPage = $currentPage - $adjacentCount;
      $lastAdjacentPage  = $currentPage + $adjacentCount;
  }
  $pager = '

Pages

';
  if ($currentPage != $firstPage) {
    $pager .=  '
&laquo; first
';
  }

  if ($showPrevNext) {
      if ($currentPage == $firstPage) {
      //$pager .= '
< previous
';
      } else {
      $pager .= '
&lsaquo; previous
';
      }
  }
  if ($firstAdjacentPage > $firstPage) {
      if ($firstAdjacentPage > $firstPage + 1) {
      $pager .=  '...';
      }
  }
  for ($i = $firstAdjacentPage; $i <= $lastAdjacentPage; $i++) {
      if ($currentPage == $i) {
      $pager .=  '
' . $i . '
';
      } else {
      $pager .=  '
' . $i . '
';
      //$pager .=  "
$i
\r\n";
      }
  }
  if ($lastAdjacentPage < $lastPage) {
      if ($lastAdjacentPage < $lastPage - 1) {
      $pager .=  '...';
      }
  }
  if ($showPrevNext) {
      if ($currentPage == $lastPage) {
      //$pager .=  '
next >
';
      } else {
      $pager .=  '
next &rsaquo;
';
      }
  }
  if ($currentPage != $lastPage) {
    $pager .=  '
last &raquo;
';
  }
  $pager .=  '

';

  return $pager;
}

Hope this helps somebody...

Original code credit goes to the author of this blog : http://salman-w.blogspot.in/2014/04/stackoverflow-like-pagination.html


Use hook form alter to change input type

If you want alter a form via an ID check you should be using $form_id == 'uc_cart_checkout_form'. Drupal form generation functions don't use "-" characters like generated CSS id/class attributes.


How do I remind users to pick an avatar?

Profile Complete Percent helps to guilt users into filling their profile details. This isn't avatar specific, but you can configure the PCP block to only use a single field for its percentage calculation.


How to identify where a particular block come from?

The easiest way for Drupal 6 would probably be to use the Contextual links module.

  Hover over nodes, blocks, and views blocks to expose styled
  edit/configure/delete tabs.

It's a backport of the same functionality that is in D7 core, but for Drupal 6.

Just hover over the block on the front page, and hit edit to edit that particular block.


Taxonomy Access Control Change Default Behavior

One option I found was to use the hook_node_access this function has three inputs

$node The Node object on which the operation is done
$op The Operation being done on the Node could have three values view, update or delete
$account the user object.

The taxonomy access control stores the access information in taxonomy_access_term which has the following fields tid - taxonomy term ID, rid - the role ID, grant_view, grant_update, grant_delete, grant_delete, grant_create, grant_list

All the grant columns can have the following values

0=>Ignore
1=>Allow
2=>Deny.

Used the following function to override the hook_node_access

    function custom_node_access($node, $op, $account) {

        if ($op == 'view')
        {
        // Get all the tids into the $tids array
            $tids = array();
            $tids[] = $node->field_class[$node->language][0]['tid'];
            $tids[] = $node->field_subject[$node->language][0]['tid'];

        // Get all the role ids into the $roles variable
            $roles = array_keys($account->roles);

        // Create the query to get the `grant_view` with a value 1 if all the
        // roles have grant permission then the result would have 2 records.

            $query = db_select('taxonomy_access_term' , 't');
            $query->condition('t.tid', $tids, 'IN');
            $query->condition('t.rid', $roles, 'IN');
            $query->condition('t.grant_view', 1);
            $query->fields('t', array('grant_view'));
            $result = $query->execute();

        // if the result is less than two then we deny access other wise we
        // ignore it so that let the node_access control take over.

        if ($result->rowCount() < 2)
        {
                return NODE_ACCESS_DENY;
            }
      }
      return NODE_ACCESS_IGNORE;
    }

This works well node displays. But the problem would be that since the hook_node_access is bypassed by the list queries this will not work, Might have to add the node_access tag to all the queries which would become a performance issue.

The second method was to use the hook_node_access_records_alter and hook_node_grants_alter

the hook_node_access_records_alter edits the grant realms before writing it to the node_access table when creating or editing a node.

function custom_node_access_records_alter(&$grants, $node) {

  // Store the grants to a temp variable

  // create a new varible to store the new gid
  $gid = "";

  // Loop through the grants
  foreach ($temp as $key => $grant)
  {
    if ($grant['grant_view'])
    {
        // if the grant_view is set to 1 then append the gid
        // after adding a padding 0 to the left so that we get
        // a 2 digit number
        $gid .= str_pad($grant['gid'], 2, "0", STR_PAD_LEFT);

    }

  }

  // After completing this loop the new gid would look something like 040506
  // which means the role id 4, 5, and 6 has access to the page. and since we have
  // added it together we can make sure that it is individualy not valid
  // has to work together.

  // Rewrite the grant values with the new gid.
  if($gid_view != "")
  {
    $grants = array();
    $grants[0] = array();
    $grants[0]['realm'] = 'taxonomy_access_role';
    $grants[0]['gid'] = (int)$gid;
    $grants[0]['grant_view'] = 1;
    $grants[0]['grant_update'] = 0;
    $grants[0]['grant_delete'] = 0;
    $grants[0]['priority'] = 1;

  }

}

The next step would be to override the hook_node_grants_alter function.

function custom_node_grants_alter(&$grants, $account, $op) {

  // we only want it to work with the view.
  if($op == 'view')
  {
    $gid = '';

    // loop through the roles of the user
    foreach($account->roles as $rid => $role)
    {
        // we do not want the role id 2 as it is the id of the authenticated user.
        if ($rid >2)
        {
            // generate the gid we created in the hook_node_access_records_alter
            // so if the user has all the roles we set to the node then we would
            // get the same gid other wise the gid would be different and access
            // would be denied
            $gid .= str_pad($rid, 2, "0", STR_PAD_LEFT);
        }
    }

    // Over write the grants array.
    $grants = array();

    $grants['taxonomy_access_role'][0] = (int)$gid;

  }
}

Note : There are few assumptions made here

We only have the taxonomy access control module as access control module other than the core access control system. If there are more then we have to check and make changes to the function accordingly.
We are only checking for the view grants and not bothered about the rest of the grants.
Maximum number of roles that a user would have is 5. The gid is of the type int so it can accommodate a maximum value of 10 digit.
Each role would have only one allow per taxonomy term and rest of it would be deny.


View files from multiple (filtered) nodes

Here is a different approach, give this a try:

Ok, get rid off all the FILTER CRITERIA except for File: type = image
Under Advanced, add RELATIONSHIP of [Your Entity Reference Field
Name] make sure you select the one that says, "Referecing" and NOT "Referenced".
For your FIELDS File: name and Content: title, click on them and for
relationship select your Content Referencing Content from [Your Entity  Reference Field Name]

Under Advanced, add a CONTEXTUAL FILTER of nid.

Select provide default value
Content ID from url (This will automatically pick up the nid (node id) from the Band node/page.

Lastly, would be to add SORT CRITERIA and add the date field.


Custom links to switch language in Drupal 6

What doesn't work for you with the language switcher ?
If you want to reproduce its behavior, have a look at its code and try to do something equal.

Here is some code:

$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$languages = language_list('enabled');
$links = array();
foreach ($languages[1] as $language) {
  $links[$language->language] = array(
    'href' => $path,
    'title' => $language->native,
    'language' => $language,
    'attributes' => array('class' => 'language-link'),
  );
}
drupal_alter('translation_link', $links, $path);
//dpm($links);

foreach ($links as $link) {
  echo t('Link for ') . l($link['title'], $link['href']) . '<br />';
}


How to theme checkout completion page in Drupal Commerce

A quick google search yielded this result:

Templating the Commerce Order Completion Pane

  Turns out that's a fairly simple task thanks to
  hook_commerce_checkout_pane_info_alter. The function passes the
  variable $checkout_panes by reference which contains an array of
  checkout pane arrays. This function is going to allow us to redefine
  the function that the checkout completion pane is looking to for
  output.


Menus are not blocks, and as such cannot be placed in regions. Some themes don't render menus on their own, expecting you to place them in a region you prefer. Sounds counter-intuitive, but it can be solved.

To make menu a block, you can use Menu block module.

  It provides configurable blocks of menu trees starting with any level of any menu. And more!

Alternatively, you could use Nice Menus module:

  Nice Menus creates blocks that may be associated with any existing site menu which can be placed wherever normal blocks can be placed in a theme

Blocks the two modules are generating are different, but both can do the job. Test which one is better handled by your theme, and if both are good, use the one you simply prefer.


Allow user to request resend of activation email

First you need to create a custom form page using hook_menu() to allow users to enter their emails.

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

  $items['user/trouble'] = array(
    'title' => 'trouble logging in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_user_trouble_logging_in_form'),
    'access callback' => TRUE,
  );

  return $items;
}

Second, you need to create form structure

function custom_user_trouble_logging_in_form($form, &$form_state) {
  $form['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Mail address'),
    '#size' => 60,
    '#required' => TRUE,
  );

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Resend activation email'),
  );

  return $form;
}

Third, validation step (check if user email already registered)

/*
 * Validation function
 */
function custom_user_trouble_logging_in_form_validate($form, &$form_state) {
  $account = user_load_by_mail($form_state['values']['mail']);

  if(!$account) {
     form_error($form['mail'], t('Invalid user email'));
  }
}

Fourth, resend user activation email on form submission.

/*
 * Submit function for the 'Re-send welcome message'.
 */
function custom_user_trouble_logging_in_form_submit($form, &$form_state) {
  global $language;

  $destination = array();

  if (isset($_GET['destination'])) {
    $destination = drupal_get_destination();
    unset($_GET['destination']);
  }

  $account = user_load_by_mail($form_state['values']['mail']);
  $user_register = variable_get('user_register', 2);

  switch ($user_register) {
    case 0:
      $op = 'register_admin_created';
      break;
    case 1:
      $op = 'register_no_approval_required';
      break;
    case 2:
      $op = 'register_pending_approval';
      break;
  }

  $mail = _user_mail_notify($op, $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Welcome message has been re-sent to %name at %email.', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail));
    drupal_set_message(t('Welcome message has been re-sent to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail)));
  } else {
    watchdog('user', 'There was an error re-sending welcome message to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail));
    drupal_set_message(t('There was an error re-sending welcome message to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail)), 'error');
  }
  $form_state['redirect'] = $destination;
}

Note: custom_user is the name of the module that I used. You can change to whatever you like.


Specific node is being attacked by spam comments. What do I do to prevent it?

If you don't care if nobody can comment on that node anymore, you could disable comments for that node. Go to the edit form and below "Comment settings" (assuming D6, slightly different in D7 but basically the same thing) change the value to "Read only" or "Disabled".


Creation of products completely except the admin

One option is to use a custom node bundle along with Rules. Allow the users to create the new node type. Then, when the node is being saved, use Rules (or a custom module) to take the values that were entered into the node form and carry them over to a product and save it.


SSESS Cookie (Session ID) is being changed when loading images that don't exist

I finally found out what was the exact problem in my case:

I had varnish which per default, strips all cookies from the request to images. So when an image style is called, the request won't get any cookies and is thus an anonymous request.
The image is not present, so PHP is called to generate it.
A custom module invokes code that includes private tempstore (via Event listener but could also be hook_init() or something similar).
The SessionStorage is not aware that there was already a session because varnish stripped the cookie away. It therefore just started a new session (with the same cookie name but with another value). That was the return cookie.

At least it's solved now. An alternate way could also be that varnish could also filter all returned cookies, but this has to be configured / coded in the varnish config.


Setting base_url in a multidomain setup?

I guess you need separate settings.php file for each site.
You can create special folder for each domain in your sites directory and set custom $base_url in each settings.php file.

.
+-- all
¦   +-- modules
¦   +-- README.txt
¦   L-- themes
+-- default
¦   +-- default.settings.php
¦   +-- files
¦   L-- settings.php
L-- de.mysite.com
    L-- settings.php
L-- ru.mysite.com
    L-- settings.php

Documentation about site folders: http://drupalcode.org/project/drupal.git/blob/c5d6e6334fb7a71ecf1dbc7e06a7de8ad9547b27:/sites/default/default.settings.php#l25


Allow HTML style attribute for filtred HTML

go to admin/config/content/formats/filtered_html

In the limit allowed HTML tags, add the tags that you need. You could view source to see what tags are being added when you're trying to font-size and text align and then add them here.

go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

Then under Advanced Content Filter, select disabled.


How to select multiple values for Drupal Facets (Facet API + Search API)

I found the first comment here to answer this question.

  the OR operator is required for the facet instead of the default AND.
  If the implementing search module you are using supports OR facets,
  you will have an option in the "Global settings" fieldset located in
  the bottom left hand corner of the facet's display settings form.


Modal form with CTools opened in several different pages

I have finally solved the problem and now everything works: the modal window, the form and the submit, sending the email in final step. The problem was that the raw URL included the class ctools-use-modal-processed and apparently that simple css was making it not work. Now more or less understand the process, thank you for your help, it has been very valuable.


Solved. I modified the page views to use a static path and then set up a contextual argument to grab the parameter of the url to use as an argument.


How do I resolve this conflict between two Feature modules?

Create a third Feature defining the components(*) used by the other two independent Features.

In the other two Features, remove the components which are now claimed by the third Feature, and instead, list the third Feature as a dependency.

(*) In Features for Drupal 7, however, this functionality isn't yet committed — see http://drupal.org/node/1064472, and help review the proposed code there. — This patch has been committed to Features 7.x-2.x.


Display the value of a field list in views

In your view, click on the field, under Formatter select 'Default'.


Programmatically alter custom checkout panes depending on cart quantity

It occurred to me there may be a nice way to do this with contrib so I'll put it down, but it does require different pieces playing together nicely, which doesn't always happen (:

I see twothree clean approaches.

Using the Field API and contrib

If you want to use the Field API to create/update/delete fields, then I still think you should use custom line item products. I'm a little surprised it doesn't have the option of displaying the form at checkout built-in. Maybe a module will be built to add that, it should be relatively simple. But in the meantime this might get you there with existing contrib:

Install editablefields and Commerce Views Pane.
Create a custom line item type for the customisable product. Add the necessary fields but don't configure them to show up on the add-to-cart form. Also ensure the line items can't be combined.
Create a line item view that accepts an order ID as an argument, and add the fields you'd like to edit (and give them the editable formatter). Add a filter to ensure it only displays line items of the correct bundle. You can test the view in preview by creating a new order with a few customisable products, find the order ID (eg. from the checkout page), and pass that order ID to the Views preview. It should show you a row for each customisable line item. I wouldn't try to get the Views pane working until it works in preview.
Add that view as a checkout pane.
Make a circle of salt around the server and whisper a prayer.

Using the Field API and combined line items (involves code)

If you'd like to have a single line item have multiple customisations, then you need to set up the fields to allow that.

Create a field collection with the fields you'd like.
Add a multi-value field collection of that type to the appropriate line item type (ensure it won't show up on the add-to-cart form).
Create your own checkout pane that displays the field edit form. You'd read the quantity from the line item and display just that many fields (as it's a multi-value field it'll save ok however many there are).

Creating a custom pane and storing data serialised with the order (involves code)

This has the disadvantages that you can't use the Field API to set up, modify, or read the fields (so no Views). checkout_pane_example.module shows how to do this, adding a nickname and second email field and storing the data with the order.

Ugly method

I think you could probably do it with Commerce Fieldgroup Panes if you create a field collection with the fields you want, and then add it as a multi-value field to the order entity. You'd need some code to ensure only the correct number of field collections are shown (to match the number of line items that need customising). This method feels dirty and has two concrete drawbacks I can think of:

As you add more customisable products the order entity will get more and more fields.
You can't associate the customisations with a particular line item (what if I want a want one message on my red sweater, and a different one on my blue sweater - which message goes with which line item?).


Doctrine annotations for custom field formatters in Drupal 8

I confused PHP array syntax for annotation syntax. Those => should be = and the trailing commas need to be removed from lines that are the last in their set. So it should be:

    /**
     * Plugin implementation of the 'views_hybrid' formatter.
     *
     * @FieldFormatter(
     *   id = "views_hybrid",
     *   label = @Translation("Views hybrid"),
     *   field_types = {"entity_reference"},
     *   settings = {
     *      "items_count" = "5",
     *      "view" = "frontpage",
     *      "display" = "linked_title_only",
     *      "classes" = {},
     *      "view_mode" = "teaser",
     *      "arguments" = ""
     *   }
     * )
     */


Why is my table not automatically created at the time of custom module install?

The following line is not correct.

'primary_key' => array('id'),

Replace 'primary_key' with 'primary key'.

In Drupal 7 you do not need to call drupal_install_schema() nor drupal_uninstall_schema() for the database tables your module uses.

You can just declare the functions.

function drupalform_install() {}

function drupalform_uninstall() {}

Just update the code, uninstall the module, and re-install it.


How do I compare fields in a database query?

You must use where(), like this:

$query = \Drupal::database()->select('mytable', 't')
  ->addField('t', 'myfield1', 'myfield1')
  ->addField('t', 'myfield2', 'myfield2')
  ->where('t.myfield1 = t.myfield2');


Ok, I've found this: Flex Slider, this seems works on my android smartphone


Omega Theme Renders a Container inside of a Container

Yeah, I have seen that before with Omega 3 - its presuming too much :)
What you can do to work around this, is get the node template file, and create a template file for a teaser mode, and reference it in template.php. One sample of doing that is here: What is the template suggestion for node 'teaser' view mode?


How to configure drupal-nodejs with https?

Go to /admin/config/nodejs/settings and select https.

Then scroll down a bit to javascript and also select https here.


Is there a way to show a node's comments when displayed in teaser format on the taxonomy term page?

Associate a custom node to each taxonomy term.

Create a content type of "taxonomy term page" with comments enabled.
Add a custom field of type "taxonomy term".
Create a View, with a display of type block. Add to it a contextual argument of type taxonomy, and specify from where in the URL path is the argument going to be found. This should filter out nodes based on the current taxonomy found in the URL path. For safety, add a content type filter (regular, non-contextual), and specify "taxonomy term page".
Change the render type from "fields" to "node", or something like that. Try to see if in the node display option, you can choose to render comments as well.
Using Context, add a condition for taxonomy/term/* paths.
In the same Context, add a reaction of type block. Browse and select your block. Add it to the desired region. Save.
...
Success!

I tried to suggest the "easiest" option, which was using Views. If however for some reason Views won't allow you to render a full node view - with comments enabled - then you will need to create your block programatically using hook node view. But you still get the idea. The purpose is to take advantage of the existing comment-to-node architecture to avoid writing custom code as much as possible.


For a non-english single-language site, is it still best practice to write t()-strings in the theme in English?

If you're 100% sure that you do not need to (re-)use this code in a multi-language environment, now or in the future, you're safe using foreign language strings. Personally, I consider it best practice to always use t() because you never know what's going to happen in the future.

Be aware that strings in code that are run through t(), are assumed to be in English, so you have to choose between t('English text') or 'Svensk text'. Never use t('Svensk text').


Enable the LDAP Query module and run your own query like below.

//Lets say you have the user details loaded here
global $user;

$ldap_query = new LdapQuery('ldap_user_query');
$ldap_query->baseDn=array('DC=CORP,DC=AD,DC=YOURCOMPANY,DC=com');
$ldap_query->sid='corp.ad.yourcompany.com';
$ldap_query->qid='ldap_user_query';
$ldap_query->name='ldap_user_query';

//Enable the Query.
$ldap_query->status=1;

$ldap_query->filter='(&(objectClass=user)(name=' . $user->field_full_name[LANGUAGE_NONE][0]['value'] . '))';
$user_data = $ldap_query->query();

//use the user data to update other fields.
dsm($user_data);


drupal remove individual paragraph tags of the tokens of my replacement patterns in a View

You could uncheck the standard style settings for "add default classes" for each field.

This should place both tokens in one paragraph if you rewrite them in another field (e.g. global custom text).


Does drupal_add_css not load duplicate filenames by design?

Looking at the drupal_add_css() function, it seems this behaviour is by design.

For any CSS that you add using the function without using 'inline' as an argument, the array of files is keyed by the first argument (string) that you pass in. So if you were to run:

drupal_add_css('file.css');

And another module has also called drupal_add_css() with the same file name, the original will be overwritten.

As Marius Illie mentions in a comment above, the best way to avoid this is to prefix any CSS files you add with your module name.


Accessing data on Drupal with external application

Yes, you can use module Views to create content listings (http://drupal.org/project/views) with Services (https://drupal.org/project/services) and combine them to web services with the content listings using Services Views module (https://drupal.org/project/services_views).

Also, look at Drupal iOS SDK (https://github.com/kylebrowning/drupal-ios-sdk) for some basic already implemented connectors from ios to drupal. (Retrieving specific single user/piece of content, retrieving already mentioned views etc...)

I would start with downloading and enabling the modules, understanding views (https://drupal.org/node/1911062), then read the documentation for services (contained in the module)


For both level and date (I understand these are session, so a range of date), you can add some "select list" in order to let the user select between the available options.
Do you have troubles adding this ? Can you make your question a little clearer regarding what you want and what causes you difficulties ?

Select the "listbox" option and it will produce:

Edit June, 23:

so you have a Content Type named "webform_info" with some fields "field_level" and "field_time".
the idea is to implement a hook_form_alter (in a custom module) to retrieve these fields and put them in the webform

    <?php
    function custom_form_alter(&$form, &$form_state, $form_id) {
      //you need to set up a custom module to store this.
      //use devel with dsm($form); to figure the name of each field
      if ($form['#id'] == 'webform-client-form-123') {
        //delete the array of options from the webform field, they start by "con_"
        $form['submitted']['con_level']['#options'] = Array();
        $form['submitted']['con_level']['#options'][''] = '- Select one level/time -';
        $i = 1;

        //retrieve the nodes of the type webform_info
        $result = db_query("SELECT nid FROM {node} n WHERE type = 'webform_info' AND status = 1");
        while ($row = db_fetch_array($result)) {
          $node_level = node_load($row['nid']);
          $form['submitted']['con_level']['#options'][$i] = $node_level->field_level[0]['value'] . $node->title . $node_level->field_time[0]['value'];
          $i++;
        }
      }
    }
    ?>

Doing node_load can be pretty heavy if you have a great number of nodes, so you might want to use the CCK table structure, have a look at another answer to adapt the code.
Code is for D6 but should give you some insights to apply this to D7 if needed.


How to show different content for various roles for the same url?

Sounds like either the Content Access module, the ACL module, (maybe) the Nodeaccess module, or possibly even a combination thereof, would be a good place to start.


db_query() and db_select() don't return any value

$get_counter_info->execute()->fetchAll();

will execute the query...but what are you doing with the results, exactly? At the moment you're discarding them, instead you need to assign them to a variable.

$results = $get_counter_info->execute()->fetchAll();
foreach ($results as $result) {
  ...
}

Or at the very least actually use the return value from the execution:

foreach ($get_counter_info->execute()->fetchAll() as $result) {
  ...
}


What is the difference between the classes ArchiverTar and Archive_Tar?

The Archive_Tar class is a very-slightly modified version of the PEAR library Archive_Tar. ArchiverTar can be thought of as a wrapper to that library. However, depending on what your module is trying to achieve, you will probably want to call archiver_get_archiver(), since this is agnostic of the specific archive format (the system module supplies tar and zip, and your module could provide additional formats using hook_archiver_info()).


A way to choose a block title's format (HTML tag)

I know you are asking about D7, but you are missing a key point about templates.  I'd take a gander at http://drupal.org/node/104319 which talks in great detail how D6 does it so you can how it can look at different block templates and then think about whether you need to create a module that has a configuration page for its blocks like what you have above or whether block location is enough.


How do I change the permalinks to #1, #2, #3?

Advanced forum provides what you are looking for out of the box (a #number permalink in the upper left corner of the post) among tons of other useful features for a forum.

You could either simply use that module, or you could look at it's template files to see how it's done. The relevant code seems to be in includes/advanced_forum_preprocess_comment.inc and looks like this.

  /* Linked post number */
  if (!isset($post_number)) {
    static $post_number = 1;
  }

  $posts_per_page = variable_get('comment_default_per_page_' . $node->type, 50);

  $page_number = !empty($_GET['page']) ? $_GET['page'] : 0;
  if (!$page_number) {
    $page_number = 0;
  }

  $post_number++;

  $linktext = '#' . (($page_number * $posts_per_page) + $post_number);

  // Permalink
  //  You can erase next 3 lines if you wish to use built-in Permalink.
  //  Template adjusted: $post_link -> $permalink
      $uri = entity_uri('comment', $comment);
  $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  $variables['permalink'] = l($linktext, $uri['path'], $uri['options']);


Edit your comments.tpl.php file and delete the <?php print render($content['links']) ?>

Then all you gotta do is create your own reply, edit, and delete links

reply is /comment/reply/[nid]/[cid]
edit is /comment/[cid]/edit
delete is /comment/[cid]/delete

So use PHP to load the nid and cid and replace the [tokens] with your PHP code.

Then use PHP if statement to check whether login (global) user is of role x, if true, you print the reply link.

For edit and delete links, you check if login (global) user uid is the same as comment author uid.


Change function view_unformatted to work with format HTML list

I think the hook name you are looking for is template_preprocess_views_view_list that applies to HTML list views.


How to rearrange user register form and still pass validation

I would try defining the name of the field manually like so. This should overwrite the default naming of the variable in the values/input array in the $form_state.

$form['profile_supplier']['account']['#name'] = 'account';


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

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

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

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

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

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


How to prevent displaying the theme on a custom page callback in hook_menu()

Simply don't return any value, and exit.

In Drupal 7, that can be done by calling drupal_exit(). In Drupal 6, you use code similar to the following one:

function custom_callback() {
  echo 'success';
  module_invoke_all('exit');
  exit();
}

When you call drupal_exit() you don't need to use exit too, as it is already used by the function.

exit() (or drupal_exit()) avoids other hooks are invoked after hook_exit().
Drupal normally calls drupal_page_footer() after the menu callback returns its value; using exit() (or drupal_exit()) avoids that function is called, too. The effect is that the output of the menu callback is not cached. If caching the output is desired then the call to module_invoke_all('exit') and exit(), or drupal_exit() can be removed. As far as the menu callback doesn't return any value, the Drupal page will not be rendered, as it is evident in the Drupal 6 code contained in the index.php file:

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_page_footer();


How do I select a table using a variable with db_query()?

This is one of the reasons the new query builder exists in Drupal 7, so you can dynamically substitute parts of the query:

$table_name = 'the_table';
$field_name = 'a_field';
$query = db_select($table_name)->fields($table_name, array($field_name));

Using db_query() you only get parameter replacement, which would only be applicable to substitutions in WHERE conditions. This means that you cannot use db_query() to replace table names, the names of fields selected, etc., only WHERE conditions.

Have a look at the db_select() docs for more in-depth examples, including how to add conditions to the dynamic query.


Yes, it's possible. You have to change the "Weight". If you put a weight greater than the other menu links, the last will appear below.


How to set readonly or locked a select webform field?

Not sure how much this is a helpful answer, but was looking for a recipe to do this and found this example using a simple little hook_form_alter (which happens to be for civicrm components in a webform but think the principle is what counts)

$form['submitted']['civicrm_2_contact_1_fieldset_fieldset']['civicrm_2_contact_1_relationship_relationship_type_id']['#disabled'] = TRUE;


How to load a customer profile from address module

you can try get profile by order and can try the code below:

$order_id =1;
$entityManager = \Drupal::entityTypeManager();
$order = $entityManager->getStorage('commerce_order')->load($order_id);

get address by field billing_profile

$address = $order->billing_profile->entity->address->getValue();


Drupal allows content to go onto your site, such as a Page or Book through a content type. If you want to show a Page or Book and embed a field or form on that page that is backed by a database -- typically you have to use another module for that which allows you to embed Forms onto existing Page (Node) content.

To do this usually you can use 1 of the following modules:

Webform

  Webform is the module for making forms and surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has an extensive API for expanding its
  features.

  Some good examples could be contests, personalized contact forms, or
  petitions. Each of these could have a customized form for end-users to
  fill out. If you need to build a lot of customized, one-off forms,
  Webform is a more suitable solution than creating content types and
  using CCK or Field module.

or

EntityForms

  The Entityform module enables you to create front-end forms (fieldable
  entities), which contain fields that you define! These forms use the
  standard Drupal fields. This means that out of the box, you can use
  any standard Drupal node field!

These modules allow you to embed any form you define through their admin interface into existing page content.

A key difference is in these forms is that Webforms stores its own data in a custom backend difficult to make into drupal (page) content on your website. While EntityForm since it uses Drupal Fields -- it's submitted content may easily be turned into Drupal site content (but need not be).


Validation and Setting value for Multi-value fields

Clearly, for any multi-value field there is a delta value inside each fields' table in Drupal Database, which corresponds to the index of the value for that entity instance.

According to this knowledge, the structure of the form_state variable for a multi-value field with two values (e.g. X and Y) is:

[field_FIELD_NAME] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => X
                                    [_weight] => 0
                                )
                            [1] => Array
                                (
                                    [value] => Y
                                    [_weight] => 0
                                )

                            [add_more] => Add another item
                        )

                )

[0] and [1] are delta values for each value of this filed in the corresponding entity instance. For setting the values of a multi-value filed in FORM submit/validate hook, you should do as follows (consider again we have two values X and Y):

$form_state['values']['field_FIELD_NAME']['und'][0]=array("value"=>'X',"_weight"=>0);
$form_state['values']['field_FIELD_NAME']['und'][1]=array("value"=>'Y',"_weight"=>1);

The above lines ought to be written inside the VALIDATE hook.

For reading values for validation, do as follows:

$values=$form_state['values']['field_FIELD_NAME']['und'];

foreach ($values as $key => $value) {
  if($value['value']...
}


In Drush 9, the command is drush user:password USERNAME "SOMEPASSWORD"; its aliases are user-password and upwd.

In Drush 8 (and earlier) the command is drush user-password USERNAME --password="SOMEPASSWORD"; its alias is upwd.


Is it possible to make a patch that modifies a module's composer.json?

This issue is actually addressed in the composer-patches documentation:

Because patching occurs after Composer calculates dependencies and installs packages, changes to an underlying dependency's composer.json file introduced in a patch will have no effect on installed packages.
If you need to modify a dependency's composer.json or its underlying dependencies, you cannot use this plugin. Instead, you must do one of the following:

Work to get the underlying issue resolved in the upstream package.
Fork the package and specify your fork as the package repository in your root composer.json
Specify compatible package version requirements in your root composer.json

If you want to follow option #2, you can fork the project's git repo, modify it, and add the forked repo to your project's repositories property:
    {
        "type":"git",
        "url": "https://github.com/vendor/module"
    }

So you can reference that dependency until the upstream has resolved the issue.


Installing on IIS 7/Windows Server 2008 R2/MSSQL 2008

phpmssql library missing

You are using the 8.x-2.x branch of the driver, that relies on a paid external library phpmssl:

http://www.drupalonwindows.com/en/content/phpmssql

You can use the "free" 8.x-1.x branch - that has no dependencies - for evaluation purposes. I say evaluation because it's a non supported half-broken branch I used to work on during the first D8 port attempt of the driver.

You can find full discussiones of this issue here:

http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows

Disclaimer: I'm the maintainer for the SQL Server driver, PHP Mssql and Wincache.


Aggregator module block shows up only to registered users

Have you checked the role permissions on the blocks? On block layout, you should be able to click on Configure. This should take you to the administration screen for the block in question. There you should see a tab layout with an option for Roles. Do you have items there checked?


Why are the commands implemented by a custom module still listed after uninstalling it?

Problem solved. Issuing drupal module:uninstall my_module removes the command from the Drupal Console command list.


Fatal error: Call to a member function extractFormValues() : Drupal 8 beta 14

This question is old but I stumbled across this issue as well, so posting the solution for future googlers..

Basically, you need to init the form_state within the buildForm method with:

if (!$form_state->has('entity_form_initialized')) {
  $this->init($form_state);
}

I found this solution here: https://withpulp.com/blog/drupal-forms-api/#initialize-the-form-state

When extending the ContentEntityForm class the parent buildForm normally handles this for you, but if for some reason you choose not to extend the buildForm you will need to init the form_state yourself.


Only display profile edit button on personal profile page

Found the answer in access the user associated with a profile.

It was simply THEME_preprocess_profile.


You can change the way the html is genereated for a field by overwriting the apropriate theme method.

Tho find the method you can use the theme developer module. After enabling the module you can click on the appropriate field to see the theme methods which are important for you.

Have a lookg at the themeing giude if this is all new for you.


Why doesn't $row->path output its value?

It is a known issue with views_php.  You should be able to access the field information through the $data variable though. If you have Devel installed just run dpm($data) in place of your code above and see how to access the field information.

For what it is worth, it is generally considered bad practice to store php code in the database. I would suggest taking a look and seeing if there is any way you can accomplish what you are after with a template file override or some other means.  If the only thing you are trying to accomplish is concatenation of those 3 fields with labels, you can do that with a regular views 'custom text' field and the tokens views provides.


To create a view of comments for a particular content type, what you have to do is create a new view and select Comments in 'Show' select list as shown in the pic :

After that go to Filter Creteria section and select the particular content type to which you want to show the comments. Also select the Comment: Approved(Yes) filter creteria.


How do we make the date field default to today's date?

If already date field created follow the below steps to change the date formate:

Goto particular Content type, which you have created.

admin/structure/types/manage/{CONTENTTYPE_MAHINE_NAME}

click on the 'Manage Fields' form the tab menu
click on the 'edit' button on the date field of the content type. The field settings will open, the link will be

/admin/structure/types/manage/{CONTENTTYPE_MAHINE_NAME}/fields/node.{CONTENTTYPE_MAHINE_NAME}.field_{FIELD_MACHINE_NAME}

Goto bottom of the page

Select the 'Current date' option from the drop down at the section of 'default value'.
To display only the date without time, goto 'Field settings' and select the 'date only' option from the drop down of 'Date type'.


The geographic data (latitude, longitude) isn't saved in content

Geofield module doesn't work without the GeoPHP library. You need to download both the module and the library and place them in the correct locations in order for the module to work.
When using Composer to install Drupal and modules the library is automatically downloaded to the correct place.
If you're not using Composer you can do that process manually. You probably already downloaded and installed the module Geofield in the common location /web/modules/contrib.
Now you have to download the GeoPHP library, you probably want the latest stable version, from the page noted on the Geofield documentation: https://github.com/phayes/geoPHP
The library is compressed, so you need to extract the archive file to get the folder with the library files. Then place that folder in your Drupal installation, usually in /vendor folder that is within Drupal root folder, so you end up with something like /vendor/geophp/ (I haven't checked the exact path and name).
Check the Status Report that the library is available and read properly by Drupal. Sometimes you need to adjust the library file permissions or ownership so Drupal can use it but I don't expect problems in cPanel.
Not using a Composer makes maintaining your site more difficult. You'll have to do updates manually and check for all dependencies yourself.
If you can invest a bit of time and use your computer for development you should install Composer and use it to build your Drupal site. Then just upload the resulting files to cPanel to host your site, but always keep a local copy with Composer to do the updates and maintenance.


State field in Civicrm profile display as digit

Check the table:

civicrm_state_province

specifically the column abbreviation for malaysia. If i had to guess, all the abbreviations are numeric and hence u r seeing numbers.

You can use PHPMyAdmin to find the relevant rows for malaysia. Your short term fix will be to populate the right values. Would be even better for you to submit a PR against civi-core so that changes get incorporated into future versions


Hiding the field label when creating a content type

Please go to admin/structure/types/manage/[your-content-type]/display

And you can hide labels accordingly.


Going over 255 means that field can not easily be indexed and thus if you filter on it in views or in a query it will be slow. As long as you stay below this limit all is well.


How to embed videos using the video module?

If you install the WYSIWYG module, you can enable a button for embedding videos that have been uploaded using the Video module, and then you can use that button to embed videos into content.


Looks like $form['taxonomy'] is not an array.

There are some options for hierarchical selects maybe this is all you need:

http://localhost/admin/config/content/hierarchical_select


Composer issue after I deleted the vendor directory

Resolved the issue:

$ composer selfupdate

Updating to version 1.10.5 (stable channel).
   Downloading (100%)
Use composer self-update --rollback to return to version 1.6.2

Appaprently, my version of composer was too old.


How to set properties for a specific chart only using the views integration of the Charts module?

No, not in the charts module, in a custom module of your own.

It is also possible for you to use drupal alter hooks from your theme's template.php file however you should be careful what you put in your theme.
You should only put code relating to visuals in the theme, if you are doing more functional code it should go in a module.

A good rule of thumb is whether or not you would want to keep that functionality if you ever changed themes. If you would want to keep it then that is a possible indicator that it is functional, not visual, and should be in a module.

.api.php files are files that give developers information on the function and hooks that a module makes available to others.

It is basically just documentation so you editing it will do nothing (except for then making that documentation incorrect, which is bad if anyone else wants to use it).

Some reasons why it is generally not a good idea to modify the module itself can be found at Why don't we hack core? (it is talking about drupal core but the same goes for other contrib modules and themes).
One of the main reasons we have drupal hooks is so you don't have to modify the original module if you want to make changes.

So you would create a custom drupal module and then in that module implement the hook like this (changing MODULENAME to the name of the module and the chart ID to match the ID of your specific chart):

/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function MODULENAME_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

There are lots of other drupal module development resources besides drupal.org docs too. There are some good affordable textbooks and some paid training type websites, as well as a scattering of blog posts in random corners of the internet.

Here is a more functional example of using the definition alter hook.

/**
 * Alter an individual chart's raw library representation.
 *
 * This hook is called AFTER hook_chart_alter(), after Charts module has
 * converted the renderable into the chart definition that will be used by the
 * library. Note that the structure of $definition will differ based on the
 * charting library used. Switching charting libraries may cause your code
 * to break when using this hook.
 *
 * Even though this hook may be fragile, it may provide developers with access
 * to library-specific functionality.
 *
 * @param $definition
 *   The chart definition to be modified. The raw values are passed directly to
 *   the charting library.
 * @param $chart
 *   The chart renderable. This may be used for reference (or read to add
 *   support for new properties), but any changes to this variable will not
 *   have an effect on output.
 * @param $chart_id
 *   The chart ID, derived from the $chart['#chart_id'] property. Note that not
 *   all charts may have a $chart_id.
 */
function THEMENAME_chart_definition_alter(&$definition, $chart, $chart_id) {
  // For the portfolio charts.
  if ($chart_id == 'MY_CHART_ID') {
    $definition['legend']['borderRadius'] = 0;
    $definition['legend']['borderColor'] = NULL;
    $definition['legend']['style']['fontFamily'] = 'Helvetica,Arial,"Nimbus Sans L",sans-serif';
    $definition['legend']['backgroundColor'] = 'transparent';
    $definition['legend']['layout'] = 'vertical';
    $definition['legend']['verticalAlign'] = 'top';
    $definition['legend']['padding'] = 0;
    $definition['legend']['margin'] = 0;
    $definition['legend']['itemStyle']['color'] = '#555555';
    $definition['legend']['itemStyle']['fontSize'] = '12px';
  }
}


How can I target the first item in a view?

One possible solution ist to create two views. One for your featured content (only 1 item or as much you want to feature) and the second one for the rest with an offset. You can set the offset under pager options (items to skip).


The libraries are loaded by weight, not in the order they are defined.

You already had figured that out. You have set a weight of -400 for the external library. This will be the first library loaded, because in drupal the lowest weight for a library is -22. But most times you would want to be above -20, because this is the weight of jquery, on which most libraries depend.

The problem in your case is, that the library mylib.js is specified to be loaded in head. So the external library will never be able to come ahead. It's loaded at top of all other libraries because of the low weight, but still with the bunch of all the other libraries at the end of the document.


If it's a permissions problem you should go to the People tab at the top of your nav bar. Then under People click on "Permissions" and see if you can find the permissions for the image field and give other users permission there.


Last I checked, Webform didn't pick up a title token.

But it is possible to send the page's url in an email by using the %server[key] token.

For example, in the Webform tab > e-Mails subtab > E-mail template, include:

http://yourdomain.com%server[REQUEST_URI]

See this page for more info.

EDIT: This comment may have a full solution


How to make a content visible only in the corresponding language it has been created on a multilingual website

Entity Translations can be configured so that when it doesn't find content for a field in a language, it uses the content of the default language if any is available. If you're in an English page and a field is missing content, it may pick up the French content.

This can be disabled in /admin/config/regional/entity_translation by unchecking the "Enable language fallback" checkbox. When disabled, fields that have no content will simply not appear and won't fall back to the default language's content.


How to setup custom breadcrumbs with taxonomy?

Not sure if this is the best solution, but you can do that always with theme_breadcrumb() function in your theme like this:

function YOUR_THEME_breadcrumb($vars) {
    $breadcrumb = $vars['breadcrumb'];
    if (count($breadcrumb)) {
        if (arg(0)=='taxonomy' && arg(1)=='term') {
            $term = taxonomy_term_load(arg(2));
            if ($term->vid==YOUR_VOCABULARY_VID) {
                $breadcrumb[] = l('Your landing page', 'landing-page-url');
            }
        }
        return '

'.implode('&raquo;

', $breadcrumb).'

';
    }
}

I'm assuming you're using D7.


Multiple modules extending form in OOP way, with no hook_form_alter()

Good question. The alter hooks will eventually be replaced, not by extending form classes, but by symfony events. Events are coded in OOP and they have a proper priority handling. See https://www.previousnext.com.au/blog/alter-or-dispatch-drupal-8-events-versus-alter-hooks


Triggers on node creation of certain content-type

Rules and core triggers/actions can co-exist. If it can easily be done in Rules, then why not use both. You then won't have to migrate.


You can overwrite views-view-fields.html.twig or create your personal views-view-fields--YourViewName.html.twig and apply the div or any wrapper you want.
I advise you to activate the twig debug to follow the suggestions


The block X was assigned to the invalid region footer and has been disabled

It doesn't work because regions are theme specific. The only way you can have cross theme block export/import is to have the same regions (machine name) defined in your admin theme.


Override theme template from module without implementing a theme

You can do this in hook_theme() with the base hook 'node':

function MY_MODULE_theme($existing, $type, $theme, $path) {
  return [
    'node__video_teaser' => [
      'template' => 'node--video-teaser',
      'base hook' => 'node',
    ],
  ];
}

You don't need to define the base hook. Drupal can discover this automatically. What's important is that you use the double underscore, because this works exactly like the theme suggestions. After Drupal found the base hook it will clone the preprocess functions of this hook and will provide the variables for the node.


How to patch module files with netbeans 7.4?

If you duplicate the file in Netbeans that gets patched (this is important that you do this on the file, NOT the project) then right click on it under Tools -> Apply Diff Patch then select your patch file. It should then say everything went as planned and allow you a summary.

You will need to repeat this for every file in the patch, or you can just apply it using Git or one of the other methods listed.


What hook function (is _form_alter correct?) do I use to alter the input submitted by the user into a views exposed filter form?

First if you want to add submit handler as first in form_alter do

//prepend the handler to array
array_unshift($form['#submit'], '_mymodule_custom_handler_submit');

So you dont overwrite any other callback by some other module.

Second, check that the form input elements dont have overriding submit handlers ("
submit action on the buttons")

Third, try to assign the value with form_set_value

$oldValue = $form_state['values']['field_geofield_distance']['origin'];
$value = array('origin' => array('#value' => $oldValue. ', UK')
form_set_value($form['field_geofield_distance'], $value, $form_state);

Syntax above is not correct, but without knowing the structure of the field its impossible to know what kind of array it requires. For example Link module fields can be modified with following.

    // Set first link of the field pointing to google, most likely
    //unsets all the following ones
  $link = array(
    0 => array(
      'title' => 'Google',
      'url' => 'google.com'
    )
  );
  form_set_value($form['field_link'], $link)), $form_state);

Last but not least, use additional form validation callback instead submit handler, that way its sure that the values get passed to all "targeted(see second)" submit handlers.

Long story short. When form is being built, add input validator to it. Validator will get called after user sends the form and there you can modify values before they get submitted to submit handlers.

Summary interpretating view flow

While the view is being built first time it calls the form (which runs through standard drupal hooks like form_alter) and gets the values from it just in case it has some defaults or accepts 0 filters.

After that it runs the queries, renders the form and the result. When finished you get the view including all the elements without user input. Like clean plate (mayby some contextual filters and stuff is applied but thats irrelevant?).

Next when the user sends the form with custom input, drupal (field widgets/handlers) transforms input to values and store them in $form_state and passes them to validators. Here the custom validator can modify the user input values in $form_state and attach them with form_set_value.

If the validation passes correctly $form_state values(modified) get passed to submit handlers. Most likely views will start building itself from them. Heres more exact flow(pdf)


JWPlayer does streaming.

http://www.longtailvideo.com/jw-player/hls-rtmp-live-streaming

I wasn't able to find a module that did this, but you can add this to your page, using the Full HTML text input:

Loading the player


Try print_r instead of dpm --

function theme_menu_link(array $variables) {
  return print_r($variables['element']);
}

or use hook_menu_link_alter --

hook_menu_link_alter($variables){
  var_dump($variables);
}


Problem with creating own module Block with an SQL query

For most contributing members you may want to look at the user points modules, they give you a lot of very nice features.

A couple of quick pointers with your code as you are asking.

Your query should use parameters and be formatted according to drupal coding standards, this helps for security and portability. The coder module can help you with this.

To get the results you will probably want something like db_fetch_array in a loop

 $result_set = db_query("SELECT ...");
 while ($result = db_fetch_array($result_set)) {
   $block_content .= ...;
 }

I hope this helps a little.


How can I get the current node view mode and add to block template suggestion?

You say in your comment it is not useful for you and I doubt there are many use cases for this at all, because normally as main content a node is rendered in the full view mode.

Nonetheless trying to answer: A block is built based on contexts and at the moment this is the route, which you have to add as cache metadata to the block. You can then base the decision which view mode the node uses on this route by checking _entity_view of the route definition. If the view mode is controlled by code somewhere else you need to pull this in as context as well.


/**
 * Implements hook_form_alter().
 */
function modulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_list') {
    $form['updated']['list']['#header']['bar_column_field']['data'] = 'Bar Column';
    $form['updated']['list']['#header']['bar_column_field']['field'] = 'bar_column_field';
    $form['updated']['list']['#header']['bar_column_field']['class'][] = 'privatemsg-header-bar-column';
    $form['updated']['list']['#pre_render'][] = '_pre_render_bar_column';
  }

/**
 * Custom #pre_render function.
 */
function _pre_render_bar_column($tableselect) {
  $i = 0;
  foreach ($tableselect['#options'] as $id => $options) {
    $data = 'Bar data in the table ' . $i++ . '';
    $tableselect['#options'][$id]['bar_column_field'] = array('data' => $data, 'class' => array('privatemsg-list-bar'));
  }
  return $tableselect;
}

You can change the $data variable with any field's value, after performing a query or something, and placing your actual data to the new column.
A field could be attached to messaging (admin/config/messaging/privatemsg/fields) or to any other available entity.


Attach a webform into faq module content

https://www.drupal.org/project/faq

  The Frequently Asked Questions (faq) module allows users, with
  appropriate permissions, to create question and answer pairs which
  they want displayed on the 'faq' page. The 'faq' page is automatically
  generated from the FAQ nodes configured. Basic Views layouts are also
  provided and can be customised via the Views UI (rather than via the
  module settings page)

.


How is the height defined for a region in a Drupal theme?

Nothing magical is going on here; just look in the .info file for the stylesheets and then look at them. The CSS in there combined with the html in page.tpl.php and other template files build the pages drupal creates. Well, sometimes some javascript comes into play, but that covers the majority of page markup.

ADDITION:

I don't have the theme you are referencing in specific on my machine, and if you are using Drupal 7 it will be slightly different, but to use garland under Drupal 6 as an example, and to expound upon the above and comments below, if we open up its .info file, we will find a:

regions[header] = Header

This tells the theme engine that it has a region called header. So, if we look in its page.tpl.php file, we will find:

<?php print $header; ?>

So, when the user puts blocks in the Header region via the Block Administration page, drupal puts all of the html etc into the $header variable for those blocks, which is then output here when it paints the page.

As you can see, $header is wrapped in a CSS id and class, so you can then look back at the .info file to find your CSS files:

stylesheets[all][] = style.css

Opening up style.css reveals:

#header-region {
  min-height: 1em;
  background: #d2e6f3 url(images/bg-navigation.png) repeat-x 50% 100%;
}

which gives the first of many cascading styles to apply to the theme's Header Region.  Don't fret over the clear-block class, it's just a wizardly way of making sure nothing floats next to the header (and vice versa), and you aren't ready for that yet lol.

So if you do this with your theme, you should be able to discover how its header is styled.


You can add the node ID manually to Drupal settings with drupal_add_js(), for example from a preprocess function.

// PHP
$setting = array('setting_1' => 'value_1', 'setting_2' => 'value_2');
drupal_add_js($setting, 'setting');

// JavaScript
var nodeId = Drupal.settings.setting_1;


Cannot figure out role-based pricing rule for custom Product Display/Variation in Commerce Kickstart

Entity has field: Parameter: Entity: [commerce-line-item], Field: field_dealer_price

Your price field won't be on commerce-line-item. It will be on commerce-line-item:commerce-product. You need to check for it there.

  Amount: [Click on Switch to Data Selector]: commerce-line-item:commerce-product:field-dealer-price:amount or commerce-line-item:commerce-product:field_dealer_price:amount or commerce-line-item:commerce-product:field-dealer_price:amount

So since the field_dealer_price is on the product instance, you'd be looking at this: commerce-line-item:commerce-product:field-dealer-price:amount

An example, without the role condition, would look like this:

{ "pricing_from_another_field_example" : {
    "LABEL" : "Role based pricing example",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-product" ],
          "field" : "field_dealer_price"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : [ "commerce-line-item:commerce-product:field-dealer-price:amount" ],
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}


Superfish menu - how to remove parent sign: "PARENT_LINK >>"?

In your superfish block settings there should be a setting that reads "AUTO-ARROWS:" with a dropdown.

Set that to no (and save) and you shouldn't have any arrows anymore.


set up social login for multiple drupal sites?

I don't think you're going to find a way to automate the creation of application accounts. Facebook, Google, et. al have to deal with enough spam as is, without them opening up a pandora's box of spam application accounts that would come from exposing an API that could create application accounts on their respective platforms.

HybridAuth works well if you're looking to have flexible access to each social login platform (e.g. a FB app that can request multiple user permissions to the Graph API). If you're looking for just login delegation you might find more success with one the 3rd-party social login services like the LoginRadius or the Janrain modules (there might be more, those are the only ones I've heard of).


OK, I managed to achieve this by implementing hook_form_FORM_ID_alter() in my mytheme.theme file.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mytheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($form['#id'] == 'my-views-exposed-form-id') {
    $query = db_select('node_field_data', 'n')
      ->fields('n', array('nid', 'title'))
      ->condition('type', 'sector')
      ->condition('status', 1)
      ->orderBy('title', 'ASC');
    $options = $query->execute()->fetchAllKeyed();

    // $form['sector'] is a type text, changing it to select.
    $form['sector'] = array(
      '#type' => 'select',
      '#options' => array('' => t('Filter by Sector')->render()) + $options
    );
  }
}

Hope it will help someone.


Clive's answer is right.. You can not pass $node object before you created yet. If you want to show the same form which is shown in the /admin section you can do something like this:

function tasks_menu() {
  $items = array();

  $items['tasks/create'] = array (
    'type' => MENU_CALLBACK,
    'title' => t('Create New Task'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('task_node_form'),
    'access arguments' => array('create tasks')
  );

  return $items;
}

and:

function task_node_form($form, &$form_state) {
  $form = array();
  $node = new stdClass();
  $node->type = 'YOUR TYPE';

  field_attach_form('node', $node, &$form, &$form_state, $langcode = NULL, $options = array())

  // Other code
}


Make errors also display in proper format and language

Either import translation for Webform, or keep in synch with i10n.

If the string ('field is required') is not translated, you have to do it yourself in the translation interface admin/config/regional/translate.


How to delete cache after updating/deleting/adding new content using hooks?

It sounds like you've already got a custom module, but just in case you haven't see the Module Developer's Guide.

The hooks you're looking for are hook_node_insert() and hook_node_update(), and the function to clear the cache will either be cache_clear_all() or drupal_flush_all_caches. The former will let you clear specific cache bins (and even specific cache items), and the latter will clear absolutely everything.

For example:

function MYMODULE_node_insert($node) {
  drupal_flush_all_caches();
}

or to clear only the static page cache after a node has been updated:

function MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid, array('absolute' => TRUE));
  cache_clear_all($nodeurl, 'cache_page');
}