Move all files and folders from a directory to another directory

Sounds like you are trying to rename files by specifying their Url. You can't do that. You have to specify the path to the file. It's a PHP issue rather than a Drupal issue. Try this instead:

rename($_SERVER['DOCUMENT_ROOT'].'/path-to-folder/anotherdirectory/filename.ext', $_SERVER['DOCUMENT_ROOT'].'/path-to-folder/filename.ext');


How should I prevent second page of site's front page from being indexed?

Since view?page=1 will almost always be the same as view, you should add these lines to your robots.txt

Disallow: /*sort=
Disallow: /*order=
Disallow: /*page=1

More at: http://larsolesen.dk/content/struggling-duplicate-content-drupal-7


login destination redirect to previous page adding #

This can be done via

<?php
  print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination(),
    'fragment' => 'article_1'));
?>


That's the best use case for the Viewfield module. It works providing a custom field, so you can "attach" a view to nodes.

You can provide a default view if you want to display the same view on many nodes.

Or you can provide a custom argument to pass to the view.


Why does webform configuration not let me choose existing content types

Admin Menu --> Structure --> Content Types --> Basic Page's Edit --> Webform tab --> select Enable

I not sure is this what you mean.


Allow module to overwrite multiple templates from module

I was able to figure it out. I only used hook_theme_registry_alter().  You have the copy $theme_registry['paragraphs'] to all items you want to use paragraphs.

/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'my_module');

  // Use the templates in my module's template folder.
  $theme_registry['paragraph__accordion'] = $theme_registry['paragraph'];
  $theme_registry['paragraph__accordion']['path'] = $module_path . '/templates/paragraph';
  $theme_registry['paragraph__accordion']['template'] = 'paragraph--accordion';
  $theme_registry['paragraph__carousel'] = $theme_registry['paragraph__accordion'];
  $theme_registry['paragraph__carousel']['template'] = 'paragraph--carousel';
}


Why kpr() shows different content than var_dump()?

$download[1][6] and $download[2][6] are the exact same object (object(stdClass)#155), not just two objects with equal values. To avoid potential infinite recursion, Krumo (the k in kpr()) only display a single object once. The screenshot shows this, $download[2][6] is displayed as "∞ (Recursion)" because the object is already displayed (but collapsed in the screenshot) above as $download[1][6].

var_dump() does not have this limitation as it does not try to prevent infinite recursion.


Contextual Filter not working wiht URL aliases

Use Content ID from URL instead of Raw value from URL


What's the syntax of drush generate --answers argument?

Finally found it:

drush generate theme --directory themes/custom --answers '{"name": "test", "machine_name": "test", "base_theme": "Classy"}'

in the absence of documentation, you'll find the needed json keys in the sources of drush code generator:

/sources/vendor/chi-teck/drupal-code-generator/src/Command/Drupal_8/Theme.php

in the "interact" method


Can I tell CKeditor to NOT TOUCH my HTML code?

Even 'Full HTML' does some html tampering - you could try creating a new text format for Admins only without any restriction at all - this is what I usually do for adsense and it has always worked great without the need for another module.


You can use Better Messages module

  Better Messages is a very simple module that provides "Popup-like"
  Drupal messages.

  Better Messages intends to let you control where and how you want to
  see your Drupal messages! Combine different animations and override
  better_messages.tpl.php to create your custom look.


Taxonomy Breadcrumb module has maintenance status: Unsupported. It means it's author's answer to all problems with it is simply "stop using it". There is a bug report 2 years 41 weeks old about your problem and I don't really expect it will be fixed any time soon.


You can add this line, {{ content.field_category[0]['#title'] }} to get  value of title inside twig.


Listing first name, last name at Users listing page

I suggest using Administration views module which will replace all administration overviews, e.g. the list of users, with actual views. You will then be able to add any field you have attached to user profiles to your overview as well. This will work for both Drupal 6 and 7.


Trying to make a custom region disappear upon user login, then reappear when user logs out

Context is a great plugin for remodelling sections of your website - paired with Delta and the Omega theme, you can overhaul your entire layout based on nearly any condition without editing any code by hand.

There's a decent intro tutorial for Context and Delta over here.

But if that doesn't fit the bill, you're on the right track with your .tpl.php files. Checking for user login is quick, just remember to global the variable first:

<?php
global $user;

if ( $user->uid ) {
  // Logged in user
}
else {
  // Not logged in
}
?>

... and by inserting the desired code between braces you could easily toggle blocks, regions, messages and nearly anything else accessible from the template.

This is my "PRINT ALL THE THINGS!!" snippet, try it out for the $user variable:

<?php global $user; echo '<pre>'.print_r($user, true).'</pre>'; ?>

Good luck!


Their is a lot of ways. I list here only things compatible with D7 and eventually on D6.

Use a modules

https://drupal.org/project/menu_position (need rules, watch http://vimeo.com/27074705)
https://drupal.org/project/menu_trail_by_path
https://drupal.org/project/context

Code your stuff

Their is now a native API menu_tree_set_path to set the path you want to use to calculate the menu active trail.

You can also work in theme_links but but I recommend to use menu_tree_set_path so other module know what is your active link. The advantage is you can use this function in your theme without creating a module.

Keep in mind, menu_position has an API to create your custom rules.

So what should I use???

It's depend of your need. if you have simple rules like: for this node type/views/taxonomy i want this active menu, context is good.

If you have a good url structure (autopath) than follow your menu structure, menu_trail_by_path will just works without any effort.

I never used menu_position... so I can very tell.

If you need some special logic, coding your things is certainly faster than creating 40 context or rules...


how can I override theme_image() on a custom node template, only

As I understood your problem, you need to redefine theme_image function only for custom template. I found following link for you that can help you to resolve your problem.

How to redefine default theme_image() function?

Another way is just override theme_image() function that you don't want to follow:

Find the original theme function.
Copy and paste it into your template.php file.
Change the beginning of the function name from theme_ to yourthemename_.
Save template.php, clear the site cache, and reload!

Keep us posted with what you figure out.


When should the "container" form element be used?

It looks like it can be used when you want to wrap a part of the form in a div, for example to be able to add some classes to it.

Some examples from core are the following:

field_default_form()

// Also aid in theming of field widgets by rendering a classified container.
$addition[$field_name] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array(
     'field-type-' . drupal_html_class($field['type']),
     'field-name-' . drupal_html_class($field_name),
     'field-widget-' . drupal_html_class($instance['widget']['type']),
    ),
  ),
  '#weight' => $instance['widget']['weight'],
);

node_filter_form()

$form['filters']['status'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('clearfix')),
  '#prefix' => ($i ? '
' . t('and where') . '
' : ''),
);
$form['filters']['status']['filters'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('filters')),
);

search_form()

$form['basic'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('container-inline')),
);

Forms in Drupal 6 often used #prefix and #suffix on the first/last element to do this; this is a lot better because it is easier to add additional items or move them around.

I could use this in a few places in my own contributed modules, actually. ;)


Are db_update->condition() and db_update->where() the same?

condition() always involves a field/column name and a provided value (or an array of provided values). where() can contain arbitrary conditions (comparing fields against each other, can contain functions/expressions), it's just a string that is passed through.

condition() example, select everything where created is bigger than timestamp value.

$timestamp = 123465...;
$query->condition('created', $timestamp, '>');

where() example, select everything where changed is bigger than created.

$query->where('created < changed');

Everything that can be done with condition() can also be done with where(), but not the other way round. The following is the same as the condition() call.

$query->where('created > :timestamp', array(':timestamp' => $timestamp));

Works just fine, but is way more complicated. The basic rule is that condition() should be used whenever possible and if not, use where().


Most Drupal modules that installed their own database tables also remove them upon uninstall. I have bolded uninstall due to the fact that modules can have two states when they are turned off namely disabled and uninstalled.

Disabled implies that you have simply turned the module off, but have chosen to keep the module's settings and database tables intact in the event that you turn it back on again at some point. Disabling is done by simply unchecking the module on the module administration page and clicking on "Save configuration".

Uninstalled on the other hand indicates that you have decided that a previously disabled module will never be used again. Consequently, you are happy to remove all the settings and database tables created. This is done by clicking on the "Uninstall" tab on the module administration page, checking the module that you want to uninstall and then clicking on "Uninstall".

If for some reason the module does not have an uninstallation script in its .install file, then you will need to remove the tables manually. You can also try creating an issue in the module's issue queue asking for this oversight to be remedied.

If you have removed the module's files from the server, then you will (obviously) be unable to run the uninstallation script (as the module will no longer be listed under the uninstall tab). To fix this, simply download/restore the module again to the file system (you do not need to install it). This should list it again under the uninstall tab and you can proceed to run its uninstallation script as above.


How can I recover from a backup but include many changes from a dynamic site?

A module that logs all database transactions so they can be individually inspected and reapplied if they're deemed legitimate?

Where it would log to? Database? Impossible, it would kill your server. Filesystem? It's slow. And it's big. Another thing worth noting is that if you would want to manually approve / disapprove each query, you can either:

Inspect them carefully, and you already told us there is a lot of them, so it could take you up to hours per one edit, if your content types are complicated enough - not nice on dynamic site.
Inspect them fast, probably making your data inconsistent.

Last but not least, if you will add that as a module, anyone with proper permissions will be able to disable that module, making your efforts void.

Modules that should be able to help some are:

Drupal Tiny-IDS
PHPIDS

Sadly, as far as I understand, neither would help in this particular case.

What I would do is:

Hourly backup. If possible, done as a snapshot of virtual machine, because that's fast and unobtrusive.
Mail about each new user, new role assignment, and password change. Sadly, if no one monitors that mail, no one can help.


Views Ticker missing views, what are views and where can I get them

Modules sometimes have dependencies on other modules.

The Views module is one of the most used modules in all of Drupal that isn't a part of Drupal core.

Generally you can find your missing modules by going to http://drupal.org/project/[name]. This is not always true as some modules is not a single module but multiple modules. Views is one of those modules, that has a core module called Views, and an UI module called Views UI which is used to create the interface for setting up views.


If you have a specific list of blocks you want to alter, get their deltas and invoke hook_block_view_alter in a custom module, as follows:

function YOURMODULE_block_view_alter(&$data, $block) {
  switch($block->delta) {
     case 'delta1':
     ...
     case 'deltaN':
       // alter the block in the required way by modifying the $data array
       break;
  }
 }

If you want to alter ALL blocks created by a particular module, say, views, do a switch on $block->module, instead, i.e.:

function YOURMODULE_block_view_alter(&$data, $block) {
      switch($block->module) {
         case 'views':
         case 'SomeOtherModule':
           // alter the block in the required way by modifying the $data array
           break;
      }
}

Bear in mind that hook_block_view_alter is called for ALL blocks, so if your site has lots of blocks, this may be a performance hit.


Fresh drupal install shows drupal core warning

Since you used git clone, you probably pulled from the HEAD and are running a development version of Drupal. Your Drupal installation does not have an official version number, so it cannot be detected. You can install Drupal with composer, download the zip, or try to clone a tagged release (I always used composer so I am not sure if a tagged release works).

As for the 32/64 bit warning. Depending on the PHP version you have installed, you can run a 32bit PHP installation on a 64bit OS. I suppose that is the root of your problem.


Is it possible to change the form submit handler from within a validate handler (need to redirect to another form depending on values entered)

You don't need to rewrite form submit handler. You can implement drupal_goto() for your first form with FORM_ID_submit() depending on user input. Pass $form_state['values'] as url options and fetch them from $_GET array as #default_values in second form.


EntityQuery condition "is not equal to..."

I found it !

I was not far away, I've just to reverse the last two parameters of the condition.

$query = \Drupal::entityQuery('node')
       ->condition('type', 'order')
       ->condition('field_multiple_choice', 'doe', '!=');
$nids = $query->execute();
$entities = \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

  As the doc says, public function
  QueryInterface::condition
  take following arguments :

condition( $field , $value = NULL , $operator = NULL , $langcode = NULL )


Problem in rendering double-field in other node

Try to change format for that field in 'Manage display' in back-office. 'key' option should be there. This option available for select list, but for "double field" try to set "unformatted list", style "simple", and text format "-none-".


Add following code to template.php and clear cache

function <THEME_NAME>_preprocess_node(&$vars) {
    if(!empty($vars['node']->tnid) && $vars['node']->tnid !== 0){
        $vars['theme_hook_suggestions'][] = 'node__'.$vars['node']->tnid;
    }
}


Create a custom Link to a File-Field in Twig

After more research, i found the answer by accident on this page. One can refer to the link by using:

<a href="{{ file_url (node.field_publication_file.entity.uri.value) }}">
  Download
</a>

The fields that were defined in the bootstrap theme don't seem to be accessible in a sub-theme of bootstrap. I'm sure I could have written a custom preprocessor to do the same thing, but this solution works for me and I don't have to write PHP code.


Create a view block that shows list of nodes that references same node as current node

Let us assume the the filed in collection that referes to article is field_entity_article

Then you would do the following.

With in your view first you would add a relationship called Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_entity_article)
The you would add another relationship Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_node_article) While you are here select the previous relationship you created from the dropdown Relationship
Add a contextual filter of the type content: nid and provide default argument and select node id from url form the dropdown.
Add the required field and give the second relationship we created for this.

That should do it.


Need to convert datetime to date during D8 migration from non-drupal source

public function prepareRow(Row $row) {

   $date = $row->getSourceProperty('database_date_field');
   $date = strtotime($date); // -> 1336341600 unix timestamp
   $date = date('Y-m-d', $date); // -> "2012-05-07"

   // Here you 'rewrite' the field with the new value before it gets saved
   $row->setSourceProperty('database_date_field', $date);
   return parent::prepareRow($row);
}


How to add two registration form on single page?

Give a try to Profile2 Registration Path module:

Problem with Profile2 module: By default, the Profile2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

Solution:

  Profile2 Registration Path enables you to set a unique registration path for each Profile2 profile type. Users who register via that unique path will be presented with fields from the chosen profile type(s).

Alternatively another method to include multiple forms (e.g: FORM1 and FORM2) on same page is somewhat like below(however I am not sure where it will work with the profile2 forms):

$output = array();
$output['FORM1_DISPLAY'] = drupal_get_form('FORM_1_FORM_ID');
$output['FORM2_DISPLAY'] = drupal_get_form('FORM_2_FORM_ID');
return $output;


Adding menu with description like mega menu

You can try TB Mega Menu, it's got very nice user interface (WYSIWYG) and also multiple built-in styles.

http://drupal.org/project/tb_megamenu


Disabled item in menu in menu_tree_all_data

'hidden' key in the array returned, will tell you if the menu links is enabled or disabled. For all disabled menu links hidden will be '1'.


Argument 1 must be an instance of Drupal\tcdev\Controller\UserAuth, instance of Drupal\user\UserAuth given

Inject the user.auth in your controller:

$auth = $container->get('user.auth')

[edited to clarify injection basics:

In public static function create(ContainerInterface $container) add $container->get('user.auth') to the return new static(...) statement.

In public function __construct(...) add the $auth to the signature at the correct position. Then add a private (or protected) variable $auth to your controller and assign the value from __construct to it.

You may simplify that by using drupal console or drush. They can create the boiler plate code for you.

If you don't want to use injection, you may use $auth = \Drupal::service('user.auth');

But this has drawbacks in testability.

[end edit]

then call the authenticate func:

$uid = $auth->authenticate($username, $pass);

With the $uid load the user:

$acc = User::load($uid);

Then set the user into the session:

  \Drupal::currentUser()->setAccount($acc);
  \Drupal::logger('user')->notice('Session opened for %name.', array('%name' => $acc->getUsername()));

Should work. But I don't think that it is a good idea to pass around the password in the URL of your tcdev.login...

Edit: Sample Code (generated by drupal generate:controller)

namespace Drupal\preosuser\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\UserAuth;

/**
 * Class AuthController.
 *
 * @package Drupal\preosuser\Controller
 */
class AuthController extends ControllerBase {

  /**
   * Drupal\user\UserAuth definition.
   *
   * @var \Drupal\user\UserAuth
   */
  protected $userAuth;

  /**
   * {@inheritdoc}
   */
  public function __construct(UserAuth $user_auth) {
    $this->userAuth = $user_auth;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('user.auth')
    );
  }

  /**
   * Checklogin.
   *
   * @return string
   *   Return Hello string.
   */
  public function CheckLogin($name) {
    return [
      '#type' => 'markup',
      '#markup' => $this->t('Implement method: CheckLogin with parameter(s): $name'),
    ];
  }

}


Show Taxonomy Name not TID in Views Query String

You can use taxonomy term names with this filter by adjusting Specify validation criteria settings. here's a screenshot:

Make sure Specify validation criteria is checked and you should be presented with more options. Under Validator choose Taxonomy term. You can optionally select with vocabularies to allow. Under Filter value type choose Term name converted to Term ID and check the Transform dashes in URL to spaces in term name filter values checkbox.


There's a module called Quick Tabs, which allows to create Ajax loaded tabs. We need to flush all caches after creating the new tab in order to be seen as a normal block. It fixed the problem.


Why are not all stylesheets in mytheme.info being loaded?

the answer is in the drupal_get_css doco page:

  Themes may replace module-defined CSS files by adding a stylesheet with the same filename. For example, themes/bartik/system-menus.css would replace modules/system/system-menus.css. This allows themes to override complete CSS files, rather than specific selectors, when necessary.

If you look at the source code at the bottom of the page, the array that contains the css has the basename of the file as the key. So this is an intentional feature.

You will just have to keep the renamed file.

Hope this helps. :)


How do I create a dynamic query that filters on month and day?

I was able to query the date by using a where clause instead of condition.
Example, replace

 $query->condition('field_donor_date_of_birth.field_donor_date_of_birth_value', $birth_date, '=');

with

$time = format_date(time(), 'custom', 'm-d');
$query->where("DATE_FORMAT(field_donor_date_of_birth.field_donor_date_of_birth_value, '%m-%d') = '$time'");


How do I create a page consist of more than 100 lines, by custom module?

There isn't a limit on the number of lines returned by a page callback, or on the number of tags it can return.
If the output is getting complex, it's rather better to separate the code into different theme functions; for example, for outputting a link there is l(), for outputting an image there is theme('image'), and for outputting a table there is theme('table'). The first rule is to reuse the existing functions.

In Drupal 7, a page callback can also return a renderable array, such as the following one returned by tracker_page():

  $page['tracker'] = array(
    '#rows' => $rows,
    '#header' => array(t('Type'), t('Title'), t('Author'), t('Replies'), t('Last updated')),
    '#theme' => 'table',
    '#empty' => t('No content available.'),
    '#attached' => array(
      'css' => array(drupal_get_path('module', 'tracker') . '/tracker.css' => array()),
    ),
  );
  $page['pager'] = array(
    '#theme' => 'pager',
    '#quantity' => 25,
    '#weight' => 10,
  );
  $page['#sorted'] = TRUE;

  return $page;

In these cases, the page callback doesn't return any HTML tags. This is also the preferred method, in Drupal 7, as it allows to the other modules to easily change the output of another module.

As alternative, you can use a template file for rendering the output. In this case, you need to:

Define a theme function that uses the template file; that is what is done from the Node module for theme('node'), which is defined in node_theme() using the following definition (Drupal 7):

'node' => array(
  'render element' => 'elements',
  'template' => 'node',
),

Optionally create a preprocess and/or a process function for the template, their purpose is to add variables to the ones that are passed to the template file. In the case of the Node module, those functions are template_preprocess_node() and template_preprocess_node().
Invoke the theme function to produce the output. In the case of theme('node'), this is done as in the following code:

// Drupal 6.
return theme('node', $node, $teaser, $page);

// Drupal 7.
$build += array(
  '#theme' => 'node',
  '#node' => $node,
  '#view_mode' => $view_mode,
  '#language' => $langcode,
);

Update
This is a common error: The template file name and the theme name must not be different; the only difference can be between using hyphens and using underscores. For the rest, the theme name and the template filename must be the same, which means that "mypage" as theme function and "mynew-page" as template filename don't work; if you are going to use "mynew-page" as template file, then the theme function must be theme_mynew_page(), reported in the theme definition as "mynew_page."


Drupal Commerce product display text input on specific option

you can use drupal conditional field module , and then on a certain value configure your text field to be displayed .
conditional fields


It seems like this could be related to particular blocks or other renderable objects on your site that may have many permutations. In one case, I saw 100,000+ rows for one particular views exposed filter block.

Since users were able to select many different options, the block was stored hundreds of times per page/URL in the cache_render table.

It's best to try to scan through the cid values of the table and see any patterns, e.g. with SELECT COUNT(*) FROM cache_render WHERE cid LIKE "%interesting_cid_here%";, to see if there are any major offenders.

Still trying to figure out the best way (besides periodically running drush cr) to fix this issue. For now, I opened up an issue in the Drupal Core issue queue: cache_render table becomes extremely large over time

See discussion around this issue in this Drupal Core issue: Make CACHE_PERMANENT configurable in the database cache — currently allows unlimited growth: cache DB tables of gigabytes!.


Need to force #default_value for AJAX tableselect checkboxes

Just before the tableselect's array in the form builder function, put the following code:

unset($form_state['input']['my_tableselect']);


I finally figured this out.
YES it is possible to have dynamic menus in Drupal.

You start by enabling dynamic access to menu item with the ['alter'] flag and hook_menu_link_alter(&$item).

function mycode_menu_link_alter(&$item) {
    if($item['menu_name'] == 'user-menu'){
        $item['options']['alter'] = TRUE;
    }
}

Note that menu_link_alter works on a menu item (not the whole menu) and needs to be trigered by editing and saving that item (for example disable->save->enable->save->).

Once the menu item is activated, I can use
hook_translated_menu_link_alter(&$item, $map)

function mycode_translated_menu_link_alter(&$item, $map){
    //drupal_set_message("Menu: ".$item['menu_name']." Item: ".$item['title']
    if($item['menu_name'] == 'user-menu'){
        global $user;
        $item['title'] = "Hi: $user->name";
    }
}

Other very useful thing you can do is to disable the menu link

$item['hidden'] = TRUE;

or (my favorite) change the links

[...];
if($item['menu_name'] == 'main-menu'){
   switch ($item['title']){
       case "Home":
            $item['href'] = 'not/home/page';
[...]


Add div after each field of a certain name

Copy modules/field/theme/field.tpl.php file into sites/all/themes/YOUR_THEME/templates

Rename it to field--additional_content--YOURCONTENTTYPENAME.tpl.php
(or only field--additional_content.tpl.php if you want to change its template for all content types)

Edit its template like this:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>


presave like option for adding vocabulary and terms similar to one provided by hook_nodeapi

You can add a validation function to the form in hook_form_alter(). If you give your module a high weight, that validation function will be added last to the validation functions array and thus be executed last. The validation function can call form_get_errors to check whether errors occurred. If no errors occurred, you can be pretty sure that the vocabulary or term will be saved to the database, making it something like hook_nodeapi($op = presave').

Note that you cannot use hook_form_FORM_ID_alter(), because these hooks are executed before hook_form_alter(). Also, I found no easy way to react on the installation of other modules.


Custom entity types with multiple value properties

// Add a single recipient to the entity
public function setRecipient()

What now, add or set? If it is adding to the existing list, I'd recommend to name it addRecipient().

I'd also recommend to name the field recipients or so, to indicate that it has multiple values.

You can add an item to a field item list with \Drupal\Core\TypedData\ListInterface::appendItem(), for example $this->get('recipient_id')->appendItem($recipient_entity_or_id_or_value_array)

To get all referenced entities, there is a referencedEntities() method on entity reference field item lists, or you can use a loop.


What is wrong with this schema definition and db query?

I believe key is a reserved word. I'd stray away from using the key instead of trying to get MySQL to accept it. But here's some examples on how to get around it (which might not be possible via Drupal's db api).

https://stackoverflow.com/questions/2889871/how-do-i-escape-reserved-words-used-as-column-names-mysql-create-table


the wildcard %exercise was returning several entities.


Drupal Commerce - How do i specify a user name for new account other than the email address on an anonymous order?

On the create user Rule you need to bring field_account_name into scope by running condition "Entity has field."

First run EHF on Commerce Order to bring the billing profile reference into scope. Then you can EHF your account name field.

You then will have the ability to have access to that field's token and use it as the new account's username.

Note: this is more a Rules usage technicality, which Commerce uses heavily.


What is the proper way to drop database references for an uninstalled drupal module?

There's no single procedure for manually removing a module, it kind of depends on what has been installed, where it's been installed and how it's been used.

For commerce coupon the basics are pretty simple:

Remove commerce_coupon and commerce_coupon_type
Remove the 4 field tables.
DELETE FROM field_config_instance WHERE field_name IN ('field_data_commerce_coupon_order_reference', 'field_data_commerce_coupon_reference')
DELETE FROM field_config WHERE field_name IN ('field_data_commerce_coupon_order_reference', 'field_data_commerce_coupon_reference')
Flush the caches

From there it gets a bit trickier. Depending on how the module's been used you may have references to coupons in the commerce_line_item table, with relationships back to their order in field_data_commerce_line_items (and the corresponding revision table). Those should also be removed to prevent errors when line items are loaded.

As you mentioned in the comments there may also be related rules (and potentially views as well), hunting down and deleting those manually might be the easiest thing to do.


For those that are trying to use the built in jquery ui you must include -core/drupal.dialog as a dependency in your theme.libraries.yml for it to work


Is there a way to see what fields are used in Rules?

Consider a rule as in this (random) sample (in Rules export format):

{ "rules_new_node_with_special_optionlist_value" : {
    "LABEL" : "New node with special optionlist value",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value =  \u0022[node:field-optionlist]\u0022" } }
    ]
  }
}

Obviously, the above rule uses a field with machine name field_optionlist.

Execute an SQL query on the Drupal database which looks like so:

SELECT id,plugin,active,name,label
FROM `rules_config`
WHERE `data` LIKE '%optionlist%'
LIMIT 3

The results I get by using this query (limited to the first 3 results only) looks like so:

id  plugin         active  name                                           label

20  reaction rule  0       rules_verify_updates_to_node_properties        Verify updates to node properties
21  reaction rule  0       rules_new_node_with_special_optionlist_value   New node with special optionlist value
28  rule           1       rules_set_an_initial_value_for_a_text_field    Set an initial value for a text field

Obviously, the result with id=21 matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin. Or if you rather want to have a site building tool, just use the Forena module (disclosure: I'm a co-maintainer). After you enable this module, these are the steps required to find the answer to your question:

Use relative link /admin/structure/forena/data/add (= Create New SQL Query).
Select a "Data source" in which the SQL statement (= data block) will be stored (saved).
Enter the above SQL statement, and use the Test Changes button (to prototype your SQL).
Voilà, there is the (prototyping) result.

The above should answer the "It would be enough to check if a certain field is used by Rules" part of your question, but if you want to further improve this prototype, use the power of Forena to build a custom report from it, and make all sort of magic happen, eg:

export it to a CSV.
eMail it to somewhere.
...

Note: the above approach works for all sorts of "Rules queries" ... after all, in the above query I used (part of) the machine name of some field (= optionlist). Do an educated guess what kind of results you get if you would use the machine name of:

a content type, e.g: article.
a rules component, e.g: rules_send_email_notification.
a module that some rule(s) depend on, e.g: webform_rules.


Disable the BBCode plugin in Tinymce settings.


I have used the wrong token field for the paragraph image field. Instead of [media...] token need to use [paragraph:...] token, as the field is paragraph field.


Painfully slow, Devel Query logs show culprit

What is the history table?

This is a table for keeping track of what user has read what node. (To show a new/updated message next to it.)

  Any idea why its taking so long to run the query?

This could be anything, and might be at the server level (not related to Drupal).

First, check if SQL is slow outside Drupal (eg. PHPmyadmin). Run the same query, see what happens.

If SQL is still slow and you have ssh access to the server, try to run some disk speed checks using sudo hdparm -Tt /dev/sda and dd if=/dev/zero of=/tmp/output bs=8k count=10k; rm -f /tmp/output (assuming Linux). I had a slow site recently that was caused by a malfunctioning hard drive.


Can I use Ubercart Stock to monitor individual components of a product?

It is. Make your hamburger a product kit which is made up of products, bread, beef, tomato, lettuce and onion. When you sell a hamburger Ubercart will be smart enough to control stock of the ingredients.


How can I create user profiles in drupal 7?

In Drupal 7, users accounts are fieldable entities like nodes. From Administration » Configuration » People » Account settings, you can add fields and configure their display on the user page (ie. /user/$uid).

For a more complex setting with multiple profile types and separation of accounts (ie. user) and profiles, you can use the Profile2 module.

You can then use Views to easily crate blocks and pages to list users and information from their profiles.


Now nothing about wp, but in drupal you will have to fire the event when the node is saved and your form field,  "save into wp" is active.

Basically I'd do this with hook node api. Use case "save", check then the field and then fire the function or api which allows you to save the content into wp


Date filter using $row data doesn't return any result

You really shouldn't use PHP in Views have you seen the warning on the module page:

  While this module allows you to directly use PHP inside views which
  may be useful for quick and easy solutions, it is highly advisable to
  use regular handlers and plugins when available (or even to create one
  yourself). Take note that filtering and sorting a view using PHP
  always has a considerable performance impact.

Also this post has instructions how to write a Views handler or Plugin.

You should be able to achieve what you're trying to do with a combination of contextual filters, normal filters and relationships.


All steps described here work for me with some minor modifications.

GOAL: show main menu in both header and footer region, but use a different template file for both (based on their region).
PREMISE: your theme has regions (like header and footer) and you have used the drupal block system to place the main menu in both your header as in your footer.

I did this in mytheme.theme file:
Dont forget to add the Block use statement in the beginning of your .theme file:

use Drupal\block\Entity\Block;

Now here's the magic for region based menu templates. Also inside your .theme file:

/**
 * Implements hook_preprocess_HOOK().
 *
 * Pass block region value to content so this can be used in
 * MYTHEME_theme_suggestions_menu_alter.
 */
function MYTHEME_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    $variables['content']['#attributes']['region'] = $region;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Provide region based menu suggestions.
 */
function MYTHEME_theme_suggestions_menu_alter(&$suggestions, array $variables) {
  if (isset($variables['attributes']['region'])) {
    $suggestions[] = 'menu__' . $variables['menu_name'] . '__' . $variables['attributes']['region'];
  }
}

RESULT when inspecting the main menu inside the header:

<!-- FILE NAME SUGGESTIONS:
* menu--main.html.twig
* menu--main--header.html.twig
* menu.html.twig
-->

RESULT when inspecting the main menu inside the footer:

<!-- FILE NAME SUGGESTIONS:
* menu--main.html.twig
* menu--main--footer.html.twig
* menu.html.twig
-->


Not sure if this is what you want to do but could you just not rename the display name of your tax to 20%?

Go to admin/commerce/config/taxes click edit on your tax and under display title enter 20% tax or what you wish the display name to be.


Can users switch to different Profile2 profiles?

It's up to you whether it is better to duplicate fields 1 - 4 or not. That depends on your specific requirements, what the fields are, etc.

In my experience I generally go with A (1, 2, 3, 4), B (5, 6, 7, 8, 9) and the fields are usually logically grouped into each profile.
For example there might be 2 profiles like "Personal information" and "Employment information" or something like that, which obviously will have their own different grouping of fields, but I can see there may be cases where you might want to go the other way.

One annoyance that you might have to deal with if replicating fields is that when a user switches types they have to enter information into fields they already filled out in the other profile. That would annoy me as a user. You could work around that though and auto fill the fields.

Either way, you can control access to different profile types based on user role.

So the easiest solution would be to configure a role for each of the profiles and then have an administrator add/remove the roles from users as required.

If your use case allows for it there are also modules that allow users to change their own roles (you can limit it to specific roles so they can't make themselves an admin), for example role delegation. This might be appropriate for some websites. Just make sure they can't give themselves any dangerous permissions.


How to sort by title using Search API / fuzzy search?

Finally I got it working – here is how:

Search and metadata » Search API » fuzzysearch index » filter

First I checked the option "Aggregated fields" in the top section "Data alterations". Then I added an aggregated field that I called "Sort Name" pulling data from the field "Name".

Then I added that field to the list of indexed fields in the tab "fields". It is important to change the field type to "string" – otherwise the field won't be available for sorting.

Then finally the field should be available for sorting from the "Sort by" dialogue inside the views form.

The third paragraph of the accepted answer to the question "I have no fields available for sorting with Search API sorts module" pointed me in the right direction: "If a field is full-text, one trick is to create an aggregated field containing just that field and assign it a string type."

…I hope this may help somebody sometime…


You can use the drupal_match_path() function:

$path = drupal_get_path_alias();
$pattern = 'user';

    if (drupal_match_path($path, $pattern)) {
      drupal_add_js('jQuery(document).ready(function () { jQuery("input#edit-name").focus(); });', 'inline');
    }


places where register_globals can be set

I have hostgator account too.
In hostgator and certain other host providers the php.ini that overrides the default values should live in /home/USER/ (i.e. check if /home/USER/php.ini exists, where USER is the username of your hosting account). Make sure that this file has register_globals = Off.

If /home/USER/php.ini is not there then either copy the default (if you have shell access check php.ini location with the command php -i | grep php.ini and then copy this file to /home/USER/php.ini) or ask tech support to help.

More details can be found here on HostGator support site.

Finally, if you are using drush on your host account you might encounter "Register globals detection" issue in which case I would suggest the solution in comment #6, i.e.

cd drush/
ln /home/USER/php.ini php.ini

the resason for this is that drush script (drush/drush) checks for drush/php.ini and if it does not find it there it detects the default php.ini not the /home/USER/php.ini one.


drush_get_commands() does not return Feature Drush commands

It is important to remember that drush_get_commands() is sensitive to the bootstrap level that your command has reached.  You must have bootstrapped a Drupal site before Drush commands associated with modules in that site are available via drush_get_commands().  There are several requirements for this to be true.

You must have selected a Drupal site when you ran your custom Drush command, either by using a site alias (e.g. drush @mysite), or via commandline options (e.g. drush --root=/path/to/drupal --uri=mysite.org), or by setting your current working directory to the same directory that contains the settings.php file for your site.
Your custom command must declare a bootstrap level that is high enough to bootstrap a Drupal site.  For example, DRUSH_BOOTSTRAP_DRUSH is not sufficient, but DRUSH_BOOTSTRAP_FULL is.  If your command has not bootstrapped to a high enough level, you may call drush_bootstrap_max() to finish bootstrapping the selected site.
Drush commands will only be loaded for enabled modules.

If you do all of these things, then you should see all commands for all modules when you call drush_get_commands().  If you don't, try drush cc drush to clear the commandfile cache.

(As a side note, do not use drush_get_commands() as a way to call other Drush commands from your custom commandfile.  Instead, use drush_invoke_process().)


Hide empty results in views caused by entity translation?

THE SOLUTION: after three days, i got that if you use entity translation in the 'entity' mode, you get some option in Views filters. In my case, only the field "body" in nodes was translatable and there was an option, among filter

Body's language

Setting this to "Current user's language" does the trick.

I heard about an option Node Translation to be set this way, but you don't have that option if you check as translatable only some field and not the whole node.


Drupal Commerce Kickstart cloud zoom image not working?

I would suggest using the following modules (since it basically creates this straight out of the box). Once you customize it you can define how you want hte widgets to appear and essentially create the view as you have outlined above.

Views Slideshow
Views


allow user to sign up for different role

Organic groups can do it however it requires a legthy process form the user. Eg. a manager must create a group (the creator of the group is also the manager of it by default). Then users that wish to join the group must go to the page of the group and request to subscribe. The good thing with og is that it also supports the concept of og content. That is you may create a content type and denote it as og content of a specific group. Then only the members of this group will have permissions to a node of this content type.

Another option is to use a plain old field in the user registration form that will be a list with the desired role. You can do this by going to the user configuration page. Then you can add a rule to automatically grant the requested role to every new user (a simple value comparison in rules) or create a manager view so the manager can see which user wants a role and grant it. The vbo module can help the manager in the later case.


Cannot create custom config entity fails because ID is blank

My understanding is that the entity system will create an ID for this entity, but it doesn't seem to be working in my case. I'm struggling to figure out what I need to change to get this work:

That understanding is wrong. Config entities have machine names as ID's, you have to provide that. Most UI's generate one from the label, but that's form/UI code, the API has no such thing.


You can do by using Field Permission module.

Or first you have to create a user role. And apply condition to fields as per role.

Or you can use User Role Field module.


Solution acording to @Vaibhav tip...

// node__view__submenuessmall is used in view
// for creating block menues with images
// when same node is used in menue and on page
// wrong theme_hook_suggestion is used on page

function cuter_preprocess_node(&$variables){
 if(array_key_exists('theme_hook_suggestions',$variables))
  {
    $lastVar = count($variables['theme_hook_suggestions'])-1;
    if($variables['theme_hook_suggestions'][$lastVar]=='node__view__submenussmall')
    {
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
      $variables['theme_hook_suggestions'][$lastVar]='foobar';
      //dpr($variables['theme_hook_suggestions'][$lastVar]);
    }
  }
}


Using jQuery we can

(function ($) {
  // Go back
  $('a.back').click(function(){
     parent.history.back();
     return false;
  });
})(jQuery);

and add class="back" to your link

Back


how to set a variable in module and get it in theme

HOWEVER:

You should really look into the various _preprocess() hooks.  From further commentary below, I am thinking that's where you should be doing all this.

ORIGINAL ANSWER:

If you don't want to use the system wide variable_set() or variable_get() you can always set a variable in the global $_SESSION array that would be seen by the current logged in user only, eg,

if ( // whatever ) {
  $_SESSION['MYMODULE_variable_name']= // whatever
}

SUPER DUPER OVER SIMPLIFIED ADDITION:

function MYMODULE_foo($value=NULL) {
  static $bar;

  if ($value) {
     $bar=$value;
  }

  return $bar;
}

accomplishes it inside your module, eg, you can do:

MYMODULE_foo('this is cool');

and then in your theme do:

$baz=MYMODULE_foo();


Ubercart entries in menu_links table causing performance issues

Can you give this patch a try? I can't answer you're question directly but I think this might help with all the user loads http://drupal.org/node/1710656#comment-6474030


How do I let my users create organic groups?

see documentation for Drupal 6 http://drupal.org/documentation/modules/og or Drupal 7 http://drupal.org/node/1114852.


How can I create a link from an organic groups content node back up to the parent OG?

burnsjeremy was right that the information I need is available to my node itself. To get this into a views block to position in a different place etc I can use contextual filter on 'Content: Nid' and 'When the filter value is NOT available' set the 'default value' to 'Content ID From URL'. I can then add the fields as normal via views.

Next will be the challenge of getting the parent group of a child group when on the node of a piece of content within the child group.


How do I get a field label by the field name?

The label is set per instance (not per field) so you would use the field_info_instance() function with some appropriate arguments:

$entity_type = 'node';
$bundle_name = 'article';
$field_name = 'field_some_field';

$info = field_info_instance($entity_type, $field_name, $bundle_name);

$label = $info['label'];

There's a bunch of other useful functions in the Field Info API documentation that might be helpful in case you haven't seen it already.


Drupal submits the entire form at every ajax call, I think you'd have to use hooks before submit, before send or similar to prevent it. Heres something to get you started. Or simply put the file field last or at least after the ajax form elements.

Disable all form elements when doing AJAX

Ideally drupal should allow you to specify what you want to submit. please share your solution if you figure it out.


Why would a multilingual site sometimes say "Save (this translation)" and other times say "Save (all translations)"?

The text of the submit button depends only on the translation settings of the status field. If the field "Publishing status" is not translatable for the content type, the button says "Save (all translations)".

You can change the language settings for content types, taxonomy vocabularies, user profiles here: /admin/config/regional/content-language


looping an image field with multiple values? alt or text?

You can follow the below code. Please change 'field_flexslider_example_image' with your field name in content type.

<?php
$node = node_load($nid);

$image = field_get_items('node', $node, 'field_flexslider_example_image');

foreach ($image as $key => $value) {
$output = field_view_value('node', $node, 'field_flexslider_example_image', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail', //place your image style here

  ),
));

$image_url = file_create_url($value['uri']);
$alt = $value['alt'];
$title = $value['title'];

print '
';
print '';

print '';

print '';

print '' . $title . '';

print '
';

}
?>


How do I get the associated node from a webform entity?

After some digging, I've found out the answer.

This is how I get the webform submission, the webform object, and the associated node:

    function MY_MODULE_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

        $entity  = $form_state->getFormObject()->getEntity(); // webform submission
        $webform = $form_state->getFormObject()->getWebform(); // webform object
        $node    = $entity->getSourceEntity(); // associated node

        // (...)
    }


User list view showing total nodes created for each user

If I understand the question this can be done in Views using aggregation.

Set up a View to list All Content (not users). Select Unsorted. Show fields rather than teasers.
Double check you really don't have any sorting in the Sort criteria section. If you do, it'll mess up the aggregation settings. If you forgot, remove it now. I know I'm repeating here, but if you don't do this you run the risk of driving yourself crazy wondering why aggregation doesn't seem to be doing what it's supposed to.
Add the Content: author relationship (in the Advanced section). This is so you can gain access to the the name field for the user.
Add the 'User: name' field (in the Fields section).
Turn on the Use aggregation option (in the Advanced section under Other).
Change the Aggregation settings for the Content: Title field. Set aggregation to COUNT. This will count up all titles authored by the same user.
If you need sorting, e.g. in descending number of posts, you can add that. But make sure under sorts you set the aggregation settings correctly, e.g. to COUNT. Alternatively, leave the Sort criteria section empty and sort via the Table format.

That's the tricky bit. If that's all working you can refine the output with Global: Custom Text fields or use of tables.

Your view configuration will look at bit like this:

Note: if you user entity has extra fields, e.g. for a richer user profile or for name variants etc. you may be able to access these through the 'Content: author' relationship. Or you may need to add another relationship.


Write complex access control in a reusable way

For access control on routes, you can write a service which implements AccessInterface.  At its simplest, this is just a class placed in a module's src/Access folder with a single method public function access(AccountInterface $account), returning a flavour of AccessResult.  Then you simply register your class in the module's services.yml, annotate the route to use that access checker and Drupal will do the rest.  Relevant documentation

The documentation suggests that if the route being access-checked has an upcasted parameter like {node}, then you can add $node to function's arguments - i.e. public function access(AccountInterface $account, Node $node) and it will be automatically supplied.  I haven't actually tried that part myself though.  Assuming it works, you can then access the node's fields as normal in order to compare the entity ids of the mother/father fields with the user to which the $account belongs.

I'm not sure if there are similar ways to automatically invoke this same access check for displaying entities with different view modes, but at the end of the day it is just a service like any other, so you could always request it from the container or inject it into whatever other controllers / services / hooks you need.  In these contexts you will of course have to 'manually' supply the current user $account and relevant $node to check.


What file permissions and ownerships are appropriate for the files directory and subdirectories?

It depends somewhat on your server configuration but it doesn't have to be 777, and in fact it should not be 777 as that is a security issue.

The web server user (on your server, not your drupal site) is what has to be able to write to the files directory. Whether the drupal user is logged in or anonymous is unrelated.

For information on this see http://drupal.org/node/244924


Pathauto patterns produce segment duplicates

Use just [node:menu-link:parents:join-path]/[node:menu-link:title] and make sure that you set the root node's URL alias manually as 'wiki'.


Programatically create node + panel configuration?

For some people, Panel Nodes is good enough. Depends on your circumstances.

The below will create a panel node with 2 column bricks layout and will use the In Place Editor (IPE):

$node = new stdClass();
$node->title = t('Home');
$node->type = 'panel';
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->status = 1;
$node->promote = 0;
$node->comment = 0;

$node->panels_node = array(
    'layout' => 'twocol_bricks',
    'css_id' => NULL,
    'pipeline' => 'ipe', // change this to "standard" if you don't want to use the In Place Editor (ipe)
);

// node_submit() populates the node with author UID and creation date
$node = node_submit($node);
node_save($node);


After going through all of your replies and a few internal discussions in my company, I have decided to modify the Quiz module's code by creating and applying a patch, quiz_notice_messages_in_result_screen.patch.

As per the information provided by Alfred Armstrong's the said patch will be solely used for our company's internal purposes, so as to find a way around the Drupal's general practice of reporting a contrib module's issues and suggesting patches for the same.

Below are the contents of the quiz_notice_messages_in_result_screen.patch file.

diff --git a/modules/contrib/quiz/quiz.module b/modules/contrib/quiz/quiz.module
index dd2b88c..e551aac 100644
--- a/modules/contrib/quiz/quiz.module
+++ b/modules/contrib/quiz/quiz.module
@@ -2075,13 +2075,19 @@ function quiz_take_quiz($quiz) {
     $_SESSION['quiz_' . $quiz->nid]['quiz_questions'][0]['rid'] = $_SESSION['quiz_' . $quiz->nid]['result_id'];
     $_SESSION['quiz_' . $quiz->nid]['previous_quiz_questions'][] = $_SESSION['quiz_' . $quiz->nid]['quiz_questions'][0];
     $former_question_array = array_shift($_SESSION['quiz_' . $quiz->nid]['quiz_questions']);
+    if (empty($former_question_array['nid']) || empty($former_question_array['vid'])) {
+      $former_question_array['nid'] = $quiz->nid;
+      $former_question_array['vid'] = $quiz->vid;
+    }
     $former_question = node_load($former_question_array['nid'], $former_question_array['vid']);

     // Call hook_evaluate_question().
     $types = _quiz_get_question_types();
-    $module = $types[$former_question->type]['module'];
+    $module = empty($types[$former_question->type]['module']) ? '' : $types[$former_question->type]['module'];
     $result = module_invoke($module, 'evaluate_question', $former_question, $_SESSION['quiz_' . $quiz->nid]['result_id']);
-    $q_passed_validation = $result->is_valid;
+    if(isset($result->is_valid)) {
+      $q_passed_validation = $result->is_valid;
+    }
     $check_jump = TRUE;
     if ($q_passed_validation === TRUE) {
       quiz_store_question_result($quiz, $result, array('set_msg' => TRUE, 'question_data' => $former_question_array));

Thank you No Sssweat, Alfred Armstrong and Alan Dixon for your inputs.


Duplicate part of the main menu to a sidebar

in nice menu you can select parent menu item to render, also you can achieve this with views tough


Sort by weight using \Drupal::entityQuery()

Taxonomy overview list uses something like:

  ->sort('weight', 'ASC')
  ->sort('name', 'ASC')

If that doesn't work for you, take a look at \Drupal\taxonomy\TermStorage::loadTree


Why can't my module install a database table?

The argument to drupal_install_schema() is the module name, not the table to install.

Generally speaking (and assuming you might have more than one table eventually), if you want to create all tables that are defined in hook_schema(), use:

drupal_install_schema('my_module1');

If you just want to create that one table:

$table = drupal_get_schema_unprocessed('my_module1', 'my_module1_node_views');
db_create_table('my_module1_node_views', $table);


How to add a CSS class to field label and items div?

have you try hook_preprocess_field().

please check this link everything is given in this blog may be it help you
http://atendesigngroup.com/blog/adding-css-classes-fields-drupal


You can create a template file for that image  field and there you can edit the image display as per your condition . You can get the name of the template file from your views (Theme: Information)


list of parent nodes with a list of child referring nodes

probably you're using Node reference, right? If this is your case the solution is quite simple.

1) Create a view with a contextual argument for displaying all the children of a specified parent.

2) Use Display Suite module to attach this view on a custom display mode of parent nodes. With display suite you can pass the current nid to the view argument. You can also use Views Attach module ( https://drupal.org/project/views_attach )

3) create a view with the list of every parent and set to show the customized display created before.

I hope this will help you.


Sounds like Node view count module would be suitable, especially as it integrates with views.


AWS RDS and Multiple Database Installation

Finally got it. :)

Here are the steps I took on a RDS under a VPC:

Created each Database individually on MySQL and then dumped each DB.

To log into your RDS MySQL:

mysql -h RDSEndPoint.rds.amazonaws.com -P 3306 -u MasterUser -p

To dump

mysql -u MasterUser -p -h RDSEndPoint.rds.amazonaws.com DB_Name_on_MySQL < /my/file/location/SQL_FILE.sql (You might need to change the .sql to .mysql)

Once you have your DB's set up and ready to go, change your /var/www/html/MySiteFolder/sites/default/settings.php file

To

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB_Name_on_MySQL',
      'username' => 'MasterUser',
      'password' => 'PASSWORD',
      'host' => 'RDSEndPoint.rds.amazonaws.com',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You might receive this error (https://www.drupal.org/node/2394349):

Command updatedb needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.       [error]

The drush command 'updatedb' could not be executed.                  [error]

A Drupal installation directory could not be found                   [error]

You can run the following two commands on where each of your sites index.php file is located:

drush dl rules
drush updatedb

You should be able to see your site now! If I'm missing something I would be glad to add it for future reference.


Adding form type item did the trick:
$form['my_incomes'] = [
      '#type' => 'item',
      '#markup' => $this->t('My other incomes'),
      '#states' => [
        'visible' => [
          [':input[name="marital_status"]' => [['value' => 'single'],['value'=>'couple']]],
        ]
      ]
    ];


Changing values in preprocess view function

The MYTHEME_preprocess_views_view($vars) hook is executed at the end of the process to build a view. The purpose of the views_view.tpl.php is a general wrapper for all elements of the view. The result of fields have been builded and rendered and they have been stored in the variable $vars['rows'].

If you want to change, alter, unset a view, we can do in different phases. Between them, i've chosen the pre-render phase:

function HOOK_views_pre_render(&$view) {
  if(isset($view->name) && $view->name == 'YOUR_VIEW'){
    // kpr($view);
    foreach($view->result as $r){
      $r->field_field_NAME[0]['rendered']['#markup'] .= '. ADDING TEXT TO CHANGE THE RESULT';
    }
  }
}

These are the stages that are given by Views API (you will find it in the views folder). Maybe one of them is more useful:

hook_views_pre_view(&$view, &$display_id, &$args) {}

  Allows altering a view at the very beginning of views processing, before
    anything is done.

hook_views_pre_build(&$view)

  This hook is called right before the build process, but after displays
    are attached and the display performs its pre_execute phase.

hook_views_post_build(&$view) {}

  This hook is called right after the build process. The query is now fully
    built, but it has not yet been run through db_rewrite_sql.

hook_views_pre_execute(&$view) {}

  This hook is called right before the execute process. The query is now fully
    built, but it has not yet been run through db_rewrite_sql.

hook_views_post_execute(&$view) {}

  This hook is called right after the execute process. The query has
    been executed, but the pre_render() phase has not yet happened for
    handlers.

hook_views_pre_render(&$view) {}

  This hook is called right before the render process. The query has been
    executed, and the pre_render() phase has already happened for handlers, so
    all data should be available.

hook_views_post_render(&$view, &$output, &$cache) {}

  Post process any rendered data.


Here is a javaScript version that may help after alot of trial and error I could only get "entity/file?_format=hal_json" to work aka "file_entity" module.

the following "bace64" = iVBORw0KGgoAAAANSUhEUgAAAG8AAABvA.....

uploadDrupalImage(bace64) {
  // Could only get hal_json to work.
  var dataToPost = '{"_links": {"type": {"href": ' + JSON.stringify(this.baceUrl + 'rest/type/file/image') + '}},"filename": [{"value": "' + this.state.file.name + '"}],"data":[{"value": "' + bace64 + '"}]}';
  var url = this.baceUrl + 'entity/file?_format=hal_json';
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': this.state.csrf_token,
      'Authorization': this.state.basicAuth,
    },
    body: dataToPost
  }).then(response => response.json()).then(data => {
    if (data) {
      this.setState({uploadedFile: data});
      if (data.fid) {
        //console.log(data.fid[0].value);
        this.setState({fid: data.fid[0].value});
      }
    }
  }).catch(err => console.error(err.toString()));
  return false;
}

taken from (when i was just learning react so be kind lol) https://github.com/taggartj/Drupa_react_REST_examples/blob/master/src/components/drupal/DrupalCreateArticleWithImageBasicAuth.js


This is possible by implementing hook_search_preprocess() and integrating with the Transliteration module.  Example code is below:

<?php
/**
 * Implementation of hook_search_preprocess().
 *
 * Transliterates text added to the search index and user submitted search
 * keywords.
 */
function mymodule_search_preprocess($text) {
  return transliteration_get($text, '', language_default('language'));
}
?>

There is a more complete example and discussion at http://drupal.org/node/1058064.


Unpublished content type using rules module based on user role

Are you using rule sets and triggered rules?

You should use a Rule set to set the conditions for the specific role and unpublish the content.

Then use the triggered rules to schedule the rule. E.g. When a user updates content run the Rule set


Can I create a link to a nodes taxonomy page?

There's a default path that links to taxonomy/term/term_id. For instance if the term_id for the term Self help books is 42, the following path will list all self help books.

taxonomy/term/42

Now, to replace this with the appropriate string, navigate to:

Home » Administration » Configuration » Search and metadata » URL aliases

and specify that Self help books should be an alias for taxonomy/term/42.

First, make sure all nodes that you want listed as self help books is tagged with the tag Self help books.

Then, to create a link to the nodes tagged with a specific term based upon vocabulary, you need to install and enable the Token module and the Token Filter module (unless you've already done so).

Next navigate to:

Home » Administration » Configuration » Content authoring » Text formats

and click Configure on the text format (or formats) you plan to use. Under Enabled filters. make sure the filter named Replace tokens is activated.

You can now see the what tokes that exist by going to:

Home » Administration » Help » Token

and expand the Nodes item.  Let us say that your book category field is named node:field_book_category.

Then, if you put an HTML link like this somewhere on a page tagged with Self help books:

View more [node:field_book_category]

you will get a link back to a page listing all nodes tagged with Self help books.

This will of course work with any other taxonomy term (e.g. sport books, cooking books, etc.) as well. However, the node can only be tagged with a single term from a particular vocabulary for this method to work.

Note: For this to work, the node must actually be tagged with exactly one taxonomy term from the relevant vocabulary.  You can easily check that the node is tagged this way: When you view the content of the node, the taxonomy term or terms it is tagged with is automatically inserted by Drupal with link to a list of all nodes tagged with the term. If this link does not appear, then the node is untagged. If multiple links appear, then there are multiple taxonomy terms. If the node is untagged, there will be no token replacement and the token will appear as plain text. If the node is tagged with multiple terms, then the token will expand into a list of taxonomy categories, and can no longer be inserted in a single link.

PS: As an alternative solution you can override the template for the node (node.tpl.php), you can replace the simple link mentioned in the previous paragraph with the string "View more" followed by the link.  This also work if there are more than one tag from the vocabulary on the page.


Admins that only control a subset of users

It looks like you're looking for Organic Groups.

[Organic Groups] Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

It is a fairly complex module, but I think it is very well suited for your use-case.


Drupal 7 Theme [Business] not pulling in to non-front pages

If you want page specific theme'ing, look at themekey module:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.


I solved the problem by adding an image field on the remote video media entity and then altering the media entity on presave, like this:

/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'media' && isset($entity->custom_thumbnail->entity)) {
    $entity->thumbnail->target_id = $entity->field_media_image->target_id;
  }
}

The image field is called field_media_image.


The $form_state array variable contains all the information about the current state of the form. print_r($form_state) to find out the array key corresponding to the upload element in the form. If there is no new upload, this array key should have an empty value, or maybe the array key won't exist at all. If for example $form_state['upload_element'] is populated, then you can call file_save($file);.


How can I change tag separator from "," to "+"?

you can use a hook_form_FORM_ID_alter. I used this validation to make sure users use commas instead of spaces:

function MYMODUDLE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
 $form['#validate'][] = 'custom_form_validate';
}

function custom_form_validate($form, &$form_state) {
  $tags = $form_state['values']['field_MYNAME_tags']['und'];
  foreach ($tags as $tag) {
    if ((strlen($tag['name']) > 15) || (substr_count($tag['name'], ' ') > 1)) {
      form_set_error('field_MYNAME_tags', 'Please enter tags separated by commas');
    }
  }
}


Why doesn't a form immediately call its submission handler?

To understand this, we should step back a bit in look at how forms are used regardless of what CMS (if any) is in use.

All <form> tags have an action attribute which define what page the browser should send the data to. If action is left blank (or missing) the browser will assume it should send the data to the same URL it is currently on. In this scenario the URL will be loaded to get the form and then again to send the data.

This is how the Form API works (by default). When you define a URL (using hook_menu I presume) that presents a form to the user, the browser will use the same URL to load and send the form.

The menu router in Drupal has to be run first so it can determine what page to display. Only after that does Drupal see that it has a form and then run the submit callback. In other words, you cannot change the order of these functions.

You can provide an #action attribute in your Form API implementation which (combined with a new hook_menu entry) should let you separate your form load/submit functions.


Caching pages with boost based on a cookie value

Ok, it took me a while, but I solved it. It lead me to learn some interesting details about Apache and Drupal.

In my question above I wondered why the rewrite rules did not alter the QUERY_STRING in Apache because apparently, the correct page was not fetched from the cache. However, the problem was not that the correct page was not fetched, but that the correct page was not written to the cache in the first place.

Looking into the code of Boost showed that it uses Drupal's request_uri() function to determine the name of the cache file. This function in turn uses PHP's $_SERVER['REQUEST_URI'] if set. Some tests in PHP then showed that the rewrite rules do actually change $_SERVER['QUERY_STRING'], but that this change is not reflected in $_SERVER['REQUEST_URI']. In other words, the query parameters in $_SERVER['REQUEST_URI'] are the ones of the original request, not the ones as potentially rewritten by mod_rewrite.

To solve this, you can add some code to (for example) Drupal's settings.php to update $_SERVER['REQUEST_URI'] similarly as done in your .htaccess. This worked for me:

if(isset($_SERVER['REQUEST_URI']) && isset($_GET['cookie'])) {
  $cookie = $_GET['cookie'];
  if(strpos($_SERVER['REQUEST_URI'],'?') === false) {
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . '?cookie=' . $cookie;
  } else {
    // I'm not sure what happens if &cookie is already set
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . '&cookie=' . $cookie;
  }
}

Note 1: $_GET does contain the rewritten request parameters, so I guess this is based on QUERY_STRING.

Note 2: code above only adds my application-specific cookie. I guess a generic solution would be to completely remove the request string of $_SERVER['REQUEST_URI'] and add all elements in $_GET again.

Note 3: you need both the rewrite rules in .htaccess and this code in settings.php. The former are needed to have Boost fetch the correct page from the cache, the latter to have Boost write the correct page in the cache.


Drupal 6 - create second contact form with redirect after submitting

I think that you need to install the Webform module:

http://drupal.org/project/webform

There might be ways to do this with the Rules module, but I think for overall simplicity, Webform is the way to go.

I'm pretty sure that the version for Drupal 6 allows a custom message to be displayed to the user. In fact, if memory serves, it also has the option to redirect to a particular page.


I prefer the Lightgallery module which is available for Drupal 7 and Drupal 8 also. It integrates the lightGallery jquery plugin into Drupal. This is compatible with Views and it also provides an image field formatter.

You can see demos for the lightGallery jquery plugin here.


Get data and uploaded files from android (mobile) version of website

YOu need to provide services using RESTful API to mobile app developer. Required modules are services, services definition and rest server through it you can connect to mobile application because it returns json or xml. Thorugh our site endpoint. Further you can go to its tutorial here.


Manage display of geofield with wkt input widget

Some suggestions:

make sure that you edit the right format when you filled in the wkt.
check for any errors in the installation of the map.

I had the same problems in the beginning with mapping too. I had an error in the installation of my leaflet map. In the end I solved it with a new installation and I geocoded the geofield from my address field.


You could Create a Custom Service Resource for this, but IMO it's easier to do this:

Enable the Views JSON module (which is a sub module of the Views datasource module). This will allow you to get JSON output from a View.
Build a JSON data document page display for a View
Add a contextual filter for a node id, this value will be grabbed from the URL path
Add a contextual filter for a user id, this value could be grabbed from the URL path, or default to the current logged in user, that's up to you
Add a relationship to the flag in the View
Add your desired field output and watch the results preview to see your JSON assembled
Add the necessary filter(s) to limit the results to a certain user/flag/etc.

You then can consume this "resource" by doing a GET on the page path to your View.


I worked out a way to do it.

Create a block with some custom PHP.

<?php

//Find current nid
if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);

//Load that node
$node = node_load($nodeid);

//Get referenced entity if it exists
if (isset($node->field_videolink['und'][0]['target_id'])) {
    $refnid = $node->field_videolink['und'][0]['target_id'];

    //Now load that node
    $node2 = node_load($refnid);

    //Display the body
    print($node2->body['und'][0]['value']);
};

?>

The entity reference field is called 'videolink'. You should enable the block only for the quiz content type otherwise you'll get an error on the home page.

Apologies if the PHP is a little shoddy. I'm not an expert by any means.


Use a file token for directory path when uploading a file via core file upload field?

In core this is not possible, because the file widget sets the #upload_location when it builds the form element.

You need a module, for example File (Field) Paths. This module sets a temp path in #upload_location of the form element and sorts this out later when the file and node entity are available.


Why can't I edit "Settings" on rules components in the Rules UI?

I had this problem when using entity-rc1.  Upgrading to entity 1.0 resolved the issue for me.


How to display the average of the votes of a rating field from a form made with webform (D8)?

Check out the Webform Analysis module.

  This module is used to obtain statistics on the results of form
  submissions.


How to display node when view contains only 1 item?

My approach is to count the views result first. If the result is only one I will get the node id and load it using entity_load_single and render according to whatever you want.

Pseudo code:

function hook_name_or_callback() {
  // Get the view.
  $view = views_get_view($view_name);
  // Based on $view you can get the views result.
  if (result_is_one) {
    $node = entity_load_single('node', NID);
    $node_view = node_view($node);
    return drupal_render($node_view);
  }
  else {
    // Just display the view.
  }
}

P.S: Haven't test this code and might not work for you.

See these:

https://api.drupal.org/api/views/views.module/function/views_get_view/7.x-3.x
http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity_load_single/7


How to use a translated taxonomy in autocomplete term-reference fields?

Are you using 'Entity Translation' or the core 'Content translation'?

I think the sub-module Multilingual select (from Internationalization) should handle this for 'Content translation' (didn't test it, though).

But for Entity Translation, this doesn't seem to work (yet): see Entity translation and the Multilingual select i18n submodule interactions and Language aware edit form and autocomplete.


How to create file->node relations use relations modules?

[Resolved]
1. Create relation between Node and file
2. Create a view for relation and only view out all related file
3. setting view to relation select values


Why do I get a fatal error when clicking on the permissions tab in admin/people?

If you are running multisite, you probably need to modify your settings.php on each sites.


8: How to specify multiple css media types in a libraries.yml file

css/styles.css: { media: "screen,print" }      # outputs media="screen,print" (WORKS!)
css/styles.css: { media: ['screen', 'print'] }  # outputs media="screen print"


It's looking like you have Views 2 installed, so, make sure you have the right Views Slideshow module installed as there is one for Views 2 and another for Views 3 per the Views Slideshow Module page on drupal.org:

Requirements

Views Slideshow 2.x requires Views 2.
Views Slideshow 3.x requires Views 3.


Context condition per menu (not menu item)

There doesn't seem to be a way to select a menu itself in Context Conditions.

Maybe you have something else common among those menu items that you can combine in different Conditions to get the same result? Maybe paths are similar? Or Content types?

Alternatively you can use a module other than Context just for this particular need: Blocks per menu.


How to add custom path for taxonomy term page

Here is sample code that will allow you to redirect all taxonomy paths to a custom URL.

function sample_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_sample_taxonomy_term_uri';
}

function _sample_taxonomy_term_uri($term) {
  return array(
    'path' => 'path-to-your-view/' . $term->tid,
  );
}

Hope this helps.


How to display the number of images contained in a node using Views?

Install the module: Field Count Formatter

  A very simple module to provide a formatter for all field types. The
  output is simply a count of the number of items in that field. This is
  most useful on fields which have multiple values as it will show how
  many values are in this field.

Then in the teaser display for your content type, add the image field and set the formatter to count.


How to create and view a clickable list of information on a user profile?

Seems like you're looking for something like what I'd call some type of "drill down" facilities. Have a look at the Master Summary with drill down example. Click on some of the links in the tabular report (or bars in the chart ...), to get some related report (for the link you followed). Think of "states" as the equivalent of your "invoices" to get the idea.

The above sample is created with the Forena module. After you install it in your own environment, you'll have access to another set (category) of reports, related to "Drupal Administration" (applied to your own site). One of the reports in it is the "Logs for User" report (located at /reports/drupaladmin.user_logs). It'll show you a summary of watchdog entries (for the user you selected). And the resulting report includes a link "Details" for any of the watchdog records shown, which you cann use (follow) to get way more details about the specific watchdog record. The format of such "detail" is shown in a format that is pretty close to your "Invoice details" screenprint.

Here is a screenprint of another (custom) report that also includes such drill-down facilities (don't look at the actual formatting of it):

The (red) numbers in it are actually hyperlinks which you can use to get the actual Watchdog details (corresponding to the link you selected). The (collapsed) "Report Execution Parameters" can be expanded to "filter" the data to be included in the report. Even though it's a custom report, it is pretty forward to build such kind of reports, e.g. using Forena's WYSIWYG report writer and/or WYSIWYG query builder.

The above is about displaying (reporting) all such data. To also be able to "add" new records (invoices), you could expand the so called "frx" files (which is just plain XHTML), to insert something like an hyperlink to "add a new invoice". Such link would then probably correspond to something like node/add/invoice (assuming the machine name of your content type is invoice). Optionally you could also use a destination parameter in such URL to return to the "report" after the new node (invoice) was added.

Disclosure: I'm a co-maintainer of Forena.


How to make custom Drush commands to work on remote instance

I believe the remote site also has to have the commands as well in order to execute successfully.


If your looking at code, all the hook_menu function calls is how the non alias paths get created. Things like users and nodes use a % in the path creation; this turns into the argument for the page callback function. Read more about this here: Wildcard Loader Arguments.
node_menu()

function node_menu() {
...
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK,
  );
...
}

user_menu()

function user_menu() {
...
  $items['user/%user_uid_optional'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'parent' => '',
    'file' => 'user.pages.inc',
  );
...
}

The function that handles this menu information is menu_execute_active_handler().
Aliases happen as the 2nd to last part of the bootstrap in the drupal_init_path function. It converts /about-us into node/4 for internal use.

For more in depth information check out this link: Drupal menu system (Drupal 6.x)


Is there a way to create hierarchical taxonomies checkboxes?

Taxonomy is hierarchical by nature, you can create category/sub stuff in it.

AFAIK, there is not any field widget as you describe in drupal core with taxonomy field. Maybe some contrib module (have a look at term_reference_fancytree ).

You also may define your own and generate a field widget dedicated to taxonomy.


Create a Redirect for a page if its unpublished / deleted

There is a module that does much of what you describe: Save Redirect on Delete.  It will push the user to a predefined page and you could put popular items on that destination page.

If you want the recommended content to be customized for the page they tried to reach you'll almost certainly want to build something custom. This module would probably give you a starting point, but in addition to what it provides you'd also need to preserve some kind of taxonomy reference (or similar) information to be able to provide something sensible.


How can user select attributes for a product when clicking on an add-to-cart link?

Very old one but why not answer?

Use Ubercart Cart LInks module (included in Ubercart Core). I think it allows links that operates on the cart, like empty cart or add a product what I guess includes product attributes.

Here it's explained, but is very old page, check module documentation.

http://www.ubercart.org/node/1427


How to parse current page URL query parameters to create link using l() function

Maybe something like this would be sufficient?

$url = drupal_parse_url('example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.');
$desired_params = array_intersect_key($url['query'], array_flip(array('check-in', 'check-out')));

array_intersect_key() will return the values in the first array whose keys also exist in the second array, while array_flip() inverts the values in the array with their keys, actually generating something like the following (in my example):

array(
  'check-in' => 0,
  'check-out' => 1,
)

You can probably use the same approach or a very similar one with view::get_exposed_input, which is probably the best way of getting the data you need.

I didn't get that you also needed to rename the parameters. Then I don't think there's any advantage in filtering the parameters, just pull out the ones you need by hand.

$params = drupal_parse_url('...');
l("link_name","http://www.example.com/path",
  array('attributes' => array('target' => 'blank'),
  'query'=>array(
    'lang' => 'en',
    'currency' => 'USD',
    'standardCheckin' => $params['query']['check-in'],
    'standardCheckout'=>$params['query']['check-out']
   )
  )
);


In the view UI, choose a php field type

and your custom php code can be entered here:


Assign different taxonomy terms to translations of content

If you don't want the node translations to share the terms they are tagged with you need to make the Taxonomy term reference field translatable. Then you will be able to enter different values into that field depending on which language you're editing.

You can enable the translations for Fields under Configuration > Regional and language > Content language and translation (/admin/config/regional/content-language).

Tick the box for your Taxonomy field and hit the "Save configuration" button at the bottom of the page.

After that you'll be able to save the translations with different values for that field than the original. The translations in languages other than the default one will probably have that field empty before you edit them, they will not "inherit" the values from the default translation out-of-box.


Share a value between two different hooks

In Drupal 7, drupal_static() could be used too, if the stored value doesn't need to be persistent between different pages.

drupal_static() is normally called as drupal_static(__FUNCTION__, $default_value), but if you use the name of the function, you can access the same value accessed from the function that calls drupal_static().

Using variable_set() and variable_get() the value is persistent between different pages, and it is not automatically removed. If the first hook execute code similar to the following one, then the second module would get an older value.

if ($condition) {
  variable_set($variable_name, $value);
}

Rather than using such code, the first hook should execute code similar to the following one.

if ($condition) {
  variable_set($variable_name, $value);
}
else {
  variable_del($variable_name);
}

Whatever method you choose, be sure the hook reading the value is effectively running after the hook setting that value.


Using Drush To Download Modules When You Dont Really Know The Name

Well I think your imagination did the trick! but the closest thing I can imagine is to use this sandbox module

  Allows you to search for modules from drush


The trouble is, hook_page_alter() is called after your theme function is called.  So if you're setting things there it's too late.

I don't know why you're doing it this way.  Why not generate your suggestions in your page callback: mymodule_page_not_found().  Then pass them to the theme function.

Something like this:

/**
 * Implement hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_page_not_found' => array(
      'template' => 'templates/404', // Not relevant to your question, but you should consider renaming this to mymodule-page-not-found because of a "bug" in D7; see discussion here: https://www.drupal.org/node/342350
      'variables' => array('suggestions' => array()),
    ),
  );
}

function mymodule_page_not_found() {
  // ... generate list of $suggestions ...
  return theme('mymodule_page_not_found', array('suggestions' => $suggestions));
}


how to get values from two content types using one entity reference

If all 3 Content types need to be interrelated then it makes sense to use the same Entity Reference Field to connect them (two CTs both use the same Field to reference the third CT).

But this isn't a requirement, it just makes some things easier if using Views to display information from one CT node on related CT nodes. While this can be solved using Views there is an easier way.

Use Content view modes to control ER Field display

The easiest way to control which Fields from the referenced node an Entity reference Field should display is to use Content type Fields view modes (not related to Views module).

You can see available view modes on the Manage display page of a Content type, at the bottom under Custom display settings.

You need to enable an existing view mode or create a new one on your Product and Purchase Content types, so they can be used for ER Field on Sales CT.

Select the view mode you want to use (Manage display page) for this purpose and on Product CT hide all the Fields except the product name.

Similarly, on the Purchase CT view mode you selected for this purpose hide all the Fields except MRP.

Then on Sales CT Manage display page (I'm assuming you have two different ER Fields, one for each CT referenced) select Rendered entity as your ER Field Format for both Fields, and change its configuration to use the view mode you configured in previous steps.

This way when you visit a Sales node it will show product name and MRP Fields from the referenced nodes instead of their node titles.

Create new Content view modes in D7

You might need to create a new view mode for this purpose. In D7 it doesn't come out of the box (as it does in D8), but you can create new modes with the help of an additional module or a very simple custom module. Read all about it in this article: 3 Easy Ways to Create View Modes in Drupal 7.

Display information from another node

To display one node information on a different page (in your case you want to display MRP field from a Purchase node on Service pages) you can use Views module (this is different from view modes mentioned above).

You use Views to create a Block Display, filter out the node you need, and show only the MRP Field. The place that Block in a region in your theme (maybe Content region) and configure it so it shows only on Service CT nodes.

Create a new View of showing Content of type All, Create a Block of fields, showing 0 item (this means unlimited, for performance reasons)
Add a new Filter Content: Nid, keep the Operator Is equal to and enter your Purchase node ID number in the Value field (you can see the NID number on that node Edit page in the link)

If you have Views preview enabled you can now see that exact Purchase node title in the Preview results
Rearrange the Filters so that Content: Nid Filter is above the Content: Published (Yes) Filter (this is for performance reasons)
Remove the Content: Title from Fields
Add a new Field Content: MRP (or whatever that field is called in your case), configure how you want that Field to appear on Service nodes
Save the View and place your Block in a region of your theme, but limit it to show only on Service CT

To test it visit one Service node and see if the Purchase MRP is showing there, and if you visit any other page then it shouldn't show.


Unable to update head_title string in template_preprocess_html

If you find that $head_title is different from implode(' | ', $head_title_array), it means there is a module running after yours that implements hook_preprocess_html() which runs after your implementation, or hook_process_html().

The code executed from Drupal is the following:

template_preprocess_html() (It runs before hook_preprocess_html().)

// Construct page title.
if (drupal_get_title()) {
  $head_title = array(
    'title' => strip_tags(drupal_get_title()),
    'name' => check_plain(variable_get('site_name', 'Drupal')),
  );
}
else {
  $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
  if (variable_get('site_slogan', '')) {
    $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
}
$variables['head_title_array'] = $head_title;
$variables['head_title'] = implode(' | ', $head_title);

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'html')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

template_process_html() (It runs after hook_preprocess_html(), but before hook_process_html().)

There is no code that alters $variables['head_title_array'], or $variables['head_title'].

The fact $head_title_array contains the value you expect makes me think there is really a module that implements hook_preprocess_html to alter $variables['head_title'].

To be sure your module is the last one running hook_preprocess_html(), you need to make your module weight higher.


How to change the hyper link to checkbox link?

You can save checkbox image from here.

a.compare-toggle {
    background-image: url("/path_to_image/checkboxes.png");
    background-repeat: no-repeat;
    color: #000000;
    height: 16px;
    padding-left: 20px;
    text-decoration: none;
}
a.compare-toggle.add {
    background-position: 0 0;
}
a.compare-toggle.remove {
    background-position: 0 -16px;
}

Let me know if you face any further query/concern regarding this.


What is the simplest, most drupalish, way to restrict access to some content to authenticated users or a certain role?

Content Access

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Video Tutorial
Field Permissions

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Your views approach is fine, assuming everything you need is in the view.
But if you want to restrict access to nodes, then you're better off using Content Access.
For example: If your view was listing links that you don't anonymous to access (eg: premium content) you would want to use the Content Access module because if anonymous users somehow get a hold of the direct link then they could see the premium nodes.