How can I create a view of child nodes based on the menu relationship?

You can do exactly this using the Menu Node API
and the Menu Node Views modules.

Create a view with your required content type, and choose a contextual filter of "Menu: Menu link ID" (this is only available with the above modules installed).

Under, "When the filter value is not available," select "Provide default value" and choose "PHP code."

The following snippet will do it, then you just expose a block from the view and you are there:

if (function_exists('menu_node_get_links')){
   $node = node_load(intval(arg(1)));
   if (isset($node->menu_node_links)){
      foreach($node->menu_node_links as $mlid=>$data){
         return $mlid;
      }
   }
}


Run module after 'Order status gets updated' Action runs

I believe you're looking for hook_uc_order() which runs for several operations, including the update operation which is:

  Called when an order's status is changed.

Assuming your module is called "hemo" you code might look something like this:

function hemo_uc_order($op, $order, $arg2) {
  if ($op == 'update') {
    if ($order->order_status == 'payment_received') {
      // Do something with the $order object.
    }
  }
}

Remember to clear Drupal's cache once you've implemented the new hook or it might not get registered.


render($content) puts comment form above markup - why?

There is a show weights link in Drupal 7.14. If you go to Comment Fields in your content type /admin/structure/types/manage/.

I set the weight, and comments still show above the body.


How to create custom date display format that displays event duration

Do the following:

Administration » Configuration » Regional and language » Date and Time
There you will see a tab for format.
Create a new format string "Y-M-d".
Make this as your default for all date fields and you won't see the seconds any more.
You don't need the date module for basic formatting.

UPDATE: From following comment,

If you want optional End time, use Timefield module

  Timefield is a Field API field for storing simple non-timezone time
  values, with an optional end time, utilizing a simple JQuery
  timepicker widget for input.


Remove "Comments" title section from node template

You can hide it via css or you can change the tpl file:

Look for the comment-wrapper.tpl.php file in your theme. If it doe not exist there, you can copy it from the modules/comment folder into your theme folder. Edit the file and remove the line:

<?php print t('Comments'); ?>


Why is it not recommended to change the default language?

In Drupal 7 it was total chaos. With Drupal 8 things have improved a lot. It's now possible to switch default language but but there may still be effects:

URL alias has a language. Changing default language can bring some strange behavior, especially if some alias was created manually: https://www.drupal.org/node/2484411
Configuration entities can end up not having the right language. You will perhaps need to export the configuration and do some manual work like making sure the exported configuration has the right lang code.
...


Media: Specify display used for File field on content type's Manage Display tab


Change module settings stored in an array with drush

Drush does not have any mechanism to convert commandline arguments into php arrays for the variable-set command; however, it is easy to write short php snippets using the php-eval command ('ev' for short).

For example, if you have set up a site alias for your site called "@site":

$ drush @site ev 'variable_set("addtoany_nodetypes", array("about_us" => "about_us", "contact" => "contact", "page" => "page", "legal" => 0, "webform" => 0));'
$ drush @site vget addtoany_nodetypes
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => page
    [legal] => 0
    [webform] => 0
)
$ drush @site ev '$v = variable_get("addtoany_nodetypes", array()); $v["page"] = 0; $v["legal"] = "legal"; variable_set("addtoany_nodetypes", $v);'
$ drush @site vget addtoany_nodetypes
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => 0
    [legal] => legal
    [webform] => 0
)

If you are not using a site alias, then cd to the Drupal root of your site (or cd to the sites folder that contains settings.php if using a multisite) and remove the "@site" from the examples above.


How to associate multiple profiles per user with Profile2

I was able to achieve the solution with this module, and by setting the right permissions offered by this module.


Is there some module which detects untranslated strings?

To my knowledge, the answer to your question is = No there is no such module. Checkout the article Drupal's multilingual problem - why t() is the wrong answer to beter understand the various challenges to be addressed with anything related to the t() function ...

Drupal's translation system consists of 2 basic components: the translation of the interface and the translation of the content of a site.

The translation of the interface is about the translation of various text strings used throughout the site, like labels used on buttons such as submit, or on tabs such as view or edit. They are the same on all sites (no matter what actual content is contained in a site). This is also what the t() function is related to.

The translation of the content is about the translation of nodes and entities. It requires a place to actually store the translated versions of the content (in multiple languages) and a system to choose which content is to be displayed where. The systems available for translation of content are:

Content translation (used in earlier versions of Drupal, and still available in D7), which translates entire nodes in multiple languages.
Entity translation (its API was first introduced in Drupal version 7, though there is no UI for it yet), which translates fields attached to the same entity.

Typical (often used) modules (in D7) related to translation of the interface (apart from the i18n module of course):

Variable.
Localization update.
Entity Translation.

For D7 there are basically 2 alternatives available to facilitate the "management" of translation of content:

Translation Overview, mentioned as a recommended add-on on the i18n project page also. From its project page:

  ... provides a table listing the site's nodes and showing what's been translated into each language. It also lets you assign priorities for translating nodes into the various languages.

Translation Management Tool, considered as the successor of the previous module, and "the" module to move forward with in D8 also. From its project page:

  ... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.

  This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

PS: Obviously, translation of content is NOT what this question is about (at least not yet ...), but pretty sure a related challenge you 'will be' (or 'are already'?) facing in this multi-lingual site ... and which cannot be handled with the t() function. Though for the sake of completeness, I hope it's OK to add that part of my answer also ....


Display a field from a content type which is not displayed in the current node

I think you're looking for the node_load function.
Example:

function mytheme_preprocess_node(&$vars) {
  // Load node with ID 123.
  $another_node = $node_load(123);
  // Format a date.
  $vars['another_node_created'] = format_date($another_node->created, 'custom', 'Y, m, d' );
}

Beware that node_load returns raw data from the database. While $another_node->created is a safe value to use, user entered data (eg. the title or body text) needs to be checked before you print it (eg. <?php print check_plain($another_node->title); ?>). Not checking raw data is a security risk for your site. See Handle text in a secure fashion for more info.


This is working.

use Drupal\editor\Entity\Editor;

function MYMODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['disallowedContent'] =
'h1 h2 h3';
  }
}

This supersedes any allowed tags in the drupal GUI. But you must enable Allowed HTML tags enabled for this to work. I took the idea from this.drupal-8-ckeditor-behaves-ltr


Does disabling a module erase its settings?

"Disabling" a module means to disable its user interface aspects only.

This means:

All code of disabled modules remains to be loaded.
Services of disabled modules remain to be functional.
Routes, plugins, info hooks, etc. remain to be available.
Access to all data items that support any notion of access is denied for all users.

hook_enable(), hook_disable(), hook_modules_enabled(), hook_modules_disabled() are removed, without replacement.


How to delete a database field named as a reserved word?

Read is a reserved word, but your problem has an easy solution (I test it and works)

Change your field name to reading

And then use:

db_drop_field('your_table', 'reading');


I use it without a function as the argument like: jsfiddle

//id for nay_date input field
$('#edit-nay-date-datepicker-popup-0').datepicker({
          onSelect: function(selectedDate) {
          alert(selectedDate);
        }
    });


file field on form in view is ajax-enabled ONLY if rendered as part of page, not retrieved through ajax

Turns out it was a bug in the popup module.


Don't show Header view after clicking next on pager

I have an idea:

Create a third view that's a page showing articles with an offset of 16 (so it skips the 4 and the 12).  Call it 'older articles'.

Then instead of a pager, have a 'more' link under your view of 12.  It's important, in the 'Advanced' section of the view, to set the more link to go to that new views page (older articles).  The older articles page can then have its own pager!!!  But the initial articles page -- the landing page -- can just have a 'view more' link so it can hop over to the older views altogether.

Would that be sufficient?


Get a list of all the modules in code base

Use the following command in the terminal at the root of your site.

grep -hr '^name =.*' . | sort

This is the non drush way and also helps me identify the duplicate code for a single module if any.


here is API https://www.drupal.org/node/336122

The two events

The flagGlobalAfterLinkUpdate event

This event is triggered immediately after a flag link has been updated. (Flag links appear in two flavors: "Bookmark this!" and "Unbookmark this!", and when we speak of "update" we mean this change in appearance).

The flagGlobalBeforeLinkUpdate event

This event is triggered just before a flag link is updated. As will be explained later, the existence of this event is for cosmetic reasons only: it allows us to carry out actions while the throbber () is still visible.

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  alert('Object #' + data.contentId + ' (of type ' +
    data.contentType + ') has been ' + data.flagStatus +
    ' using flag "' + data.flagName + '"');
});


Panels cache terminology- what's the difference between caching by argument vs. by context?

Disclaimer: I usually find that the setup is simple enough that the distinction isn't necessary, thus I must admit my practical experience is limited, and I could be wrong below.

Arguments, are based on the URL. node/5 gets cached separately from node/7, because 5 is different from 7. node/5/7, if you where to have such a path, is yet another cache.

Contexts, are generally derived from Arguments, and in the examples above, it's very likely that the caches would be exactly the same, regardless of which cache option one would pick. However, Contexts, can also come from (at least) three other sources, Relationships, manually defined ones, and the special case, the logged in user.

If your context is both a node from the URL, and a user pulled from an entity reference on the node, then your context has two unique entities, or two contexts, but only one argument.

So one chooses Context or Argument depending on whether you want the cache to take any "extra" contexts into question, or not.

  But in Views, the option is called argument input and the value I chose was from context. So am I dealing with an argument or a context?

Unfortunately the terminology isn't exactly the same between the two modules. Panels calls dynamic pieces of the URL arguments, and it creates contexts from those. Views, means something closer to a function argument, when it refers to arguments, and in this particular case, it will derive the argument from a context, passed in by Panels.


This page Drupal 7 Template (Theme Hook) Suggestions explains the topic.

To investigate for yourself:

Install Devel module. Add this bit of code to your theme's template.php file (check if the function does not already exist):

function MYTHEME_preprocess_node(&$variables) {
  dpm($variables);
}

Then inspect the theme_hook_suggestions key. It will look something like this:

This show the suggestions available. To convert it to a tpl.php file just convert underscores to hyphens and add the extension tpl.php.

You can also create your own suggestions by adding this code into preprocess_node:

if ($variables['type'] == 'article' && $variables['view_mode'] == 'teaser') {
  $variables['theme_hook_suggestions'][] = 'node__article__teaser";
}

Here I am checking for the view mode teaser and adding a theme suggestions based on that. You can check for other conditions as well and add your own suggestions as you please.

Some themes add their own suggestions so always inspect it with dpm() first.


Template Suggestions Causing Undefined Variable

hook_preprocess_page() is run for any page, even non-node pages. If you're getting that error it means your trying to access $node in the page.tpl.php file when you're on a non-node page. As no node is available on such a page, the variable won't have been set.

Because of the delay that can happen when messages are set in template files, you might only see this message when you've left a non-node page, and navigated to a node page. So it will look like it's that particular page complaining, when in fact it was the previous one.

You should be able to fix the problem by checking the $node variable is available in your template file as well as in the preprocess function. e.g.

<?php if (isset($node)) : print $node->something; <?php endif; ?>


Pass node field value to view filter in a block

The easiest way to use a view in a block (or anything that uses a build array) is as a render element:

$node = \Drupal::routeMatch()->getParameter('node');

$current_nid = $node->id();

$view_arguments = [$current_nid];

 $build['news'] = [
   '#type' => 'view',
   '#name' => 'myviewname',
   '#display_id' => 'block_1',
   '#arguments' => $view_arguments,
   '#weight' => 30,
 ];

return $build;

The first argument passed in will be used as your content ID.

If you want to do it all through the UI, you set your contextual filter to pull from the content id.

then if you place a block based on the view, it will pull in from the current node.


Access custom user field from a different account

This seems a bit dirty, but using your exact code as a base, something like the following may work:

$uids = array(
  // Here is the list of user ID's that you know.
);

$full_names = array();

foreach ($uids AS $uid){
  $account = user_load($uid);
  $full_names[$uid] = $account->field_full_name[LANGUAGE_NONE][0]['value'];
}

unset($account);

return $full_names;

This will give you an array of full usernames keyed by the UID.

Also to bear in mind, this performs no access checking or permission checking.

For further reading, you might want to try taking a look at something like field_get_items() as well.


How to use form API to edit sub form that is added to user_register_form

You probably forgot to reference the $form variable ("&$form").
The alternative to #after_build would be #pre_render, which misses $form_state but should generally be preferred for changes that only affect the rendering of a form.


Not sure if "faster" but I'd recommend the integration of Drupal Commerce and Phonegap (I'm guessing you're using DrupalGap already) if you're already using both: https://www.drupal.org/project/commerce_drupalgap

You've got plenty of resources there to get started such as the Commerce Services module.

It's up to you to decide where you need or not a full bootstrap of your backend, I'm thinking you need it to get advantage of user access, permissions and consistency check in your order status, but it depends a lot on your app and where  you're implementing the business logic. If you access the database directly, without any bootstrap is going to be faster, but the same way you build a drupal site, if you bypass Drupal to access directly to the database that'd be faster as well.


Create a view to display last browsed content

I am able to do so using the sort criteria timestamp by the Radioactivity module.

  This module provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.


Two tabs of Month came up in the first place don't make sense. It never happened to me. I would suggest to recreate this Calendar view, it's actually pretty easy if you "add view from template". (Consider you've installed the Calendar Module)

Make sure to select “A calendar view of the 'field_date' field in the 'node' base table.” on the list of views/add-template


Ajax Form Not Working in some Some Regions

I got the solution for this . Just want to tell  the answer for anyone who might come across this problem. The problem was :

I was printing it in html.tpl.php.

The solution is

print it on either page.tpl.php or page--xxxx.tpl.php and print it as

<?php
     print render($page['contact']);
 ?>


How do I change drupal_core_path to /public instead of /web?

You should be able to create a symbolic link to web called public.
ln -s web public
Your server will find the contents of web/ inside of public/ and vagrant will find what it needs in web.


iframe in - rewrite results - Override the output of this field with custom text

I have been wrestling with this as well but my users want to embed google docs.  Same concept though.

I figured out the solution and it's not super complicated.  You you just need to create a 'Field Template' in the theme.

This video covers the concept with 'Node Template' but you can easily apply it to the field template.

Drupal 8 Theming - Part 11 - Displaying Fields
https://www.youtube.com/watch?v=fQ6Ypik_jsE


Rendering a form using \Drupal::service('entity.form_builder')->getForm($entity, 'default') is returning a plain form, before hook_form_alter

Ensure that your implementation of hook_form_alter() runs at the right time via hook_module_implements_alter().

  This hook is invoked during
  \Drupal::moduleHandler()->getImplementations(). A module may implement
  this hook in order to reorder the implementing modules, which are
  otherwise ordered by the module's system weight.

But pay attention when using possible variations of hook_form_alter().

  Note that hooks invoked using \Drupal::moduleHandler->alter() can have
  multiple variations(such as hook_form_alter() and
  hook_form_FORM_ID_alter()). \Drupal::moduleHandler->alter() will call
  all such variants defined by a single module in turn. For the purposes
  of hook_module_implements_alter(), these variants are treated as a
  single hook. Thus, to ensure that your implementation of
  hook_form_FORM_ID_alter() is called at the right time, you will have
  to change the order of hook_form_alter() implementation in
  hook_module_implements_alter().

See? Right now you are checking for if ($hook == 'form_FORM_ID_alter') which won't work. Fix it by replacing it with if ($hook == 'form_alter').

If that doesn't work try to change your module's weight via module_set_weight().


Unable to set field collection field value on form validation

Use Computed field instead of doing it yourself! Don't use _validate, just use _compute.

Change field_total_cost to a computed field, saving as decimal.
Create a custom module and add the following (much clearer than using Computed Fields settings inputs - yuk)

Do something like the following :

/**
 * Computed field for - field_total_cost
 */
function computed_field_field_total_cost_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $tot   = 0;
  $books = 0;
  $rate  = 0;
  if (isset($entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'])) {
    $books = $entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'];
  }
  if (isset($entity->field_rate[LANGUAGE_NONE][0]['value'])) {
    $rate = $entity->field_rate[LANGUAGE_NONE][0]['value'];
  }
  $tot = $books * $rate;
  $entity_field[0]['value'] = number_format((float) $tot, 2, '.', '');
}

/**
 * Display for - field_total_cost
 */
function computed_field_field_total_cost_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
  return '£' . number_format($entity_field_item['value'], 2);
}

I obviously don't know what your calculations are like but you get the idea.
This will calculate and populate the Total Cost field per field collection.

OR

If you still want to do it on validate you (afaict) can't do it on node_validate but you can on a field validate. So you need to add a custom validate function to your Field Collection field, then it should work as you think.

Add a custom validate callback on hook_field_widget_form_alter

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add custom validation hooks for Field Collections.
  if ($context['field']['field_name'] == 'field_assignments') {
    array_unshift($element['#element_validate'], 'MYMODULE_field_assignments_validate');
  }
}

Create the custom validate function and set the value similar to how you suggested

/**
 * Custom validate function for field_assignments.
 *
 *  @see MYMODULE_field_widget_form_alter()
 */
function MYMODULE_field_assignments_validate($element, &$form_state, $form) {
  form_set_value($form["field_assignments"][LANGUAGE_NONE][0]['field_total_cost'], array(LANGUAGE_NONE => array(0 => array('value' => 123.456))), $form_state);
}

I obliviously left out any logic in this example, but you get the idea :)


How to display message (NDA, warning, etc.) before content can be viewed?

You've listed a nebulous group of requirements that somewhat overlap with existing module projects out there. FWIW, there's also the Premium Content module which also has elements of what you're asking for.

My guess is you're not going find one that 100% matches your current and ongoing needs. So you either find one that matches the most & work on patches to that project, or you build your own. Depending on how specific your needs are one might work better than another.

If you go the "build my own" path, look at hook_node_access() & hook_node_view() (D8: hook_entity_view()) which respectively allow you step in front of node permission checks and rendering. They will be the core of your strategy to determine when to allow full access & when to send your user through a NDA confirmation workflow.


Views alter changes next row instead of current one

Got it to work with the following code. I needed to output the changed value in the $vars['output']. This would override the url in the nothing_1 field so I then had to create a new link and use that to alter the original value.

/**
 * Implements hook_preprocess_views_view_field().
 */
function frontview_general_preprocess_views_view_field(&$vars) {

  $view = $vars['view'];

  if(isset($vars['view']) && ($vars['view']->id() == 'evenementen') && ($vars['view']->current_display == 'accreditaties_overzicht')) {

    if($vars['field']->options['id'] ==='nothing_1') {
      $accreditaties = $vars['row']->_entity->get('field_accreditaties');
      $accreditaties = $accreditaties->getValue('list');
      $amount = count($accreditaties);

      // $vars['field']->options['alter']['text'] = 'View Applicants ('. $amount .')';

      $nid_value = $vars['row']->nid;
      $url = Link::fromTextAndUrl(t('View Applicants ('. $amount .')'), Url::fromRoute('view.evenementen.page_2', ['arg_0' => $nid_value]))->toString();

      $vars['output'] = $url;
    }
  }
}


Why is my javascript not being executed?

You don't attach your to your form:

$form['#attached']['library'][] = 'module_name/library_name';

Just a suggestion:

In your library yml it's unnecessary to append your module name to your library name.


You might want to try the Views Slideshow Xtra module

  Views Slideshow Xtra is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in  overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.


How to Include custom tokens in the user register welcome mail

The user mail templates can be found at example.com/admin/config/people/accounts. The welcome mail for instance looks like this:

  [user:display-name],

  A site administrator at [site:name] has created an account for you.
  You may now log in by clicking this link or copying and pasting it
  into your browser:

  [user:one-time-login-url]

  This link can only be used once to log in and will lead you to a page
  where you can set your password.

  After setting your password, you will be able to log in at
  [site:login-url] in the future using:

  username: [user:name] password: Your password

  --  [site:name] team

As you can see there are already many tokens used.

Furthermore, Drupal does not distinguish between core tokens and those of modules. So if a textfield allows you to use core tokens (like this one), you can also use any other token. If you create a custom token, you will be able to use it in the mail. BUT, you must keep in mind that this mail template only has access to a select set of tokens (click the Browse tokens link below the textarea):

Current date    current-date    Tokens related to the current date and time.
Current page    current-page    Tokens related to the current page request.
Current user    current-user    Tokens related to the currently logged in user.
Random  random  Tokens related to random data.
Site information    site    Tokens for site-wide settings and other global information.
Users   user    Tokens related to individual user accounts.

When working with tokens, each module can define which tokens it handles (The $data array passed to Token::replace()). In this specific case, it only gets the user entity of the created user. Apart from that, several global tokens are always available, these are Current date, Current page, Current user, Random and Site.

So your custom token must be provided within the user or site type.


Running tests on fresh 8.2.x install throws "Permission Denied" for Kernel tests

Looks like some tests can only be ran with the command line and will not work with the test runner UI.


You don't need to actually override the login process to do this; The user module provides a hook (hook_user_insert()) which gets invoked any time a new user is created.

As far as inserting into the database goes, the best place to look first is the Database abstraction layer documentation which goes into detail about the various database methods available.

In this specific case it's the db_insert() function you're looking for. Your code might look something like this:

function MYMODULE_user_insert(&$edit, $account, $category) {
  db_insert('custom_table_name')
    ->fields(array(
      'id' => $account->uid,
      'text' => 'some text'
    ))
    ->execute();
}

This code would go inside a custom module; if you're not familiar with creating one of those check out the Module developer's guide which will tell you everything you need to know.


Why the path alias is like http://domain/http://domain/path?

I ended up using a different token which fixed the issue. I believe using token URL in the URL field is the cause of the double URLs.


Problem while using the user_reference field in my bundle

You are missing the module definition, though I'm not sure it's required.

The easiest thing to do it so use field_info_field and field_info_instance for the field to see what info Drupal provides and fill in the blanks until every works.


Prevent a user from viewing another user's profile based on a field value

You can control profile2 access with

hook_profile2_access

Views listens to node access so you might be able to use to exclude rows from the view.

/**
 * Implements hook_profile2_access
 */
function MY_MODULE_profile2_access($op, $profile = NULL, $account = NULL) {
  if (isset($profile)) {
    // Use wrapper for field access
    $profile_wrapper = entity_metadata_wrapper('profile2', $profile);
    // Check if $account uid is set in field_invalid_users
    if(isset($profile_wrapper->field_invalid_users)){
      if(in_array($account->uid, $profile_wrapper->field_invalid_users->raw())){
        // Deny access
        return FALSE;
      }
    }
    // Example: Explicitly deny access for a 'secret' profile type.
    if ($profile->type == 'secret' && !user_access('custom permission')) {
      return FALSE;
    }
    // In other cases do not alter access.
  }
}

One consideration is caching. Cache will need to vary enough to not serve the same cached content to valid and invalid users. Perhaps those pages aren't cached at all, it depends on your application.


Redirect according to views filter input

You can do it using hook_form_alter() on the exposed filter form.
It is very well explained in this post.
A drupal_goto() depending on the input entered should work.


What should I do to use a more recent jQuery version?

Looks like there is a patch for the jQuery Update module to update it to jQuery 1.7.


Is Menu-minipanels reliable to make a mega menu

Menu Minipanels looks like a good choice.

An alternative you might want to try for a simple 'mega menu' is the Mega Menus module. Worked well for me, once I had my settings and CSS sorted out. See also this answer for lots more mega menu options...

Finally, regarding performance, since Menu Minipanels uses Panels you will have full control over caching of individual panes within it. The performance burden can therefore be significantly reduced.


You can use like:

$other_database = array(
  'database' => 'drupal8',
  'username' => 'root', // assuming this is necessary
  'password' => '123123', // assuming this is necessary
  'host' => '192.168.1.243', // assumes localhost
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql', // replace with your database driver
);
// replace 'YourDatabaseKey' with something that's unique to your module
Database::addConnectionInfo('d8243', 'default', $other_database);
db_set_active('d8243');
// execute queries here
db_set_active()

You can access your other database like above. For reference check this link.


How to add country suffix to the hreflang tags?

This cannot be achieved in the Alternate Hreflang module or any other Drupal module. They all use the language code as the hreflang code which is incorrect as hreflang contains 2 parts - the language "es" and the country "ES" (Spanish, Spain) or in your example es-MX (Spanish, Mexico).

I've had three or four contributors (metatag, Alternate Hreflang) come back to me and state that you need to create custom languages for this to actually work. So for Mexico create a new language and use the code es-MX then this will show the appropriate hreflang code es-MX. However it will
a) create an unnecessary language
b) probably require Language Hierarchy to avoid superflouous translations
c) also show in the URL as es-MX which in my opinion is also not ideal (the MX is in UPPERCASE and the URL will always be flattened to lowercase on output not ideal for SEO or asthetics...)

Off the shelf them's your options me thinks.

I would suggest coding some simple patch to the Alternate Hreflang module to include the ISO list of country codes so through a UI you could add whatever country you liked alongside the any enabled language into the hreflang code.


User can't change language after redirection from custom module

Now your code redirect always, and you only want to redirect once. It means you need implement logic similar to the one below:

Test $_SESSION to see if redirection evaluation took place already. If yes, end.
Create element in $_SESSION, to mark this session as already evaluated against redirection
Decide if you want to redirect or not.
Perform redirect if needed.

That way you will run code responsible for redirection once and only once per user session, and that's seems what you want to do.


How can I add a class to link around image field

From the way lightbox does it (line 145), i would think there is not much you can do to alter the link, since it is "hardwired" there.
What you could do (and is surprisingly easy :) is to implement your own handler that would extend the lightbox one and allow you to specify the css class (or submit a patch that would do it in their code).

You might as well specify the class on the parent div (in views "Styles settings" for the field, "Customize field HTML" and "Create a CSS class". And then just sligthly change your selector.


How can I download a results set with a form built in Entity forms?

You can use Views Data Export: For downloading submissions, Entityform support that by default.


Validating form data that it is a weekday

date('w'[, $timestamp]);

gives you the days of the week as an integer from 0 (Sun) to 6 (Sat).

So you could check to see whether the chosen delivery date is 1 - 5.
I am not aware of any existing Drupal function to do this, but it's a fairly simple function to write oneself.


Do you also have wysiwyg module installed. You can go to admin-config- ckeditor there you can choose for different editor types like full-html which buttons are availible. To upload images i like to use the kcfinder module.


Creating an editable table which can be updated

For your requirement Slickgrid is the best option for you and for that you need to use views module.

At the front end, users can show/hide, resize, reorder columns &
resize the height of the grid. These settings will be stored per user
and used next time the grid is shown. Saving the view (via the usual
views UI) will reset these settings.

For every field defined in the view, you can set its column width, whether it's sortable, and formatters (how the cell data is displayed), an editor, a validator and filters (for filtering the column data).
This modules comes with the following plugins ready to use:

Editors:

Inline cell editor - for excel-like editing of text & numeric data.
Popup field form - the field form pops up in an overlay. All field types can be edited.

Features of the grid:

Grouping field - group fields with a common value together
Collapsible taxonomy fields (tree structures)
Tabs - organise columns into tabs
Resize, reorder & hide columns
Delete entities via the grid
Force fit columns (to fill the available column space)
Undo (undo previous changes - uses node revisions)
Set viewport height
Set row height
Add entities via the grid*
Clone entities*
Export data (via the views data export module)*
Multi edit/delete/clone/export (checkboxes will be displayed in the rows - select as many rows as you want to perform action against)***

or as  Pontus Nilsson said use this Editable Views module.


Is it safe to update a field value direclty on the Database

It is not recommended, there is a way of doing this using field_attach_update which should give you the performance benefit of not saving the whole node while using drupal api. Example:

$node = new stdClass();
$node->id = $id_value;          // node id
$node->type = $bundle_value;  // aka content type

$node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
field_attach_update('node', $node);

Sources:

updating field value of a content type with query

https://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself

https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_update/7


Simple category with drupal commerce not showing to anonymous users

Here are some tips:

Set all checkboxes in People -> Premissions : Product-> View any product of any type
or If you are using any contextual filter in views configuration be sure that arguement exists in category page;


Show a menu item as expanded if on a certain node type

I would go with the context module.

You can set a context to be active whenever a certain content type is shown, in this case, an 'Article'.

You can then set the reaction to 'menu' and choose an item which will get an active trail. You can then target using CSS or more likely, it's probably already expanded.

https://drupal.org/project/context


Is there a way to skip bootstrapping drupal to save load time via drush?

That is hard-coded for each command: The module defining a Drush command sets the bootstrap level required to run the command. For example, cache_drush_command() defines cache-clear as the following:

  $items['cache-clear'] = array(
    'bootstrap' => DRUSH_BOOTSTRAP_MAX,
    'description' => 'Clear a specific cache, or all drupal caches.',
    'arguments' => array(
      'type' => 'The particular cache to clear. Omit this argument to choose from available caches.',
    ),
    'callback' => 'drush_cache_command_clear',
    'aliases' => array('cc'),
  );

To require not bootstrap at all, the "bootstrap" property should be defined as follows.

  $items['xkcd-fetch'] = array(
    'description' => "Retrieve and display xkcd cartoons.",
    'arguments' => array(
      'search' => 'Optional argument to retrive the cartoons matching an index number, keyword search or "random". If omitted the latest cartoon will be retrieved.',
    ),
    'options' => array(
      'image-viewer' => 'Command to use to view images (e.g. xv, firefox). Defaults to "display" (from ImageMagick).',
      'google-custom-search-api-key' => 'Google Custom Search API Key, available from https://code.google.com/apis/console/. Default key limited to 100 queries/day globally.',
    ),
    'examples' => array(
      'drush xkcd' => 'Retrieve and display the latest cartoon.',
      'drush xkcd sandwich' => 'Retrieve and display cartoons about sandwiches.',
      'drush xkcd 123 --image-viewer=eog' => 'Retrieve and display cartoon #123 in eog.',
      'drush xkcd random --image-viewer=firefox' => 'Retrieve and display a random cartoon in Firefox.',
    ),
    'aliases' => array('xkcd'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH, // No bootstrap at all.
  );

Using DRUSH_BOOTSTRAP_DRUSH says to Drush that Drupal doesn't need to be bootstrapped at all.

Clearly, that is not something that can be arbitrarily changed; it depends from the code executed from the command.


In the contextual filters click on override title and set it to %1
Specify validation criteria to taxonomy term and select the vocabulary
Leave the views title empty.

This will set the present's term's title as the view's title.

If need you can add "text" %1 to display the text appended to the term's name.


Making an ecommerce photography competition website

I would look at Node Limit. So the user buys roles and that gives them access to create more content.

Then create a content type for Entry with all the appropriate tag fields.

I like the purchasing the role structure. I wouldn't do this directly on the user


How to include XML file in node for js map rendering?

It looks like, according to the demo page you showed, the URL is relative to the path where the JavaScript is loaded; adding a slash in front of URL passed to $.ajax() should work.

$.ajax({type: 'GET', url: '/sites/default/files/repfinder/xml/usaMapSettings.xml'


Can I conditionally hide a route (e.g. action / local task)

You can add a custom access method on your controller. According to this page you should have access to your item argument in the access method so you should be able to restrict access based on a value on that item. The action should be hidden if the user does not have access to the route, i.e. your custom access method denies access.


I think you could use an alias in your apache virtual host, something like this

Alias /site1 /path/to/your/site1
<Directory /path/to/your/site1>
  Options +Indexes
  AllowOverride All
</Directory>

Like it is suggested here https://stackoverflow.com/questions/19055372/redirect-to-a-subfolder-in-apache-virtual-host-file#19055573


Drupal.attachBehaviors only working for some fields when using Ajax .load

$.load() will not update the Drupal.settings object, which contains the references to which fields need to be ajaxified. This is why you are seeing the issue you have. In order to load a form through AJAX, you need to return the form as well as the settings for the form alonng with the form, after the form has been rendered. This will update the Drupal.settings object, which then will ajaxify your form.

First you need to declare a callback path in hook_menu()

function hook_menu()
{
  $menu['my/ajax/callback'] = array
  (
    'title' => 'AJAX callback',
    'page callback' => 'my_ajax_callback',
    'access callback' => TRUE,
  );

  return $menu;
}

Then you need to generate your form, and ajax settings, in the callback path

function my_ajax_callback()
{
  $form = drupal_get_form('some_form');
  $rendered_form = render($form);
  $javascript = drupal_add_js(NULL, NULL);
  $settings = FALSE;
  if(isset($javascript['settings']))
  {
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ' .
      drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data'])) .
    ');</script>';
  }

  $response['form'] = $rendered_form . $settings;
  drupal_json_output($response);
}

Finally, you need to make an ajax call to get your form, and append it to the page somewhere, finally calling Drupal.attachBehaviors()

$.ajax(
{
  url:'/my/ajax/callback',
  success:function(data)
  {
    // Create a div and set the returned data as the contents,
    // so as to turn them into HTML
    var formElement = $("<div/>").html(data.form).contents();

    // Append the form somewhere on the page
    $("#some_container").append(formElement);

    // Finally call Drupal.attachBehaviors
    Drupal.attachBehaviors(formElement);
  }
});

For more of an understanding on what I'm doing with Drupal behaviors, read my tutorial on working with JavaScript in Drupal 7, in particular the section on attaching behaviors: http://www.jaypan.com/tutorial/high-performance-javascript-using-drupal-7s-javascript-api


The best solution is to always review the tests. The tests create promotions and coupons programmatically.

Here's how to create a promotion.

$promotion = Promotion::create([
  'name' => 'Promotion test',
  'order_types' => ['default'],
  'stores' => [$this->store->id()],
  'offer' => [
    'target_plugin_id' => 'order_percentage_off',
    'target_plugin_configuration' => [
      'amount' => '0.10',
    ],
  ],
  'start_date' => '2017-01-01',
  'status' => TRUE,
]);
$promotion->save();

And then coupons.

$coupon = Coupon::create([
  'promotion_id' => $promotion->id(),
  'code' => 'coupon_code',
  'usage_limit' => 1,
  'status' => TRUE,
]);
$coupon->save();


AJAX HTTP error 200 when using Views Bulk Operations on Files

200 means that a response was returned successfully, but the response is not something your code can work with, which is why you are getting the error. It looks like the response is returning a script, rather than whatever is expected (likely JSON).


The easiest to resolve (and most likely) issue is:

You are limiting the allowed HTML tags for the text format you're using and you haven't allowed the align (and also caption, if you want captions) attributes for the drupal-entity HTML element. (I'm assuming you do have the Align images and Caption images filters enabled because you said those features were working for non-media embeds. If they're not enabled, enable them.)

Solution:

In the "Limit allowed HTML tags and correct faulty HTML" section (/admin/config/content/formats/manage/MY_FORMAT#edit-filters-filter-html-settings), make sure the drupal-entity has at least the data-align (and data-caption for captions) attributes. E.g. <drupal-entity data-align data-caption data-etc...>.


Why does the title callback of /user produce the title for /user/register?

For the user/register title to be changed in a theme:

function mytheme_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is 'register'
  $arg = arg();
  if ($arg[0] == 'user' && $arg[1] == 'register') {
    $variables['title'] = 'Test';
  }
}

For the user/register title to be changed in a module:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
  drupal_set_title(t('Test'));
  }
}

Hope that helps.


How do I fetch the product display nodes referencing the given product using "Fetch entity by property"?

Have a look at Action "Fetch entity by property" does not allow to fetch by multi-valued properties, which appears to be similar to what your question is about (and has RTBC status).

If I'm right, try the patch attached to it.


What methods are available to assign a TPL to a specific url for Drupal 7 theming?

Unset the JS or CSS assets on page build with either hook page build or hook page process and drupal add js.

Alternatively you can use hook theme to define custom tpl files on custom business logic (such as url paths).

Im on my phone, unable to gives more info or examples until at pc.


LDAP SSO - User not redirecting to user/login/sso to login the visitor

You can use a rule to redirect them to the /user/login/sso. You can make a rule, if user has not logged in auto send them to /user/login/sso. If the user is already logged in send them to the home page.


Is it possible to set up preferrential IPs when in maintainance mode?

Actually on Drupal you can create a new role and assign permission to this role to login in maintenance mode (Add permission "System > Use the site in maintenance mode").

If this is not what you want, then you can filter IP addresses on firewall /linux level. Please ask on https://serverfault.com/ if you need this kind of solution.


Editing the /cart page in Views

I think this is the expected approach. Note: this assumes you know your way around Views.

Install Commerce Cart View Override, as you've done.
Edit the view named Shopping Cart Form, clone it, change the machine name  to something starting with commerce_cart_form like commerce_cart_form_custom
Select this in the dropdown on the admin page admin/commerce/config/cart-overrides (Administer >> Store >> Configuration >> Cart Overrides), then save.
You can now edit the view that appears on the /cart page by editing this new view. A few non-intuitive tips:

To see a preview in the Views preview, you'll need to enter a shopping cart ID number into the "Preview with contextual filters" box above the preview. You can see some shopping cart ID numbers at /admin/commerce/orders/carts. You just enter the ID number, no other text needed.
To add any views fields from the products, for example product images, you'll need to add a new relationship from Line Items to Products. Under Advanced in the Views UI, under Relationships, click Add, then choose Commerce Line item: Referenced products. Product fields like images and taxonomy tags will then become available under Fields.
A common Commerce Cart configuration confusion: If no "Checkout" button appears for customers who aren't logged in, you need to go to admin/people/permissions and tick the "Anonymous user" box next to "Access checkout"
If you want to change the labels of buttons, for example the "Remove" buttons... that's a whole different story. Form elements are generated in a whole different part of the Drupal ecosystem and put into a View like this pre-rendered, all you can edit in Views is the labels that appear alongside or above the button. To edit the buttons themselves has to be PHP code:

Editing form elements like buttons

In a custom module or your theme's template.php file (remember that if you use a seperate admin theme, your template.php won't have any effect in the views preview, only the customer-facing pages), add something like this (credit):

function yourthemename_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id)  {
  case 'views_form_commerce_cart_form_custom_default':
  //               ^ from here on should match the view machine name from earlier
  //                                         ^ from here, the particular view display, which you can see at the end of the Views UI URL while editting that display
      foreach ($form['edit_delete'] as $row_id => $row) {
        if(isset($form['edit_delete'][$row_id]['#value'])){
            $form['edit_delete'][$row_id]['#value'] = 'New delete button label';
            }
        }

    $form['actions']['checkout']['#value'] = 'New checkout button label';
    $form['actions']['submit']['#value'] = 'New update button label';

  break;
  }
}


I think there is not really a good option for this yet.

It's tricky, because you can't just override the config and have those modules enabled since they also provide their config (which would and install/uninstall processes that can't be skipped. In fact, providing config overrides for core.extension is explicitly prevented.

Maybe someone will come up with a good way to do this, I currently don't really know how that should work.


Make sure you enable panels node template at admin/structure/pages.


Why I can upload only one file at a time with multi upload widget?

Probably you are using APC for upload progress:

Check your status report to see. If so, do what it suggest. Or ask / pay your sysadmin to do it.


Delete all nodes of a user using flags and rules

I did in this way without writing a single line of code.

1) Add action: Fetch entity by property: Choose Entity type as 'Node', Property as 'Author' and Data selector as 'flagged-node:author'. Choose variable label ('spam nodes' in my case) and variable name ('spam_nodes' in my case) as you wish.

2) Add Loop: Select Data selector as 'spam-nodes' (this will show as per your  variable label in step 1). Set variable label('spam node' in my case) and variable name('spam_item' in my case) as you wish.

3) Now click on 'Add action' link under 'Operations' column against the loop you have added in step 2. Select 'Delete Entity' and set the Data selector as 'spam-item' (this will show as per your variable label in step 2).


How do I send a command after submitting a form?

The Drupal way to do this is to use hook_form_alter() to add a submit hook, and then add your command in the submit hook.  Here's a simple example.
You'll need to add this code to a custom module.
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id') {
      $form['actions']['submit']['#submit'][] = 'MYMODULE_my_form_submit';
  }
}

function MYMODULE_my_form_submit(array &$form, FormStateInterface &$form_state) {
  // Insert command here.
}


Render Teaser Image in search block using Twig

You could use the URL Formatter Module

Then go to Manage Display and for your image field and select URL Formatter as your formatter.

then use: <img src="{{ content.field_teaser_media[0] }}">


Repeat the alt text and title text for a series of image field values

You could just implement a custom template for your field and implement whatever logic you require there.

So, in admin, you could enter the alt and title just for the first image, and then with the template you could apply the alt and title to all the images.

Does that make sense to you ?


Add button to teaser on specific content type

I would check out Display Suite's custom fields capability.

It allows you to create custom code "fields" that can be attached to nodes and other entities, and can be included in views. These fields can be, for example HTML code with tokens to create links that redirect user to the full node.

These fields also have the capability of accepting php code, which would allow you to evaluate if the user is logged in and include logic to redirect to the appropriate place. Check out the tutorial for custom fields here: https://drupalize.me/videos/display-suite-fields?p=1141


How to add Callback function for delete operation?

The operations are a list of links. If you want to delete a different entity see this example from the core workflows module how to build a delete link:

WorkflowStateEditForm::Form()

  $links['delete'] = [
    'title' => t('Delete'),
    'url' => Url::fromRoute('entity.workflow.delete_transition_form', [
      'workflow' => $workflow->id(),
      'workflow_transition' => $transition->id()
    ]),
  ];


Fatal error when calling drupal_goto from hook_boot

In hook_boot() lot of APIs will not work as the required function definitions for them will not be loaded. In this case common.inc where drupal_goto() is defined is not yet included ergo you get that error. If its not possible to use hook_init() make use of Header. Check out mobile_tools module hook_boot() for more info.


Autocomplete field - fill the selected id into another form element (eg. hidden field)

I've found solution, so I'll share it with others:

Both options in the question were correct. I just expected that the new value of hidden field will be visible through "see source code" which it's not. When I check the $form_state['values']['geonameid'] it is filled correctly.

The complete solution:

1) In Drupal.jsAC.prototype.found I've filled the 'autocompleteValue' with value instead of key, and added new data 'autocompleteKey' which I've filled with key, surprisingly :)

2) In Drupal.jsAC.prototype.hidePopup just added $('input[id="search-geoname-id"]').val($(this.selected).data('autocompleteKey'));

Hope this helps to someone in future.

P.S. I know modifying core functions is not the cleanest way to do things, but it works.


How to get contextual filter in hook_views_query_alter or hook_views_pre_execute?

The contextual filters are in $view->args.

$view->args is an array of arguments (contextual filters).

So you can do things like this:

/**
 * Implements hook_views_pre_execute().
 */
function MODULENAME_views_pre_execute(&$view) {
  // Set the first contextual filter value.
  $view->args[0] = 1;
}


Did you check if the submit is called in your ajax request?

public function bulk_email_addfieldsubmit(array &$form, FormStateInterface $form_state) {
    $num_users = $form_state->get('num_users') + 1;
    $form_state->set('num_users', $num_users);

If not, you can put this code in buildForm(). In this case you need to check if the triggering element is the correct one.

And another small issue, this line in buildForm():

$num_users = $form_state->getValue('num_users');

Should be get('num_users'), because getValue() is for user input.


Button with different value and label / text

I think this might be a duplicate of a question I posted a few weeks ago for Drupal 8.

Original question: https://drupal.stackexchange.com/a/226494/57

Some more write up: http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements

Basically I wanted to target just one submit, hence that technique. Simply changing the #type to button is not enough in the Form API to get that result you're asking for.


I found the function I was looking for. You can insert nodes in the results array just after the query has been executed.

This goes in the module:

function modulename_views_post_execute(&$view) {
  // wait for the right view
  if($view->name == "name_of_the_view") {
    // create the object you want to insert in the result
    $temp = new stdClass;
    // creation date of that node
    $temp->node_created = 1314807643;
    // nodeID
    $temp->nid = 13;

    $new_result_array = array();
    $i = 0;
    foreach($view->result as $single_result) {
      if($i == 2) {
        // insert the extra node at 3rd position
        $new_result_array[] = $temp;
        $new_result_array[] = $single_result;
      } else {
        $new_result_array[] = $single_result;
      }
      $i++;
    }
    // replace the old result array
    $view->result = $new_result_array;
  }
}


Display price on Views for product variation

I think I found a solution, in "Fields" just instead
"(Variations: Product variation) Product variation relationship: Price"
need to use:
"Product datasource: Variations", and there are some settings to handle multiple values.
In "Formatter" need to set "Rendered entry", instead default "Label"


Unable to retrieve user id of edited user from $entity in hook_field_validate

You can always get this information from the path, eg:

// you are sitting on user/#/edit

$uid=arg(1);                      // quick, or...
$account=menu_get_object('user'); // the full user object, eg the uid is in $account->uid


theme_hook_suggestions based on empty field

You need to clear the cache after making changes in the template.php file.

For Drupal 7 version please run below command to clear the cache and check aftewards.

drush cc all

For Drupal 8 version please run below command to clear the cache and check afterwards.

drush cache-clear


Add show more/read more to CKEditor Drupal

I don't think this is possible within CKEditor and even if it's possible you need to make sure that your theme understands the tags inserted by CKEditor which is not always the case.

This is because when the text content is displayed on the theme layer CKEditor is not involved at all at that point and Drupal, the Text Formats you define, views if configured, and the theme layer take care of displaying the text.

Possible solution: by default Drupal gives you the body text as "Long text and summary" with the widget "Text area with a summary" and hence your editors, by default, can click on "Edit Summary" on top of the editor to input summary text. I highly recommend you stick to inputting the summary text here and then the "read more" text in the body as most themes and views use that functionality by default. Some don't, but I see this as standard most of the places.

Good luck.


If you just add the following snippet under -> location ~ '.php$|^/update.php' {

#Redirect urls with php extension
if ($request_uri ~ .*.php.*) {
        error_page 404 =  @rewrite;
}

that should get it to work! It's basically telling nginx how to handle urls with .php extension.

And then restart nginx

sudo service nginx restart


Text field formatter with link to the entity?

you could do this with a Display Suite custom field and use the tokens to build the link.

I would do it like that if I wouldn't like to write a custom template. Or, as already mentioned, create a template for that node. Due to the fact that you don't use the native title, you will have it available in the node template and you can change the markup there.


how to make unsortable header colmn in theme_table drupal 6

Looking at the code for tablesort_header the sortable stuff is only added if the particular header item is an array. So you can cancel off certain columns by just setting the header to a string, e.g.:

$tableHeader = array(
  'This colum header is not sortable.',
  array('data' => 'Article','field' => 'a.title'),
  array('data' => 'From date','field' => ''),
  array('data' => 'To date','field' => ''),
  array('data' => 'Perpetual','field' => ''),
  array('data' => 'Access type ','field' => ''),
);


It seems that the problem was some kind of data mixing made by mistake at the page.tpl.php.

I think it's fixed now.


There doesn't seem to be an "elegant" way to do this. All that Ubercart provides for shipping modules is a hook to register callback functions. The hard work of dividing products into individual packages is left on the modules. Which kind of makes sense, but also makes the system absolutely "unhookable".

Thus, to add an initial weight to each package, you would have to hack every shipping quote module and initialize each new package's weight before the individual products' weights are added up.

This is what I ended up doing with my UC Auspost module:

--- uc_auspost.module.orig      2011-08-15 08:59:46.000000000 +1000
+++ uc_auspost.module   2011-08-15 09:04:04.000000000 +1000
@@ -562,6 +562,7 @@ function _uc_auspost_package_products($p
           $addresses[++$last_key] = $address;
           $key = $last_key;
           $packages[$key][0] = new stdClass();
+          $packages[$key][0]->weight = 200;
         }
       }
       $packages[$key][0]->weight += $product->weight * $product->qty * uc_weight_conversion($product->weight_units, 'g');


If you are placing the menu in a block for display, check out the Menu Block module https://www.drupal.org/project/menu_block it has an option to expand all menu links.


As per Drupal 8 form api you can define checkboxes like below:

$form['high_school']['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => array('SAT' => $this->t('SAT'), 'ACT' => $this->t('ACT')),
  '#title' => $this->t('What standardized tests did you take?'),
  ...
);

In your case you can update above code

$options = array();
$options[1] = 'example_url';
$options[2] = 'example_url4';
$options[3] = 'example_url2';

$form['items_selected'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#title' => $this->t('Title you want to give'),
  ...
);


Email without body being sent to newly added users

Do you have any module that alters mail before being sent? If so, can you check if they are causing the problem.

Can you check for other mails as well, sent by Drupal. Do they generate the same issue?

Apart from that, please check the mail headers once, that might give you some hint.

If you get anything, Post it here, I will be happy to help ....


drush --quiet cron generates watchdog notices

drush cron simply calls the Drupal cron function. Drupal is initiating the watchdog messages; Drush implements system_watchdog() to convert these messages to drush log entries (Drupal 6 and 7).  If you set the option --watchdog=0, then these messages will not be printed by Drush.

If there is a problem with cron, then $? should still be set to a nonzero value when drush cron exits, and the watchdog messages will still be available in the Drupal Watchdog log (visible via drush watchdog).

If you need a finer level of control over the error behavior of Drush cron, please submit a feature request in the issue queue.


Set order / weight of user profile core fields against user profile custom fields

You can just try and set the weight as follows

$form['status']['#weight'] = field_info_max_weight('user', 'user', 'form') + 10;

Have not tried it but I am pretty sure it will work. This will make sure the status will always be the last field.

Also it should be $form['account']['status']['#weight']


Set from e-mail address for new user registration only?

You can use hook_mail_alter() to change the "from" email address of any email sent out from your site. Your code would look something like...

function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <noreply@mysite.com>';
}

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the $message variable from the code sample above.


how to get a field name by field label in Drupal 7

If you want to find specific content types based on field you can use:

field_info_instances($entity_type, $bundle_name);

If you want to find any field you can use:

field_info_field_map();

In both cases you will get an array of fields and you can get field name by filtering label value.


How do I make an internal link with CKEditor?

Yes, what you're looking for is covered by the LinkIt project.

  Linkit provides an easy interface for internal and external linking
  with wysiwyg editors by using an autocomplete field. Linkit has by
  default support for nodes, users, taxonomy terms, files, comments and
  basic support for all types of entities that defines a canonical link
  template.

Once you install the module, you'll need to create a profile (under Administration > Configuration > Content authoring > Linkit) for selecting your entities. Following that, configure your text format (under Administration > Configuration > Content authoring > Text formats and editors) to use your LinkIt profile.

Once associated, you should be able to add a LinkIt button to your text format toolbar which will let you autocomplete links to your page content.


I discovered the region is only visible in the variant drag/drop editor after it's been referenced in the template (because in fact you're looking at a site preview, not just an admin page - but that wasn't terribly obvious as none of the rest of theme was visible):

<?php print $content['foo'] ?>


Yes, you can call it whatever you want. It's a regular content type like any other, i.e Page, News, Event, Blog post, etc.

Perhaps this will help: Absolute Beginner's Guide to Organic Groups (OG)

Cheers,


Taxonomy terms follow/unfollow module (even for anonymous users)

You can use my sandbox module
Total Subscription

This module is in the Drupal project applications' issue queue.

It will provide the functionality as per your requirement.


Combining 2 Queries to pull titles of 2 related content types from the node table

I think you just want to join the node table in to your query again and grab the title that way:

$query = db_query("
  SELECT n.nid AS pnid, n.title AS ptitle, n2.title as swatch_title
    FROM {node} n
    INNER JOIN {$products} p ON p.$productref = n.nid
    INNER JOIN {node} n2 ON n2.nid = p.$productref"
);


how to send notification to seller when payment is received

Assuming author of product is also seller, You can do this with a rule using loop and author:mail. Try importing this rule and see how it works

{ "rules_e_mail_seller_checkout_notification" : {
"LABEL" : "E-mail seller checkout notification",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "uc_cart" ],
"ON" : [ "uc_checkout_complete" ],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "order:products" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "[list-item:node:author:mail]\u000D\u000A",
            "subject" : "OrderID: [list-item:order-id] Product: [list-item:title]",
            "message" : "Order: [list-item:order-id]\u000D\u000ANid: [list-item:nid]\u000D\u000ATitle: [list-item:title]\u000D\u000AQty: [list-item:qty]\u000D\u000APrice: [list-item:cost]\u000D\u000ASeller: [list-item:node:author]",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]

}
}

source - https://www.drupal.org/node/1830962


How to add css and js to a views-view-table--viewname.tpl.php

You could do this by using a process function at theme level...

function YOURTHEME_preprocess_views_view(&$vars) {
    if (isset($vars['view']->name) && $vars['view']->name == 'YOURVIEW') {
        drupal_add_css("themes/bartik/style-test.css", $type = 'file', $media = 'all', $preprocess = FALSE);
        drupal_add_js("jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);
    }
}

Change 'YOURTHEME' to the theme you are using so if 'bartik' then
you want bartik_preprocess_views_view().
Change 'YOURVIEW' to the name of your view. You can get this by
printing $vars['view']->name from the function.
Clear caches after adding function.


For anyone looking in the future, this will solve it.

Add this to your htaccess file:

# Allow the alias "/libraries" to work without breaking actual assets in the libraries directory.
RewriteRule ^libraries$ /index.php [L]

Just before this block:

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

I also had to add an .htaccess file to the libraries directory. Inside of that, I had to do:

DirectoryIndex ../index.php
DirectorySlash off

Now I can create an alias for /libraries and not introduce and endless redirect loop, and physical assets (CKEditor plugins) can still be loaded correctly from this directory.


How to dynamically change the CSS style of a node-type?

Unless you have a ton of CSS you should add the CSS for all the nodes and use the node type class on the wrapper div of the node.

I can't remember the exact classes you can view them in the source. You could do something like this

.node {}
.node-page {}
.node-blog {}

Where the first class is on all nodes and the latter is dynamic for the node.


You can use hook_field_widget_WIDGET_TYPE_form_alter() to alter the button name

example:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function example_field_widget_inline_entity_form_form_alter(&$element, &$form_state, $context) {
  // Rename the button in specific form.
  if($form_state['build_info']['form_id'] == 'eck__entity__form_edit_sample_sample') {
    $element['actions']['ief_add']['#value'] = t('Add new medecine');
  }
}


Unit tests must have the following namespace: Drupal\Tests\dev_module\Unit.

For complicated reasons, they also don't show up in the right group but they are all in the PHPUnit group.

To run your unit tests with phpunit, just pass the module folder, that also makes it 10x faster for finding the tests:

./vendor/bin/phpunit -c core modules/dev_module


content access does not work after changing domain

Rebuild the permissions table.

Go to /admin/reports/status/rebuild
Or find the link on the status report: Reports -> Status report and the link is under the Node Access Permissions row.


Fast way to test (manually) commerce checkout process

This is not specific to Drupal, but you can use Selenium IDE.

Selenium is a framework for automated testing, but the IDE allows you to do lazy manual testing too.

You need to install Firefox and the Selenium IDE addon.

Basic explanation of how to get started

Open the IDE (addon) and press the red "record" button.
Go to your site and carry out all the steps manually. Selenium IDE will automatically record the steps as you go along.
You can also add steps manually or edit the steps in the displayed editor.  This supports cut and paste so you can edit it pretty quickly.
When you're done, save the file.  You can then open this file again in the IDE and press the play button to automatically carry out all the steps.


You might get it to work by implementing an "edit-in-progress" (= EIP) feature using the Flag module, combined with using the Rules module. Similar to what I described within "Option 1" in my answer to "Can the Flag module be used to lock content while editing to prevent concurrent edits?" (BTW, that question is a variation of yours, not a duplicate though ...).


Jump Menu Style Dropdown To External Links

you could create a node type link and a Views jump menu that loads said node types.


It's generally considered bad database design to give primary keys any business meaning. Just think what will happen if your business changes and your claim number format isn't the same anymore. Changing primary keys in DB is very hard to do.

Malks advice is very good. Add a specific claim ID field to your content type and use token and Automatic Node Titles module and maybe Pathauto to get nice URLs.


Product category filter on the /products page

You need to add a new filter to your view and remove the default category filter.

You should choose: Content: Has taxonomy term ID (with depth)

This filter / argument will also return content assigned to child terms of any given taxonomy term.


What drush version I can use that doesn't require composer?

I believe any version on this page that is released as a phar file:
https://github.com/drush-ops/drush/releases

Super old versions of Drush (unsupported) were not released as single phar files. The current version of drush (version 9) seems to be geared to released/maintained via Composer only; and no longer Pecl or other distribution channels.


Your base route is wrong. You need to use the route that node uses for /node/1. That's not node.view. It's entity.node.canonical.


How to display default image in Drupal 8

Instead of doing this in code, the Drupal core image fields provide a default image setting in the UI as well.

If you navigate to an image field in the UI (Structure > Content types > [Add/Edit a content type] > Manage fields > [Add/Edit image field]), you can upload a default picture that will be used by Drupal in case no image was provided.


Manage display not updating user account display

Are you sure you edited the right viewmode? Have a look at the viewmodes which are enabled. Probably you moved the fields not on the viewmode "Full Content" (or "Full Profile") but on the "Default" instead. Or maybe the "Full Profile" is not activated?


Self answered by user1031742

I had to enable permissions for viewing product - namely: View any Product product. Otherwise any content pulled from product would be forbidden to all users but administrator.


How to get CCK optionsfield value, if I have the key for that value?

Node_load will return fully-populated node object.

Value of cck fields in node object are usualy accessed in this way:

 $my_node_object = node_load($nid);
 $myVar = $my_node_object->field_your_field_name['0']['value']

You can see what $node object contain if you do

dsm($my_node_object); // Devel module must be turned on

Hope this helps.


I'd rather try to use the Views Accordion module. Here is a screenprint of what you can get from it (from its project page):

If your question is about D7, you may also want to add the Views Nested Accordion module. Here is a screenprint of what you can get from it (from its project page):


Getting Miss always in varnish cache for the page using REST API

First of all, we need to disable "shield" module from our modules and then we need to check Cloudfare rules for caching and need to update accordingly.


what are the consequences of altering the users schema?

For your case, as you are just altering a field's length, without adding new fields, or new indexes, the only problem could be code that handles the same field, and which uses an hardcoded value for its length. That could be code executed from a third-party module, or a future version of Drupal.
For example, user_validate_name(), the function that is used to validate the username entered during the account registration, or when the user account is edited, uses the following code.

if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
  return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}

If a module alters the database field containing the username to make it bigger, Drupal would still throw an error when the username length is higher than USERNAME_MAX_LENGTH (actually 60, also in Drupal 8).

The reason why altering a database table defined from a module is not something suggested to do is that it would cause problems when more than one module do that for the same field.   Imagine what would happen if a module increases the length of the signature field to 350, and another module changes it to 300.
The other problem is when the modules are uninstalled. Which size would the field get when one of the modules is uninstalled? If modules remember the size the field had before they were installed, there would be a problem when modules are uninstalled in an order that is different from the installation one. If modules restore the field size to the original one, that would cause a problem when only one module changing the field is uninstalled.

In the case a module adds a new field, there could be some performance issues if the module doesn't introduce an index. If the module introduces an index for the added field, there could be errors with the SQL queries used from the module that introduced the database table; if then those queries are not dynamic, it would not be possible for the module that added the field to alter them.


You may use combination of Metatag, Views and Editable Fileds.

Configure node types to use own fields for meta tags like
keywords, description, abstract, etc. and create it. use Field
Permission to restrict access to this fields.
Configure Metatag to    use newly added fields for filling metatags
on Metatag admin page    or node type page.
Create view with table    display, add    metatag-fields. Choose
formatter "Editable" on    each field    settings.
Set path for this    view like admin/config/search/metatags/massedit. Save view and now you    can mass    edit
any fields.

Also you can try Editable Views module.


How to hide View Page Menu if there is no content?

There are multiple options do do this, but all seem to require custom coding.

Maybe Hiding tab when view is empty or How to find out programmatically if a view has a result before rendering the whole view? give an idea of how to do that. They are both mainly about Drupal 6, but the same principles apply.

I would probably use some hook_preprocess or theme function, load the view using views_get_view(), execute that with all the necessary arguments if any, then check the result count and if that's empty, remove the menu link from the page. That last part is described in How to hide menu items without relying on permissions [SOLVED] and Customizing menu link output

Update:
So in your example you could do:

$view = views_get_view('news');
$view->execute();
$link['#access'] = count($view->result) > 0;


I'd say in this specific case the error message looks like saying that $user is NULL. You need to validate that User::load returns a valid UserInterface because if the $uid passed to the method is not found, it will return NULL, which is the value you are getting. Try with a valid uid like 1, see what happens and move ahead from there.


how to Remove "Add new Content" from the Main page

Just add this code to the page.tpl.php or page--front.tpl.php on Drupal 7.

find

<?php print render($page['content']); ?>

and replace with below code.

<?php  if(drupal_is_front_page())
                {
                    unset($page['content']['system_main']['default_message']);
            }
        print render($page['content']);
    ?>

And i believe you surely get all blocks or contents you posted on page.

and to remove page title on page like

Welcome to "website name"

find this code on page.tpl.php or page--front.tpl.php

<?php if ($title): ?>
<?php  print $title; ?>

<?php endif; ?>

and you can remove this code or else just make a comment over.


Shutdown functions not working on php-fpm setup?

Example shutdown is getting called ; you can't use dpm in a shutdown function though, because at that point the session already got written to the database and there's just no way to add a new message to it.

In PHP-FPM, the connection also could have already been closed, so print or var_dump is not really a good test to check if you're shutdown function is getting called in general ; it should work in D7 though if you're not using a module that's specifically closing the request, so you should be able to use print "Hello world"; and get it to show on screen (that's what the core "Shutdown functions tests" is doing in D7).

If you want something realiable to use in a shutdown function to check if it got invoked, try something like file_put_contents('/tmp/drupal-debug.txt', 'Shutdown function called');


I was looking for a solution for hours. Right after posting the question, i found one:

calling

\Drupal::moduleHandler()->invoke('openid','begin',array($openid,$return_to,$form_state));

seems to do the trick.

Still, I wonder why I can call user_login_finalize directly.


Node theming through Views or tpl.php files - which one is better for performance?

The two are essentially doing the same work and are going to degrade over load very similarly from my experience. If you look at how views works and builds its content, contextual filters is just aiding the discovery by passing in all the data the view needs. This has to be done one way or another. After that, the view builds the same regardless.

However, tpl files are greatly useful for code management. If you are really worried about performance, then you need to look into memcached and/or Varnish - both are open source and can be implemented easily on most *nix servers.


Hot to pass an argument to #ajax['path']

From the docs:

  It is possible to replace ajax_form_callback() with your own functions. If you do so, ajax_form_callback() would be the model for the replacement. In that case, you would change #ajax['path'] from the default 'system/ajax' and set up a menu entry in hook_menu() to point to your replacement path.

So you need to

Set up a menu callback (looks like you've already done that)
Copy ajax_form_callback() to that path's page callback function
Make the changes you need to. The function is very short so it should be obvious which bits you need.
In your form elements use this:

$form['foo'] = array(
  ...
  '#ajax' => array(
    ...
    'path' => 'path/to/new/callback',
  ),
);

You shouldn't write any JS code to invoke this manually, Drupal takes care of that for you.

Note that this method does load the full form; that's unavoidable using Drupal's built-in AJAX functionality.


Get image width for a styled image in module

according to documentation, you just need image_style_path instead of image_style_url

and finally

 $field_image = field_get_items('node', $node, 'field_image', LANGUAGE_NONE);
 $img_uri = file_load($field_image[0]['fid']);
 $img_url = image_style_path('mystyle', $img_uri->uri);
$img_info = image_get_info ($img_url);


Correct way to call a service in a controller

There are 3 questions here:

How to create a controller?
How to create a service?
How to use services in a controller?

1. Create a controller

1.1 Add a controller class - you did it. For others see Drupal documentation

1.2 Add a routing file - it looks like this is missing in your code:

my_module.routing.yml

my_module.my_route_name:
  path: '/my/path'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::myAction'
  requirements:
    _permission: 'access content'

see Drupal documentation

2. Create a service

2.1 Add a service class - you did it.

2.2 Add a routing file - you did it although it contains extra code that belongs to the routing file. This is all you need:

my_module.services.yml

services:
  my_module.my_service:
    class: Drupal\my_module\Service\MyService

see Drupal documentation

3. Use services in a controller

You did it. Here's a reference for others:

3.1 Override the create() method

The controller class inherits this method from class ControllerBase. Its role is to create the controller object. Watch the method argument: it is passed the services container. Extract the services you need and pass them to the constructor:

public static function create(ContainerInterface $container) {
    $my_service = $container->get('my_module.my_service');
    $other_service = $container->get('other_service');

    return new static($my_service, $other_service);
}

3.2 Initialise services in __construct()

public function __construct($my_service, $other_service)
{
    $this->my_service = $my_service;
    $this->other_service = $other_service;
}

3.3 Start using the services


Add line

RewriteBase /dupalHere

to your .htaccess file.


"You are not authorized to access this page." in Chrome after returning from offsite payment

Possible solution would be adding following rows to .htaccess file inside <IfModule mod_headers.c> block.
  Header always edit Set-Cookie (.*) "$1; SameSite=None; Secure"
  Header onsuccess edit Set-Cookie (.*) "$1; SameSite=None; Secure"

Some more info on this issue:
https://docs.datatrans.ch/v1.0.1/docs/security-samesite-cookies


How to use hook_url_outbound_alter for emails only?

Can I use hook_url_outbound_alter() to only alter URLs when it was invoked from a specific module or something?

You cannot, if that module doesn't put in $options (the same argument passed to url()) something that makes you understand that. To make an example, entity_uri() uses $options['entity_type'] and $options['entity']; if you were trying to intercept the calls to url() done from entity_uri(), you could check the presence of those options.
Otherwise, the context given to hook_url_outbound_alter() doesn't allow to understand which module called url(). Maybe you could get that using debugging functions, but I am not sure I would put that kind of code in a module.

Since you seem to trying to alter links in an email sent from Drupal, you could implement hook_mail_alter(), assuming the emails are sent using the correct way of sending them with Drupal.


Add Google Analytics JS file to every page

When I have been in this situation, I use the GA module, look at the JS file that the organization give me, and then update the Code snippet (before) and or Code snippet (after) under the Advanced Settings => Custom Javascript code tab on admin/config/system/googleanalytics as needed.


I haven't found a solution to the "Killed" loop issue (even after scaling up to the largest instance offered by my host, which has 64GB of RAM), but I've managed to get drush itself to work by pulling the .phar from Github and making it executable.

Using the install script still doesn't work (still leads to the Killed loop) despite making sure that everything that should be executable is executable, and installing from the tarballs or via composer likewise fails in a similar way.


How to display a field only if option (x) isn't selected

Create a file in template folder : node--articles.html.twig

             {% if content.field_gif_image|render is not empty %}

{{ content.field_gif_image }}

             {% elseif content.field_image|render is not empty %}

{{ content.field_image }}

             {% endif %}
             {{ content.body }}
             {{ content.field_more_on }}

Fields defined are just for reference, hope It can give you a clue of how to do this.


"Twig_Error_Syntax: The block 'content' has already been defined line"

You can remove all twig blocks from the template; that is, remove all of these lines:

{% block content %}
{% endblock %}

This defines a Twig Block, which could be used to extend this template, but this doesn't make sense anymore after you have implemented the condition.


How to show event calendar with active links and event details underneath

i have not tried this, but i think it will work, with calendar module enebled, go to month view, add a block view and build your underneath view, then add this block view as a footer (middle column in views ui) in your month view (Global: View area), then pass arguments in settings to be the same as your month view.


What is the meaning of $form['cid']['#value']?

cid is the comment id. And this comment checks if it is empty or not. When it is not empty, it means that we are editing an existing comment as opposed to creating a new one and this code doesn't need to run.


View commerce product image and price fields

I'm pretty sure you'd have worked out the *the latest 3 items placed in the show_product content type* part already:

Add filters, Node: Type, Node type: show_product
Add sort criteria, Node: Post date, Sort order: Descending
Items to display: 3

For the attributes part, the tricky one, instead of defining a relationship in the existing view, you'd be better off creating a whole new view, which would list the attributes of product passed in as argument.

To make it all work together, you'll attach the latter view to the former one using one of  Viewfield (7.x-dev), Views Field View (7.x-dev) and View reference modules.

An example, using Viewfield. To the show_product node type add a hidden View field called Attrview. Set it to "Always use default value". Set the default value to the attribute listing view. The argument is "%nid". Exclude its display from node teaser, full view etc.

In the first view, then, along with Price and Image, also add Attrview as a field. Done!


How to enable menu link when creating a new node?

You'll need to create the menu item separately, using menu_link_save

$item = array(
  'menu_name' => 'main-menu',
  'link_title' => $node->title,
  'link_path' => 'node/'. $node->nid,
);
menu_link_save($item);


Unfortunately this behaviour is hard coded into the theme_user_admin_roles() function, so you'll need to override that theme function to remove the link and add the locked label. You'll also need to override the access check for the role edit/deletion page so it can't be visited directly.

This is the theme override you'll need to use (it's exactly the same as theme_user_admin_roles() except it has an extra test for your custom role):

function MYTHEME_user_admin_roles($variables) {
  $my_role_id = function_to_get_custom_role_id();

  $form = $variables['form'];

  $header = array(t('Name'), t('Weight'), array(
      'data' => t('Operations'),
      'colspan' => 2,
    ));
  foreach (element_children($form['roles']) as $rid) {
    $name = $form['roles'][$rid]['#role']->name;
    $row = array();
    if (in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID, $my_role_id))) {
      $row[] = t('@name <em>(locked)</em>', array('@name' => $name));
      $row[] = drupal_render($form['roles'][$rid]['weight']);
      $row[] = '';
      $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid);
    }
    else {
      $row[] = check_plain($name);
      $row[] = drupal_render($form['roles'][$rid]['weight']);
      $row[] = l(t('edit role'), 'admin/people/permissions/roles/edit/' . $rid);
      $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid);
    }
    $rows[] = array(
      'data' => $row,
      'class' => array('draggable'),
    );
  }
  $rows[] = array(array(
      'data' => drupal_render($form['name']) . drupal_render($form['add']),
      'colspan' => 4,
      'class' => 'edit-name',
    ));

  drupal_add_tabledrag('user-roles', 'order', 'sibling', 'role-weight');

  $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'user-roles')));
  $output .= drupal_render_children($form);

  return $output;
}

And this is the code for the access override (needs to go in a custom module)

function MYMODULE_menu_alter(&$items) {
  $items['admin/people/permissions/roles/edit/%user_role']['access callback'] = 'MYMODULE_user_roles_edit';
  $items['admin/people/permissions/roles/delete/%user_role']['access callback'] = 'MYMODULE_user_roles_edit';
}

function MYMODULE_user_roles_edit($role) {
  $my_role_id = function_to_get_custom_role_id();

  if ($role->rid == DRUPAL_ANONYMOUS_RID ||
    $role->rid == DRUPAL_AUTHENTICATED_RID ||
    $role->rid == $my_role_id) {
    return FALSE;
  }

  return user_access('administer permissions');
}


How to upgrade module table scheme for entity

@Clive is correct (in the comments). You'll just want to add the new definition to the schema hook and then create an update script in the .install file (hook_update_N) to add in that definition for sites/installations that have already created your new entity.


Compare two views that present two different content type and delete nodes

You can simply achieve that by using the Remove Duplicates module.

  This module helps the administrator to easily remove duplicate nodes according to one of the node fields.


Yes!!

Go to Manage form display of the content type
Go to the entity reference field and there you can find a list of options including checkbox .


Explain field's language opposed to node language

If you use the module Entity translation you have the possibility to say that the body field can be translated but the image field should not be able to be translated.

In your example this would mean

The value of $node->field_body will have different values for the different languages the field is translated to. I.e $node->field_body['en'][0]['value'] could differ from $node->field_body['sv'][0]['value'].

But at the same time the image field will only have value in LANGUAGE_NONE.

Before the most used setup to have a multilingual site was to use the  Internationalization module, which would create a new node when a translation of a node was done. The new approach with entity translation translates the fields instead.

Worth noticing, the Internationalization module can be used together with Entity translation. I am only stating the older solution to multilingual sites.


how to render a welcome page in page--front.tpl.php

Login as admin to the site, visit "admin/config/system/site-information" , scroll down to find setting for for front page and then form "Default front page" set the node relative path to be used as default front page that looks like "welcome-message" in your case.

with the above process you have informed drupal to use the node you have created as front page.

Now remove the hard-coded page front template you have created before as "page--front.tpl.php" because it will be used over the node till its present there.

clear your caches.


How to send an email 1 minute after a node is created or updated by using a scheduled Rules Component?

There are a couple of things in your Rule and Rules Component that are either wrong, or should be simplified, such as:

the scheduling part of it belongs in your Rule, not in your Rules component.
nowhere you have an "identifier" for the task to be scheduled (each scheduled task requires an identifier).
all your Rules Component should have to do, is to send an eMail to "some user" (= the node author in your case), indicated by a parameter of the component.
what should happen if the same node is updated twice in say 30 seconds?

Read on for an example of a Rule and Rules Component to achieve what you're trying to do.

Step 1:

Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly eMail reminder (Subject)",
          "message" : "Friendly eMail reminder (Message body) ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.

Step 2: Create a "Rule" using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste, after you changed (twice) the machine name article to advertisement to fit your case; then change the rule from inactive to active):

{ "rules_send_email_reminder_to_node_author" : {
    "LABEL" : "Send email reminder to node author",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [ { "node_is_published" : { "node" : [ "node" ] } } ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[node:author]-[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : "+1 minute",
          "identifier" : "[node:author]-[node:nid]",
          "param_user_to_notify" : [ "node:author" ]
        }
      }
    ]
  }
}

Note that this rule refers to the Rules Component from the previous step. And it also includes an extra Rules Condition that the node must be published (similar to the Rules Condition in your question).

The schedule_delete that is part of this rule is to ensure that previously "scheduled" eMails will get removed when updating a node multiple times during a very short period like 20 seconds. That way it only triggers 1 eMail, and related to the most most recent update (imagine you add some extra data from the node content to the message body, in that case you don't want to eMail outdated information, right?).

Also important is the identifier you use for these scheduled tasks. In this case I used [node:author]-[node:nid] (= "author", followed by a "-" and then the nodes's "nid"). That way you have a unique task identifier for every node of each author.

Step 3: Review your timings

Rules Components scheduled for execution using Rules Scheduler, will actually be executed "next time cron runs" (after the scheduled date/time has arrived). So make sure to actually run cron and be patient enough for cron to have run.

Example: if you want to send the eMail after 1 minute, but cron only runs every 60 minutes, and the last cron ran 5 minutes ago, then you'll have to wait another 55 minutes before an attempt will be made for the eMail to be delivered.