Revert configuration languages overrides

Answering to myself, I think I've found the solution:

$langcode = 'es';
\Drupal::service('language.config_factory_override')->installLanguageOverrides($langcode);


Can't get favicon/shortcut icon to show up

Just went through this Drupal favicon mess myself :) Hope this helps:

  When I looked into the generated source code, I could not see neither my file nor the default drupal icon.

This is the first problem to solve – getting at least the default blue Drupal drop icon to show again. For this:

There is both a global "Shortcut icon settings: Use the default shortcut icon." setting at admin/appearance/settings and an equivalent one for each theme that can be enabled on that page. In all these forms, tick this setting and save the form. If neither this box is ticked nor a valid path entered into the "Path to custom icon" field of the form whose settings "win" the overwriting, Drupal will interpret this as "do not show any favicon".
Make sure Drupal's default favicon is readable by your webserver user: visiting http://example.com/misc/favicon.ico for your domain should show that icon. If it is not accessible to the web server, Drupal will detect that and not even render a shortcut icon header entry.
Cache clearing should not be necessary, but who knows. If still no favicon shows up, do a drush cc all and check again. Check the HTML source code, not what the browser shows, to prevent issues with the browser cache.

Now that the "blue drop" Drupal default favicon shows up again, let's configure your own one. The surefire way is this:

Navigate to the settings screen admin/appearance/settings/theme-name of your "most-sub-theme" applying to the page where you want your favicon to be in effect. So if you have a theme A, a sub-theme of A called B and a sub-theme of B called C, go to admin/appearance/settings/c.
Click "Shortcut icon settings: Browse" and upload a custom favicon. It will end up in the files root directory of your default site.
Load your site again, and it should show your favicon now, at least in the HTML source. If not, try a full cache clear, though that never helped in my case.

Explanations:

Choosing the most-sub-theme. This is necessary because the admin/appearance/settings form is just the global setting for all themes, and values entered here will be overwritten by each theme and sub-theme down the chain of themes. So the setting in the "most-sub-theme" will win. Plus, it seems there is no option to not enter a value into the "Shortcut icon settings": when you keep the "Path to custom icon" field empty, Drupal will not fall back to the theme higher up in the chain, but interpret it as "do not use any favicon".
Uploading, not typing in a path. There seems to be a Drupal bug with the "Shortcut icon settings" form: it will only accept typed-in values for the "Path to custom icon" field after uploading an icon before. You can then modify the value in that field and it will modify what favicon is used, but when you delete the value, save the form, enter a new value and save again, no favicon will show up even though the same value worked before.
Base path when typing in a filename. If you use the above trick to upload first, then modify the value in the "Path to custom icon" field, also remember that the base path for filenames entered here is the files directory of your default site. So, sites/example.com/files/ from web document root. You can be sure it's the right one by checking that your immediately before uploaded favicon arrived in this directory. (If the referenced file exists, Drupal will also accept without form validation errors if you type in a path starting at document root (like sites/all/themes/my_theme/favicon.png) – but I never could get favicons referenced this way to show up.)


Is it redundant to use the "boost" module if varnish is used?

No, with the correct configuration, Boost and Varnish can work together. The combination is said to speed up your site even more than just Boost or Varnish (I haven't tried it myself yet).

See Will Boost conflict with Varnish and Use Varnish for cache storage instead of file system. If you're visiting DrupalCon London, check out the Boosted Varnish talk.


Custom Javascript doesnt work unless JQuery is set to Default jQuery Version

magnific.js clearly needs the .off() function which was added in jQuery 1.7. If you need magnific.js, you will need jQuery 1.7 and it is your job to upgraded your custom JavaScript accordingly.

Upgrade to 1.6
Upgrade to 1.7

You may find the changes you need are minimal.


Add class to views row if image fields has content

When you use the preprocess function you find the result in

$vars['view']->result

and the corresponding classes array under

$vars['classes_array']

where in results and in classes array the corresponding rows have the same key.

You can do now something like this in your preprocess function:

foreach ($vars['view']->result as $rid => $row) {
  if (isset($row->YOUR_FIELD) && !empty($row->YOUR_FIELD)) {
    $vars['classes_array'][$rid][] = 'has_field';
  }
  else {
    $vars['classes_array'][$rid][] = 'has_no_field';
  }
}

It is untested and just a little scribble but maybe it helps you.


Tag/Label an image in an image field with Taxonomy terms?

I would suggest using a field collection for this.  This creates a collection of fields that you can add and do exactly what you are looking to do.


Hooking into updates to an entity reference field within Parent node

You don't have a direct connection for those(the same way some entities work at least) so best approach would be to have a node_update for Color and then inside it to query (can use entityQuery) and see which fruits have that color, from here you can do your stuff.

the following pulled out of my head since I haven't touch D7 for over a year so here we go

function node_update($node){
  if($node['type'] == 'color'){
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'fruit')
    //value or target_id
    ->fieldCondition('field_photo', 'value', $node['nid']);

    $result = $query->execute();
  }
}


how to remove module-created links from menus?

Ok, just in case anyone else finds this useful: I got in this pickle because I installed a module (nodehierarchy) which generated menu items. Menu items created by modules are not deletable in the normal admin UI. When I removed the module it did not clean up after itself, leaving orphaned entries that drupal thought belong to a module that doesn't exist.

I don't know why drush cc menu didn't clean them out, perhaps a policy of not deleting data just in case.

To fix: start a mysql client on your drupal db and inspect the contents of menu_links, find the rows and delete. e.g.

mysql> delete from menu_links where module='nodehierarchy';

Then clear caches and fixed.


how can i see recurring payment details on my website?

I'm able to see my memberships at /admin/store/orders/recurring (this is Drupal 6). From there I can edit the recurring fees and search based on a number of different properties.


How do I direct link a view to a taxonomy menu?

If I understand well your question, I think that you can show your menu with the Expose Filter fature of Views:

first add the filter related with your taxonomy:

then select the type of your menu (for example: dropdown) to expose:

and finally, you can expose these filter to visitors, to allow them to select terms to see just the content related:

I hope I have understood, and that information be useful. Here is an example of the view with results according a selection:


So, nothing was wrong with my batch definition, but I tried to disable the web profiler module and everything gets back to normal!


Multistep form loses input when visiting previous step

I think you should add if statement with #triggering_element or #clicked_button. Example:

function PREVIOUS_STEP_submission_OR_SOME_KIND_OF_CALLBACK($form, &$form_state) {
  if($form_state['clicked_button']['#value'] == 'BACK') {
    //show_previous_step()
  }
  else {
    $a = new ind();
    $a->get_ind( $form_state['build_info']['args'][0] );

    $form_state['values'] = get_object_vars($a);
    unset($a);
    // or your logic
  }
}


Making a variable in a certain node type and access that variable in another node type

What you are looking for is, basically, Entity Reference, as mentioned by Jimajamma and Bala:

  Provides a field type that can reference arbitrary entities

Just add entity reference field to news and allow artists to be selected. For pictures and songs, use either simply fields in Artist content type, or repeat the process - create content types for them, and add entity reference fields to artist content type.

Now, for display consider Views - it can use entity reference field to show all songs by artist in setup like that. I believe that's the easiest way.


How do I put this custom CSS and JavaScript into a certain block?

In very broad strokes, in your module's block() or block_view() hook, you would do something like this:

 drupal_add_js(....);   // see http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7
 drupal_add_css(....);  // see http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_css/7

and to have the CSS apply only to that block, look at what Drupal's block theme functions wrap the block with, and then using one of those ids or classes, cascade your CSS accordingly, eg, instead of:

.content {
  ....
}

use:

#BLOCK-ID .content {
   ....
}

or:

.BLOCK-CLASS .content {
   ....
}

Of course, you would return as the block's content either the HTML or a renderable array of it.


Alter entity_translation vertical tab access

The reason you cannot use hook_form_alter() to modify the tabs is because the hook you implement in your custom module is being fired before entity translation injects the tab.

If you use hook_module_implements_after() you can change the order of the execution of the hooks.

function CUSTOMMODULE_module_implements_alter(&$modules, $hook)
{
    if ($hook == "form_alter")
    {
print_r($modules);
        // save off hook
        $temp = $modules["testing"];

        // remove it
        unset($modules["testing"]);

        // add it to the end
        $modules["testing"] = $temp;
print_r($modules);
    }
}

The first print_r outputs:

Array
(
    ...
    [CUSTOMMODULE] =>
    [entity_translation] =>
)

The second print_r outputs:

Array
(
    ...
    [entity_translation] =>
    [CUSTOMMODULE] =>
)

Now that the custom module fires after entity translation, use hook_form_alter() to hide the tab:

function CUSTOMMODULE_form_alter(&$form, &$form_state, $form_id)
{
    // make sure you set the form_id in this conditional properly.
    // I am using the edit form of a "page" node type.
    if ($form_id == "page_node_form")
    {
        $form["translation"]["#access"] = FALSE;
    }
}


How to consume RESTful web services in a custom module?

Module RESTClient is for this purpose.

It provides 4 APIs:

restclient_get()
restclient_post()
restclient_put()
restclient_delete()


Most probably Correct faulty and chopped off HTML is not checked in the input format used. Goto admin/config/content/formats and then look at the format used for this and make sure that it's last, eg:

If this doesn't work, check out How to get teaser break to work with WYSIWYG + CKEDITOR? for more things to look into.


You can also create a view of calendar event data and export data in excel format by the help of view_data_export


How to programmatically add a custom field to Address?

Not sure if this solves your specific problem, but you can create a custom paragraph type with an address field and a boolean field, then add a Paragraph Entity field on your content type. You can limit this paragraph reference field to your newly created paragraph type. This will allow you to have a field with both address/accessibility information.


How to save a vote of an anonymous user only after registering using modal window?

You could store anonymous votes in a cookie, then on login/register, check to see if that cookie exists and cast the votes accordingly.

When an anon user tries to vote, use user_cookie_save() to save the Entity Type and Entity ID of the Entity that the user was trying to vote on in a cookie. Name it something like pending_votes. At the same time, you can trigger your modal login window. It's possible that a user won't login/register at that time and it's also possible that they will attempt to vote on other Entities before finally logging in. So you'll probably want to store the Entity Type and ID as a serialized array.
Then you can hook into a user logging in with hook_user_login() and check for the existence of the pending_votes cookie. If it's there, use it's contents along with votingapi_set_votes() to cast the pending votes. (delete the pending_votes cookie afterwards so they don't cast more votes each time they log in)


generate multiple custom blocks from a single api call

What I would really like to be able to do is keep my existing block
  class (in whatever form) and pass that same single API call to 3
  seperate templates that can be placed as three separate blocks. How do
  I do this?

This is possible. Add a configuration option to the block class in blockForm() and then use this option in build() to change the content and template. Then place the block three times and choose for each instance a different option. To avoid calling the remote API three times in one request use drupal_static().

  Alternatively, is is there some way to generate the API call through a
  function in the .theme file in my theme (abandoning my custom module
  completely) and then just pass the variables directly to the page
  rather than going through the block system?

This is no problem. You can put three variables in mytheme_preprocess_page() and use them directly in page.html.twig.

Think about caching. You can cache the remote API call with \Drupal::cache('data')->set() with a certain expire time. In a block this is not necessary, you can set a cache max-age and as long the block stays in the cache the remote API is not called.


form_state['values'] generating error undefined index: values

The error indicates precisely what is going on: during the initial call of templates_form() the $form_state['values'] does not yet exist. This will exist in a future ajax call (if you do ajax) and in validate and submit functions. You better check if it exists first with isset or empty.


Set CSS class for a View programmatically in a hook

Something like this should do it:

$view->display_handler->setOption('css_class', 'your_class');

Good luck!


SQL insert in taxonomy_index doesn't work

I think in D7, you can not use db_query() for insert operations - db_query() can be used only for Select and you should use db_insert() for insert operation.

For your 1st code bloc, perhaps the db_insert() causes 1st row with blank values - since it expects fields and values for 1st row. The subsequent $query->values() adds a second row. This may explain the blank values in dvm().


That should work. Try making sure that you have a properly loaded node object.

$node = node_load('NID');
echo $node->uid;

It is possible that if the node was created by an anonymous user that the $uid would be zero and thus wouldn't print.


Why are links missing when using the Notify module?

Your question is pretty incomplete, so let me start with adding some crucial information that I think is missing in it:

Relative path admin/config/system/mailsystem is not something that gets added to a site by the Notify module. Instead that path is what gets added after you enable the Mail System module, at least for the 7.x-2.34 version of it, which is what the rest of my answer assumes you're using.
After you enable the Mail System module you can navigate to the admin/config/system/mailsystem path.

After you do so, within the settings for "Site-wide default MailSystemInterface class", you'll be able to select either DefaultMailSystem or TestingMailSystem. However you can not, repeat not, select HtmlMailSystem (as in your question).

In order to be able to select HtmlMailSystem, you first have to enable the HTML Mail module. Which is what I did, I enabled the 7.x-2.65 version of it, which is what the rest of my answer assumes you're using.

With the above crucial additions, I think that the actual answer to your question can be found within relative path admin/config/system/htmlmail, where you can configure the settings for the HTML Mail module. I'm not sure if it's the only solution to answer your question, but pretty sure that you should select some other text filter within Post-filtering (located near the bottom within Step 3): by default it uses unfiltered, so check the results you get if you use any of the other filters you have available (or define a new filter to make it work as you want).


I guess $node is not defined. You should know when a node page is shown. Then get the node id using arg(1). Load the node object and then use.


How do i generate token for each user they submit my custom form?

1.Declare custom tokens using hook_token_info()

2.Create custom tokens using hook_tokens()

3.You can use your custom tokens using token_replace()
that is call the token_replace at the place where u need to send the email.

4.Create a seperate file inside your module with .tokens.inc extension and include the hook_tokens_info() and hook_tokens() inside it.


You can pass only the image uri, and render image using it in the twig.
Try the following suggestion:
In your loop try to get image as the following:

  $image_field_values= $t->field_body_image->getValue();
  /**
   * @TODO: if you have multiple values loop through them i will test just by the first
   */
  $image_target_id = $image_field_values[0]['target_id'];
  $image_file = File::load($image_target_id);
  $section[$key]= [
    'image_uri' => $image_file->getFileUri()
  ];

In your twig will be something like:

<img src="{{ file_url(section[0]['image_uri'])}}" >

Don't forget use Drupal\file\Entity\File;.


Is registering the path 'node/%/ajax' bad practise?

I wouldn't say it's bad practice as such, but I always go under the assumption it's good practice to prepend paths with your module name, e.g.

node/%/mymodule_ajax

That way you can be pretty sure that you won't run into any issues with other modules that don't follow the same convention.

For the record I don't think I've ever come across a module that implements the node/%/ajax path, but if you're at the start of your implementation and can change the path easily, I'd go with adding your module name to it.

It'll mean some extra work on the JS side, but if you want to be as sure as possible that you won't get path conflicts in the future, I think it's your best bet.


You should use Firebug and take a look at the function that gets called, when clicking on the "Next"-Button.(Something like onClick() )

Now take a look at the function, that gets called, when you click on the image.

Now just place the "Next"-Button function into the image. Delete the old one.

The functions are usually in a .js-File.

This is not so hard, i am a beginner and managed it with the shadowbox.


Redirection should not lose the URL parameters

To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Custom Drupal Analytics with Views- how to track the number of users by role over time?

You should record custom variables in Google Analytics. Download the GA Module https://www.drupal.org/project/google_analytics and Tokens
https://www.drupal.org/project/token
in the bottom of the configuration [yoursite].com/admin/config/system/googleanalytics
expand the SHOWCUSTOM DIMENSIONS section
populate the values with tokens like [current-user:roles]
You can also record an event upon account creation which identifies the type of account
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
you can do a JS event on submit that will record or it probably makes more sense to create a library to record all instances of certain types the way Google Developers is implying.


Taxonomy Term View - how to display parent View term info when child terms exist?

What you would probably want to do is create a view of the taxonomy terms that lists Parties, Sports, etc.  On the fields to display, re-write the output to a link to categories/%1, which will take the term being listed as an argument, and make sure to un-check link to taxonomy page.  For this view you should make the link something like "categories".  Then, in the second view (or maybe just another page in the same view), make the link something like "categories/%"  The % wildcard will take in the value of the taxonomy term form the page before.  So when you click the link from the first page it will link you to the second view, where you can make a contextual filter that takes the taxonomy term given via the URL from the one clicked on the first page and have it list the terms based on that with a relationship.


See which context is used on a page when looking at the page

You can use the active context api to get this done.,

$contexts = context_active_contexts();
print_r (array_keys($contexts));

Place the above code in your form_alter or in any hook_node_view. This will list the active context in the page.


Copy Print's print.tpl.php file into module folder, and name it print--node--foo.tpl.php.

function foo_theme_registry_alter(&$theme_registry) {
    $theme_registry['print__node__foo']['template'] = 'print--node--foo';
    $theme_registry['print__node__foo']['path'] = drupal_get_path('module', 'foo');
}

Note: My module and content type share the same name of foo.


The \Drupal::entityQuery object doesnt support JOINs I believe:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8.2.x

If it did you could Join onto the Paragraph bundle and LIKE across that all you want.

I recommend the following approach with Views, a small chance exists it may not work:

Create a View of your case study Nodes
add a relationship to the Paragraph bundle (if needed)
assure the field list for the View includes title and field_rows (you can Exclude field_rows from showing in your view if you want).
add a Grouped Filter and Expose it and select it to use your title and field_rows values.

That should do the trick...


The easiest way is with a View.

Create a new view
Disable the Page that will be checked by default.
The view should take as argument the Node ID.
Also add a filter based on the content type
Then in the view, add the fields you want (File, PDF)
On the top (+ Add next to Master), you need to add a display as a block

Now, you go to /admin/structure/blocks and add the block. Filter it by Content Type.

:)

Views module - https://www.drupal.org/project/views


Build page from content type course - use views or custom code

It's unclear from your post on your knowledge of Views.  However if your referring to the 4 content boxes being shown in the sketch then Views is a great tool for doing this.

Regarding layout there is the functionality to return all fields you require in divs / classes etc and will be able to generate the look you wish.

Also links are no problem; in fields call up [content:path] - you can then add a 'custom text' field with your link

Link

Views can general be viewed as a way of returning data from the database and present it how you wish.  enjoy!


How can I add custom classes to each view's generated row?

If you look at /core/modules/views/views.theme.inc at template_preprocess_views_view_unformatted you'll see this code:

function template_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
  $style = $view->style_plugin;
  $options = $style->options;

  $variables['default_row_class'] = !empty($options['default_row_class']);
  foreach ($rows as $id => $row) {
    $variables['rows'][$id] = [];
    $variables['rows'][$id]['content'] = $row;
    $variables['rows'][$id]['attributes'] = new Attribute();
    if ($row_class = $view->style_plugin->getRowClass($id)) {
      $variables['rows'][$id]['attributes']->addClass($row_class);
    }
  }
}

This is how if you have set a row class in the view, it gets added.

And the resulting output:

You can copy this function to your custom module and customize it as you like.  For example, this will add the "views-row-" plus the name of your view cleaned up using the pathauto cleanstring utility:

function mymodule_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];

  foreach ($rows as $id => $row) {
    // Add custom class to each row that encorporates the view id.
    $custom_row_class = \Drupal::service('pathauto.alias_cleaner')
      ->cleanString($view->id());
    $custom_row_class = 'views-row-' . $custom_row_class;
    $variables['rows'][$id]['attributes']->addClass($custom_row_class);
  }
}

If you would like to add classes to a views rows from hook_preprocess_views_view, you can do it this way:

function mitsloan_global_preprocess_views_view(&$variables) {
  $view = $variables['view'];

  if ($view->id() == 'testview') {

    $row_style_plugin = &$variables['rows'][0]['#view']->style_plugin;

    $custom_row_class = 'views-row-' . \Drupal::service('pathauto.alias_cleaner')
        ->cleanString($view->id());

    $row_style_plugin->options['row_class'] = $custom_row_class;
  }

}


How can we use form directly without using drupal form handler

If your goal is to just get the HTML output of an existing drupal form then this will get you there:

$form = drupal_get_form('drupal_form_id');
$form['#action'] = url('mypath');
print render($form);

Replace 'drupal_form_id' with whatever registered Drupal form you want and url('mypath') with whatever URL you want to post to.


Display Local tasks from one page to another

I kinda managed to to this by using the following piece of code:

$path = drupal_get_normal_path('path-where-local-tasks-are-displayed');
if($path) {
  menu_tree_set_path("navigation", $path);
  menu_set_active_item($path);
}


Metatags and Commerce - pass taxonomy metatags to commerce product view

The short answer is that the metatag module will provide metatags entered for terms if your view path matches the core taxonomy path (taxonomy/term/%).

In metatag_views_post_render(), metatags checks if your view display path matches the path from the entity's info before it will proceed.

This gives you a couple of options.

1) You can make sure your view uses the taxonomy/term/% path and use Pathauto to make the aliases for your terms for that vocabulary (or all terms) match the desired 'category/term-name' pattern.

2) You can mimic what the metatag module does for your specific view using a custom module and these hooks:

/**
 * Implements hook_views_post_render().
 */
function MYMODULE_views_post_render(&$view, &$output, &$cache) {
  // Build a shortcut to the current display object.
  $display = $view->display[$view->current_display];

  // Only proceed if this view is a full page, don't process block or other
  // Views display objects.
  if ($view->name == 'MY_VIEW_NAME' && $display->display_plugin == 'page') {
    // Check if this is an entity display page, if so trigger
    // hook_entity_view().
    foreach (entity_get_info() as $entity_type => $entity_info) {
      // Entity paths will include an auto-loader that matches the entity's
      // name, thus the path will be 'some/path/%entity_name'.
      if (isset($entity_info['path']) && $entity_info['path'] == 'taxonomy/term/%taxonomy_term') {
        // Only proceed if this entity type supports meta tags.
        if (metatag_entity_supports_metatags($entity_type)) {
          // There must be at least one argument and the first argument must be
          // numerical.
          if (!empty($view->args) && is_numeric($view->args[0])) {
            // Only the first argument is used.
            $entities = entity_load($entity_type, array($view->args[0]));
            // Only if the entity actually exists.
            if (!empty($entities)) {
              $entity = array_pop($entities);
              MYMODULE_entity_view($entity, $entity_type, 'full', NULL, TRUE);
            }
          }
        }
      }
    }
  }
}

/**
 * Implements hook_entity_view().
 *
 * Provides additional argument to allow the display to be forced, to work
 * around problems elsewhere in the APIs.
 */
function MYMODULE_entity_view($entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
  // Only run this function once per page load.
  static $i_will_say_this_only_once = FALSE;

  // Only proceed if this entity object is the page being viewed.
  if ($entity_type == 'taxonomy_term' && $view_mode == 'full') {
    // Some API calls need to force the data loading.
    if (!$force) {
      // Only run this function once per page load.
      if ($i_will_say_this_only_once) {
        return;
      }
      $i_will_say_this_only_once = TRUE;
    }

    // CTools uses 'page_manager' view mode to indicate the full entity display
    // page rather than 'full', so streamline the internal processes.
    if ($view_mode == 'page_manager') {
      $view_mode = 'full';
    }

    // Generate metatags output.
    if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
      list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
      $instance = "{$entity_type}:{$bundle}";
      // We need to register the term's metatags, so we can later fetch them.
      // @see metatag_page_build().
      metatag_page_set_metatags($instance, $output);
    }
  }
}


set a entity reference field programmatically

In case entityreference prepopulate is not a viable option, I always use an EntityMetadataWrapper to set field values.

function mymodule_node_ref_presave($node_ref) {
    global $user;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node_ref');
    $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
    $result = $query->execute();
    // A more efficient way to grab entity ids from a EFQ
    if($result['node_ref']){
      $ref_ids = array_keys($result['node_ref']);
    }
    if ($ref_ids){
      // Load the entity w/ metadata wrapper to set field more transparently
      $node_ref_wrapper = entity_metadata_wrapper('node', $node_ref);
      $node_ref_wrapper->entity_reference_field->set($ref_ids);
      // Because this operation is going to execute a save anyways,
      // we don't need to do $wrapper->save()
    }
}


Is there a reason I need to unset CSS files provided by contrib modules if I have CSS aggregation enabled?

As I understand it unsetting CSS stylesheets is to:

reduce the final size of the aggregrated css file(s)
more easily override / implement custom CSS rules

Beyond these 2 reasons, your site probably "uses" all css files defined in the modules you have activated. Unless you need the performance boost from cutting out the extra bloat of X css files, or want to hand-theme certain things completely .... I see little need to unset style sheets.

I've only unset style sheets once .... and it's probably because i'm not making use of drupals multisite capabability where i have 1 site resolving from 2 url domains: http://www.foo.com and https://secure.webhost.com/foo.com/page depending on the domain I use a hook to unset/set a CSS files that fixes image paths in CSS when i'm on a secure url.


How to fetch a field's values from a lot of nodes?

You can also use field_attach_load, I believe you can pass it just 1 field you want and a set of entity ids and you can get back all the values. The below example is taken from this blog post and I take no credit for the code:

$query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node')
   ->entityCondition('bundle', 'article')
   ->propertyCondition('status', 1)
   ->fieldCondition('field_image', 'fid', 'NULL', '!=');
 $results = $query->execute();
 $articles = $results['node'];
 $fields = field_info_instances('node', 'article');
 $field_id = $fields['field_image']['field_id'];
 field_attach_load('node', $articles, FIELD_LOAD_CURRENT, array('field_id' => $field_id));


#attached can be used as follows.

$form['#attached']['js'][] = array(
  'data' => array(
    'xx_system' => array(
        'xx_code' => variable_get('xx_code', 'xx'),
        'xx_key' => variable_get('xx_key', 'xx'),
      ),
    ),
  'type' => 'setting',
);

With drupal_add_js(), you can use the following code.

 drupal_add_js(array('orgs' => $orgs), array('type' => 'setting'));
 drupal_add_js(drupal_get_path('module', 'module_name') . '/module_name.js');

In a JavaScript file, you can get the value of the variables as follows.

  Drupal.behaviors.module_name = {
    attach: function (context, settings) {
      var cities = Drupal.settings.orgs.cities;// you will get the cities value here
    }
  };


hook_block_view For an Array of Paragraphs

There isn't a 'preferred' way, or built in function, to render an array of paragraphs. You could do it like this:

$build = array(
  'p1' => array(
    '#markup' => 'Something',
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'p2' => array(
    '#markup' => 'Something else',
    '#prefix' => '
',
    '#suffix' => '
',
  ),
);

Or this:

$build = array(
  'p1' => array(
    '#markup' => '
Something
',
  ),
  'p2' => array(
    '#markup' => '
Something else
',
  ),
);

Or you could build a theme function which takes an array of paragraphs and builds up an HTML string. Or you could use some variation of implode(), or a simple loop, and so on.

It really depends on how you want to approach it, there are several equally valid ways to solve that problem.


How to code a views filter to exclude parents that have children

The following is designed for Projects and Tasks, but would probably work for any Entity Relationship with optional children of a parent.

To create a view that lists all parent nodes (in this case Project content type) whether they have children (in this case Tasks) or not use the following methodology.

The output will be all Projects with Tasks listed below them if they have Tasks.

Create a View for Projects. The Format chosen was Table, but other options would probably work.

Table Settings should include Grouping field Nr. 1 set to Content: Title. Check all the boxes Hide Empty Column for each field.

In the Fields section of the View do not list fields that are in the Project data type. Use only those in the Task data type. The Project title will automatically be retrieved because of the relationship in the Task data type that points to the owning Project. Filter Criteria should be set to Content Type = Project.

Click Advanced on the View page then click Add (next to RELATIONSHIPS). Click the drop down box and select Entity Reference. Select "A bridge to the Content entity that is referencing Content via pmtask_parent". Type Tasks into the Identifier blank. This establishes a BACKWARD reference to Projects. Require this relationship should NOT be checked because there are Projects without Tasks. You must read the Entity References very carefully. Some are very similar to each other.

There appears to be no way to find a list of all Entity References in Drupal except to add an existing field to a content type (Manage Fields) and to click the drop-down arrow next to it to select a field. Entity References are preceded by the term Entity Reference.

From the database perspective, the pmtask_parent Entity Reference is an index (or pointer) to the parent database record. In this case, the Project. Traditionally relational databases would create separate tables for Tasks and Project, but Drupal does things differently with both stored in the node table. The field_data_pmtask_parent table serves as the linkage between the two node types.

Above from https://www.drupal.org/node/2533748.


Question regarding SearchAPI and Index performance/scaling

Regarding Search, I would suggest to go with external Search System, like ApacheSolr, Elastic Search, Algolia, etc. This will make sure that database will not be overloaded with content index.

I'm working on a project where we currently have almost 2 Lac nodes and around 30-500 nodes created every day. The number of concurrent users are 1-20 max. We're using ApacheSolr (Solr hosted on different server) with Search API and Search API Solr Module and results are retrieved in less than 1-2 Seconds (The Project is internal of Client's Company so can't share the link here).

  I was thinking of just using straight views, and trying to do search
  filters, but it's not scalable and after a few months to a year it
  would be quickly unmanageable.

Using view for rendering search results will not help much in terms of instant results. Preferred way will be writing custom code to query based on keyword and show results based on requirement.

  Alternatively, thinking out loud, could I have it submit the new node
  to the index on every new node addition?

Indexing of Node after Creation/Updates are managed by module. The search indexing is normally done when running Cron. So setting up your site Cron to run every minute will make sure that the nodes are indexed instantly.

Hope this helps.


You override markup by using :

  function template_preprocess_field(&$vars){
    if($vars['element']['#field_name'] == 'field_event_geofield')
     {
          //kpr($vars); //Uncomment to output the $vars array.

           if(isset($vars['element']['#items']['0']['lat']) && isset($vars['element']['#items']['0']['lon'])) { $vars['items']['0']['#markup'] = 'View Map'; } return; }
           }


Remove XMLRPC to avoid vulnerability exploit

is it safe to remove xmlrpc.php file?

Yes, if you're not expecting anyone to use it.

  Is it bad practice? If so, why?

Could be construed as such; any change to core creates an additional step when updating (I'm sure we're all aware of the dangers of 'hacking core' by now, but if not: Never Hack Core).

  Is there any way to neutralize this security risk without removing this file?

Update your core to 7.31, where the vulnerability has been fixed.


How do I add a region to the Color module?

You need to also provide a color for the field you added. In fact, the function that adds the form elements for the color settings contains the following code. (See color_scheme_form().)

 foreach ($palette as $name => $value) {
    if (isset($names[$name])) {
      $form['palette'][$name] = array(
        '#type' => 'textfield',
        '#title' => $names[$name],
        '#value_callback' => 'color_palette_color_value',
        '#default_value' => $value,
        '#size' => 8,
        '#attributes' => array('dir' => LanguageInterface::DIRECTION_LTR),
      );
    }
  }

Without a color value for your field, $form['palette'][$name] will not be added, and it will not be possible to change the color for it.

In fact, the Bartik theme uses the following values, for its default palette.

$info['schemes']['default'] = array(
  'title' => t('Blue Lagoon (default)'),
  'colors' => array(
    'top' => '#055a8e',
    'bottom' => '#1d84c3',
    'bg' => '#ffffff',
    'sidebar' => '#f6f6f2',
    'sidebarborders' => '#f9f9f9',
    'footer' => '#292929',
    'titleslogan' => '#fffeff',
    'text' => '#3b3b3b',
    'link' => '#0071B3',
  ),
);

The keys you find in (for example) $info['schemes']['default']['colors'] are the same keys you find in $info['fields'].


Commerce (and Commerce Kickstart) rendering add-to-cart buttons on any page?

Solved: Experimenting I added a product variation field to the Slideshow content type. This essentially creates a new line item type but that's okay. I can now render the field in the view and it adds to the cart like it's supposed to. Just some CSS now and it will be just fine.


Views UI module gives you a nice user interface to create, and edit your views.
A "view" here means what the Views module produces; it could be a slideshow, a page with a table, a block of recent comments, etc.

You can turn that module off if you have finished making all the views, and the site is ready to go on production. Your views will work no matter you have the Views UI module enabled, or not.


Menu link on hover is showing & instead of &

Try to turn off Provide a menu link in Menu settings of your webform and to add menu link to webform page in your menu, /admin/structure/menu > list links (of your menu) > Add link instead.

If this doesn't work you can override themable output in your theme template.php file or in a custom module. Look at this post.


How to modify the fields of user registration form and user login form?

Use hook_form_alter() or hook_form_FORM_ID_alter to update anything in the forms:
Example of updating the user login form using hook_form_alter():

function My_Module_form_alter(&$form, &$form_state, $form_id) {
  // Modify the user login form. ('replace the "-" with "_" in form id')
  if ($form_id === 'user_login_block') {
    // Modifying the label and the size of input of username and password.
    $form['name']['#title'] = 'User Name';
    $form['name']['#size'] = '20';
    $form['pass']['#title'] = 'Password';
    $form['pass']['#size'] = '20';

    // Adding extra class to the form.
    $form['#attributes']['class'][] = 'custom-class-name';

    // Adding additional validator to the form for some custom validations.
    $form['#validate'][] = 'My_Module_custom_form_validation';
  }
}


Using symlinks / multisite to display one drupal site at two domains

I don't think it's going to cause any problems, but it seems you just make things complicated for no reason. So, that would be a reason not do it that way :)

Just point both domaines to ~/sweet-bro/html and get rid of the symlink in /sites/.

Both domains will be showing the same site, as long as you don't use a .htaccess rule to redirect to one or the other.


Why doesn't hook_preprocess_node() get triggered?

The problem is with dpm(). This uses drupal_set_message(), which uses the session variable to store messages:

function dpm($input, $name = NULL, $type = 'status') {
  if (\Drupal::currentUser()->hasPermission('access devel information')) {
    $export = kprint_r($input, TRUE, $name);
    drupal_set_message($export, $type, TRUE);
  }
  return $input;
}

When the node template is processed, the page is already built with the session variables at this point. Any messages that come later will not make it on the page. In this case better use kint(). dpm() is more usefull for debugging code that doesn't produce a page output, like form validation.


combine several exposed filters into one exposed (search) form?

Views 3 provides solution for your question from the box.
It's Global: Combine fields filter.

Add fields.
Add Global: Combine fields filter to filter criteria.
Check fields you want to combine in filter's settings.

If you use Display suite or teasers mode - force using fields in the View settings (under Format -> Settings).


URL Alias Preventing a Pattern on Vocabulary

Ok thanks to Digital Fire, I started checking for other alias conflicts, which I found in my defined views.  The problem I had initially was that the URL alias was working with views, however clicking on the link / taxonomy term took you too the default drupal view.

So in order to get the term with an alias working with view's I realised that in the view path use the original link to the taxonomy term instead of the url alias.

Hopefully that makes sense and might help someone else out.


You're looking at Drupal 7 form api reference perhaps. For drupal 6 according to the form api you just need to put your HTML string in #value as the default D6 #type is markup


How to get the view count of taxonomy term pages in Drupal 8?

I found a Drupal patch for Statistics module, which tracks view count for all content entities. It seems like this feature will be integrated into the core.

After applying the patch, I can track view counts for taxonomy term pages.

Link to the patch:
https://www.drupal.org/node/2532334


How to declare one custom module's dependency on another custom module

Try this just like contrib projects.

dependencies:
  - your_module_name


You get that error because $node is not one of the variables passed to views-view-fields.tpl.php, which receives:

$view: The view in use.
$fields: an array of $field objects.
$row: The raw result object from the query, with all data it fetched.

Basing on the description, $row could be used to retried the node object. I cannot tell you the content of that variable, but using print_r() from your template file can help to understand its content.


These modules are now in core in D7.

EDIT:

I think I now understand what you are trying to do, and it is going to be a little more difficult than simply upgrading your site to D7. If I understand correctly, you are taking a D6 module generated by Features, and trying to plug it into a D7 site. Before you can do that you MUST first upgrade the D6 module to a D7 module. You will find more information here. The Drupal API has changed for D7.

If this is only a small site, do a clean install in D7, create your content types manually, and use cut and paste to migrate your content. For larger sites, create a complete working copy on a test bed and do a site upgrade following the instructions found here.

I have done several d6 -> d7 upgrades, and it usually takes two or three tries to get it right. If you do multiple backups during the process, you can restore to a working stage and continue without having to start from scratch if the upgrade fails for whatever reason.

Good luck.


Display content by taxonomy term, including sub-terms

link- https://drupal.org/project/taxonomy_menu_block

Taxonomy Menu Block allows you to make blocks
containing unordered lists that represent the structure of
your vocabularies, creating a menu out of your
taxonomies (without using Drupal's menu system).
TMB combines the idea of Taxonomy menu with the
workings of Menu block :
Make multiple menus per vocabulary.
"Split" the taxonomy into different menus.
This allows, for example, the creation of one menu with
only the top items (parents) of a vocabulary and
another menu with only the sub-items (children).
Make a menu out of a specific branch of your
vocabulary only.
Follow the active trail, also for nodes coupled to a term
with a term reference field.


The easiest way to check the mailkey is if you look at the source code of the mail you received. The body-tag has a class with the mailkey. At least if you use the default template.


How do I share data from a hook to a service/controller?

For those who may have the same troubles as I do...

I am trying to set a message in Drupal to show on /cart the main cart page.  The data is seemingly already there but it was a bit trickier to actually pull the data into code compared to the Views module just simply inserting a field.

So I can't say I fully understand how this is working.  But my site uses a multi-store model so it's necessary to specify store ID.  Here is my code:

This isCartNotificationController.php (I changed the route behavior of /cart by setting a default _controller method in RouteSubscriber.php and copy-pasting the CartController.php class from commerce_cart/src/Controllers/CartController.php and making edits.  Now the behavior of the route at /cart is different.

$store = \Drupal::service('commerce_store.current_store')->getStore();
$cart = \Drupal::service('commerce_cart.cart_provider')->getCart('default', $store);
$price = $cart->get('total_price')->getValue()[0]['number'];
drupal_set_message($price); //shows $19.98

So it's a rough implementation but I can successfully access the cart value using this.  I'll probably make a template or something instead since a drupal_set_message is a little bland.

Lots of Google searches will bring up hooks and extending certain hooks but it doesn't seem like you can practically use those within a service/controller.

In other words, I misunderstood what a hook was doing.


How do I customize a Superfish Menu for Drupal 7?

You need to overwrite the styles in your own custom stylesheet.  Use firebug to find which styles you would like to adjust.

Keeping it in your custom stylesheet will keep the styles from being lost when you update the module.


Seamless Responsive Photo Grid with Omega

I have a kind of similar issue. I was actually trying to display different packages where the packages div's had variation in heights. I tried to align them using css without any luck.

so I then tried Isotopes and that worked perfectly.

You should also try https://drupal.org/project/isotope it comes with Example Context Reaction for Isotope.

there is also https://drupal.org/project/views_isotope module

You can also use

https://drupal.org/project/views_fluidgrid
https://drupal.org/project/masonry
https://drupal.org/project/masonry_views


File structure for custom modules in Drupal 7

Keeping your modules folder clear is important part of development. This is my common structure:

contrib — modules from Drupal.org
custom — modules developed for this project
features — exported features for Features-driven development
unstable — sandbox, forked, unstable, patched modules

Here are some examples how to organize patches/forks:

Drupal Boilerplate from Lullabot
A sustainable development workflow for patching drupal from Jennifer Lea Lampton
Drush Make workflow from @Letharion
Managing patches & getting your drupal patch accepted from Greg Knaddison

  But how to install a newly downloaded module in `sites/all/modules/contrib from admin-panel.

Use Drush please.

drush dl views rules # will download Views and Rules into sites/all/modules/contrib automatically if contrib folder exists.

You also can specify --destination where to download project.


Typically, to control the output of your field you'd just print out all your fields in your template files by doing precisely what you have up there:

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

You can have as much html in your template file in addition to these rendered fields and then style them with css!  So you can have

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

And then theme this with css using any of the ids and classes you get and whatever the fields themselves render.

If you really need to modify the field's output more precisely and the standard output from print render doesn't work for you, you could certainly look into the field structure itself and grab the individual field parts you need.  I'd only do this if you absolutely need to...

To start peering into the exact structure of the fields, I'd

Install and enable the devel module... You can just enable the 'Devel' module that comes with it for this purpose
In your template file, put a

<?php dsm($content['your_field']); ?>

statement somewhere.  That function is only available if you have the devel module enabled, and it will print out the field array for you to inspect in detail.  Here is an example of the dsm output:

Once you can look into the structure of that array, you can take any pieces of the field you need, if you don't want to render it in the default way.

So, you can do something like getting only the uri of your image...

<img src="<?php print $content['field_image'][0]['#item']['uri']; ?>" >

Anyway, hope this helps!


migration process plugin not registering

The module was in a funky state. I ran drush pm-uninstall complimentmigration which gave the following message.

  complimentmigration is already uninstalled.
  There were no extensions that could be uninstalled.

Then I ran drush en complimentmigration which gave the following message.

  The following extensions will be enabled: complimentmigration
  Do you really want to continue? (y/n): y
  Drupal\Core\Config\PreExistingConfigException: Configuration objects (migrate_plus.migration.compliment_xml_to_node) provided by                      complimenttmigration already exist in active configuration in /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/Config/PreExistingConfigException.php:65
  Stack trace:
  0 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/Config/ConfigInstaller.php(496): Drupal\Core\Config\PreExistingConfigException::create('complimenttmigrat...', Array)
  1 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/ProxyClass/Config/ConfigInstaller.php(132): Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module', 'complimentmigrat...')
  2 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/Extension/ModuleInstaller.php(150): Drupal\Core\ProxyClass\Config\ConfigInstaller->checkConfigurationToInstall('module', 'complimenttmigrat...')
  3 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(83): Drupal\Core\Extension\ModuleInstaller->install(Array, true)
  4 /Applications/DevDesktop/tools/vendor/drush/drush/commands/core/drupal/environment.inc(131): Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array, true)
  5 /Applications/DevDesktop/tools/vendor/drush/drush/commands/core/drupal/environment.inc(198): drush_module_install(Array)
  6 /Applications/DevDesktop/tools/vendor/drush/drush/commands/pm/pm.drush.inc(1180): drush_module_enable(Array)
  7 /Applications/DevDesktop/tools/vendor/drush/drush/includes/command.inc(422): drush_pm_enable('complimentmigrat...')
  8 /Applications/DevDesktop/tools/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
  9 /Applications/DevDesktop/tools/vendor/drush/drush/includes/command.inc(199): drush_command('complimentmigrat...')
  10 /Applications/DevDesktop/tools/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
  11 /Applications/DevDesktop/tools/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
  12 /Applications/DevDesktop/tools/vendor/drush/drush/drush.php(12): drush_main()
  13 {main}

I ran drush ev "\Drupal::service('config.manager')->uninstall('module', 'complimentmigration');", followed by drush en complimentmigration, which gave the following message.

  The following extensions will be enabled: complimentmigration
  Do you really want to continue? (y/n): y
  complimentmigration was enabled successfully.

This fixed the issue I had.


Views: creating a hierarchy of content - am I doing it right?

A taxonomy tree is often the first that comes to mind thinking of a hierarchical directory of content items – but similar structures can also be built in many different ways. Here's just two examples that I personally find often easier to handle, than a taxonomy tree:

Entity reference – rather than having 'lists' of content items 'attached' to taxonomy terms, to me this approach has a more 'real' feel concerning the item-to-item relations. You actually have nodes (items) that can either be partens, children or siblings of nodes (or content types) with all the advatages that come with nodes like commenting etc. And the free tagging reference field let's you even generate new elements 'remotely'.
Book module – probably one of the most underrated core modules – let's you genrate complex tree structures out of the box. While I consider it ideal for a quick start, it might become a bit low-fi in the long run.

For me reading this article "RIP Taxonomy Module in Drupal 7" was appeared to be quite helpful when I (again) had to decide how to build a tree of related nodes.


How can I get row field in hook_preprocess_views_view_unformatted(&$variables)?

You find the field handlers you have configured in the Fields list in $view->field. A field handler has methods like getValue(), render() and advancedRender(), which accept as argument the row variable:

Example:

$view = $variables['view'];
$rows = $variables['rows'];
foreach ($rows as $id => $row) {
  $field_value = $view->field['field_name']->getValue($row);
}

See also Get result view with formatter programmattically


Changing navigation depending on authentication status

Check out Menu per Role Module. This module allows you to restrict access to menu items based on user roles. Once enabled, there will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.


Object undefined in jquery, plus my links are pointing elsewhere

The Drupal JS object not being defined is a symptom of it not loading core JS files. His previous site probably enabled JS aggregation that places the aggregated file in sites/someothersite/files/XXX.js. The same goes for the missing images. Have you copied over sites/someothersite/ from the previous host?

It sounds like sites/someothersite/settings.php was what his original host was using and configured for DB & files. Since you're now viewing the site on  gator1111.hostgator.com Drupal is using sites/default/settings.php.

This primer on drupal multi-site settings might help to also explain what's going on.


Custom field validator comparing original and new values

Normally the original entity is stored in the entity object before the user input is applied. If not, you can get it via the loaded revision id, which is preserved when an entity is loaded to keep it save from changes:
if (isset($entity->original)) {
  $original = $entity->original;
}
else {
  $original = \Drupal::entityTypeManager()
    ->getStorage($entity->getEntityTypeId())
    ->loadRevision($entity->getLoadedRevisionId());
}

$value_original = $original->{$item->getFieldDefinition()->getName()}->value;


How can I grant anonymous users access to the locale language select form without hacking core?

You should be able to just replace the #access property for the element added by the locale module in your form alter:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Use exactly the same access logic as the original,
  // without checking for the 'administer users' permission
  $form['locale']['#access'] = ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register'));
}

That's essentially the same as taking the && user_access('administer users') part out of the core file.

All you need to make sure of is that your module hooks are run after those of the locale module (so the element actually exists when you try to alter it), which you can see how to do here.


Exclude users from users list in issue tracking

Since your needs are so specific, I think the easiest (and maybe most logical) way to do this is not to restrict the users on the list. Instead, hide the field for all users of a certain role and have the value default to you. And for you, just don't hide it.

You can achieve this in a few ways. It would be very simple to write a custom module to do this. Use hook_form_alter() to access your issue form. In that function, use the global $user object to check the role of the current user, and  if it's your clients' role, set the '#access' property to FALSE and the '#value' to your user id. That's all.

You can probably do this without custom code also. Every field already has a default value in Drupal core. Set the default value for that field to you. Then use a module like Field Permissions to hide the field from your clients.

This achieves what you want without actually messing with the user reference list. That is also an option, but seems like a worse option to me. To do that, you would need a custom hook_form_alter() that, depending on the current user's role, would loop through the #options for that field and remove any users that aren't you.


During database updates the schema of any module could be out of date

No, that is not correct. You cannot use a string as update version for a update hook, or Drupal will not recognize it as update hook.
For the other functions that aren't hook, Drupal doesn't check their name follow a schema, since Drupal is not going to call them. The only non-hook functions Drupal calls are those functions referred in some data structure returned to Drupal, or those functions whose names match a form ID followed by _validate or _submit, which could be used as form validation or submission handlers.

See the code executed from drupal_get_schema_versions(), in particular the following one.

// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

A function name like mymodule_update_toto() would not match /_\d+$/, so it would be discarded immediately; a function name like mymodule_test_001() would not match /^(?P<module>.+)_update_(?P<version>\d+)$/, so it would be discarded on the second round.
The same is true for a function name like _update_N_mymodule_my_function(): Since it doesn't end with a number, it would be discarded at the first round. _update_mymodule_my_function_N() would be discarded on the second round, since _update_ is no after the module name (so it doesn't match /^(?P<module>.+)_update_(?P<version>\d+)$/).


How do I secure pages and related media files?

Try to use Secure Site for this.

  This module allows you to authenticate users with a browser-based password (HTTP Auth). You can restrict access to the site by role and choose to secure restricted pages or the entire site. This means the site will be inaccessible to search engines and other crawlers, but you can still allow access to certain users.


Can Drupal's search index external tables?

Yes, you can use the search api to specify your additional content. In particular you will need

hook_search_info
hook_update_index
hook_search_execute


Drupal does all the work.

I made a call to file_validate_size() in my hook_file_validate() handler.  I also made an admin form to modify each role's allowable space (using variable_get/set), and it works great.

Next step is to create a table containing non-default values (keyed by uid), and an admin tool to set individual users' allowable space.  I'll then update my hook_file_validate() handler to check for the user in that table.  If not, then check the default.


How to enable WYSIWYG in a text field summary?

The WYSIWYG module's logic acts on text fields with input formats, if you want to explicitly target a form element by its ID you can use the CKEditor module instead.


Drupal 6 does not like it when an image tag's absolute path contains “http:”

the issue i reported was caused by a mod_security setting.
my host fixed it after i spoke to them.


How to show/hide fields with the Rules module based on the user's language?

The Conditional Fields module might be of help to you.


How can I show all registered users per event in Calendar?

I figured this out by creating a seperate view for registrants and then with the module Views field View I could show that view inside the Calendar view


How can I store the user agent string and referrer for Webform 4.x submissions?

This issue is Closed (won't fix) on Drupal.org

If you want them back, you basically need to create a module that implements hook_tokens() and hook_token_info(), as described in the API. I don't think anyone did it already.

Here is how I'd do it:

function yourmodule_token_info() {
  $type = array(
    'name' => t('Server'),
    'description' => t('Tokens related to $_SERVER superglobal.'),
  );
  $tokens = array();
  foreach($_SERVER as $key => $val) { //discard $val now
    $tokens[$key] = array(
      'name' => $key,
      'description' => "\$_SERVER['$key']",
    );
  }
  return array(
    'types' => array('server' => $type),
    'tokens' => array('server' => $tokens),
  );
}

function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'server') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
        $replacements[$original] = (string)$_SERVER[$name];
    }
    return $replacements;
  }
}

Of course code above is not production ready, it ignores proper type handling, security issues and so on. It's meant to set you on the right track, but you need to apply your own sanity before deploying it. I take no responsibility for abuse. Read about the reasons it was removed in the first place before you decide to add it back, and be careful to restore only what you really need.


How to check programatically whether a comment is new?

Use hook_comment_insert() instead, that should work.


Custom exposed filter for year in date field with ajax

You can use this custom filter to filter by year:
https://github.com/DarkteK/d8-views-custom-filter/tree/master/d8_filters
Just change the years you want to use in the file 'ViewsYearsFilter.php'
This will work with Ajax


The solution proposed by Jaypan works well.
The solution was to not put the modifications of my field in the callback but in the form definition and set the value here by checking the $form_state fields.


Change decimal separator to comma using commerce-order:commerce-order-total:amount_decimal

You can achieve it with hook_commerce_currency_info_alter(). Please do refer the discussion in this thread, you will get an idea.
Comma as decimal point


Drupal function field_get_items vs user_load

No, You can't use field_get_items without the loaded user object. As the entity has to be passed as the second argument as illustrated in documentation.

Any reason why you hate user_load_multiple? As user_load itself uses user_load_multiple.

If you don't want to retrieve that huge amount of arrays. You can consider building your own query to retrieve just the field you want.


Prevent trigger of other hook_preprocess_HOOK()

You can disable hooks via hook_module_implements_alter().

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_page') {
    unset($implementations['module_foo']);
    unset($implementations['module_bar']);
  }
}


Sorting orders by name rather than by order number

Assuming you are using views to build your table, take a look at the table settings. In there you can set default sort, and there is a checkbox to make columns sortable.


How to put Inline Entity Form in another form (without widget)?

i would do it via ajax submit handler. yes you will recieve the full node but you can just take the necessary values and save it directly yourself.

see this post for how to do ajax in forms: ajax_example_add_more - Drupal 8


If you want to be professional, use  Menu clone module all right. Simply do it on development copy of client's site.

It's never a good idea to use beta modules on production site without testing them on devel and stage, but if you do test and they work for your particular site, it's usually safe*. And if all you need are cloned menus, you can use it and then uninstall before stage -> production migration so it will never even appear on your production server.

* As safe as your tests were good.


You can try Linkit. This will allow you to select internal links inside CKEditor and will convert them to aliases.

  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.


How to import multi-value fields into profile2 using the Migrate module

Make sure you're mapping the field using the right separator, e.g.

$this->addFieldMapping('field_interests', 'interests')
     ->separator(',');

Then make sure you've the right length in the source field ($this->map) and your Drupal field support such lengths as well.

If this does not help, increase the length of the destination field by SQL, drush or hook_update.


Overriding css file in theme.info not working as expected

Try disable/enable theme. Yes it likes a trick. It seems info files are parsed when modules/themes are enabled/disabled.


I'm not sure I understand you correctly but let me clarify:
A.If you have a new content type that users can vote for that. You just use the votingapi http://drupal.org/project/votingapi and use with Fivestar module http://drupal.org/project/fivestar or plus1 module http://drupal.org/project/plus1. You will go to plus1 or fivestar for setting the content type that be voted.
B.To determine the total of the votes of your content type you should do following:

Create a new view and choose the type of your content, remove sort options, fields and other default settings.
Add a field for "Content: Type" Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
Create the relationships with votes table("Content: Votes")
Add another field for "Content: Votes", click "Aggregation settings" and set the aggregation type to "count"
The second "Content: Votes" should now look like " COUNT(Votes: Value)"  and now you can see your content type and the total votes of that.

C. In order to anonymous users can edit your content type just go to permissions and set configuration for anonymous users.


How to add a field to a group with form_alter

Let's say that you are doing this in a module named custom.

First, take a look at how the form is structured using dsm($form) in custom.module.  Make sure you have the devel module enabled and that you have permissions to see devel's output.

<?php

custom_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

That will give you the structure of the $form array, which you can then add your markup to.  So, let's say that you want to add some markup to the author pane in the vertical tabs.  From the output from dsm($form), we see that we are working with $form['author'].

So, in custom_form_alter(), we simply add the markup element we desire using the standards documented in the Drupal 7 Form API.

In the code below, I also give the custom element (which I have aptly named "custom") a weight, so it appears above the other elements.

/**
 * Implements hook_form_alter().
 */
function custom_form_alter(&$form, $form_state, $form_id) {
  // Add custom markup to the "Authoring Information" tab when adding or editing a page.
  if ($form_id == 'page_node_form') {
    $form['author']['custom']['#markup'] = 'Text goes here';
    $form['author']['custom']['#weight'] = -9;
  }
}

Also, rather than using an if statement to target the form id, I could have used hook_form_FORM_ID_alter(), like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_form_page_node_form_alter(&$form, $form_state, $form_id) {
  // Add custom markup to the "Authoring Information" tab when adding or editing a page.
  $form['author']['custom']['#markup'] = 'Text goes here';
  $form['author']['custom']['#weight'] = -9;
}


From reading the module description, I get the impression that the Match redirect module module only replaces wildcards and cannot remove them.

I suggest you try redirect module with pathauto. After you change the path in pathauto, remember to use the BULK UPDATE tab to update the urls. Redirect will automatically do it's thing.


I found a solution to resolve my problem.
After having readed several posts, i have decided to create a custom Ajax Command to open my files (pdf/csv).

Create a custom command - link

In my custom module, I have built the required files for this and call in my CallBack function this new ajax command ('OpenFileCommand') :

    $ajax_response = new AjaxResponse();
    $command = new OpenFileCommand($file_url);
    $ajax_response->addCommand($command);

Here is the simple code for this command:

use Drupal\Core\Ajax\CommandInterface;

/**
 * Class OpenFileCommand.
 */
class OpenFileCommand implements CommandInterface {

  // Create a new property.
  protected $file_url;

  // Construct the File Url property.
  public function __construct($file_url) {
    $this->file_url = $file_url;
  }

  /**
  * Render custom ajax command.
  *
  * @return ajax command function
  */
  public function render() {
    return [
      'command' => 'OpenFileCommand',
      'file_url' => $this->file_url
    ];
  }

}

Now, I can open a file when I click on a ajax button.

Thanks for all for your help. This solution can help someone...


Building a username search by writing custom module

A form submission handler doesn't use echo to output its result. You need to use a render array to render the result, such as with the following code. I assume usersearch_form() is the form builder function.

function usersearch_form($form, &$form_state) {
  // Add the form elements.

  if (!empty($form_state['username'])) {
    $form['username'] = array(
      '#markup' => t('The username is %username', array('%username' => $form_state['username']))
    );
  }

  return $form;
}

function usersearch_form_submit($form, &$form_state) {
  $username = db_query('SELECT name FROM users WHERE uid = :uid', array(':uid' => $form_state['values']['uid']))->fetchField();

  $form_state['username'] = $username;
  $form_state['rebuild'] =  TRUE;
}


How to create a simple list of links to Drupal panel pages?

You could create a View of miscellaneous page links, if the list of links was actually a list of a series of nodes with a particular taxonomy term applied to them.

For example:

Create a taxonomy vocabulary called "Page Links", and create a new taxonomy term for it called "Custom Menu One". Then, tag each of the pages which you want included in your list of links, with this Custom Menu term.

Now, you can go into the Views UI, and create a block View which outputs all nodes which have the taxonomy term "Custom Menu" applied to them. You can set up the view to use fields, and output the title of each node as a link back to the original content.

You'll also be able to configure the display settings for the View so that the links are output as a List, or Table, or unformatted, etc.


Override title with field label instead of key inside a views contextual filter

edit your Contextual Filter check Specify validation criteria in Validator check PHP code and enter following:

if ($argument == 'youth_competitive_program') {
  $handler->options['title'] = 'Youth Competitive Program';
  return true;
} else if ($argument == 'primary_competitive_programe') {
  $handler->options['title'] = 'Primary Competitive Program';
  return true;
}
return false;

there is another similar way:

if (!empty($argument)) {
  $handler->options['title'] = t($argument);
  return true;
}

return false;

and translate them, so if you add more option to your user_program fields, this code will work better.

but there is another option yet:

$field = field_info_field('field_user_program');
if (array_key_exists($argument, $field['settings']['allowed_values'])) {
  $handler->options['title'] = $field['settings']['allowed_values'][$argument];
  return true;
}
return false;

I will select the last way


Can I allow users to choose what input widget a Drupal field should use on a node by node basis?

In your content type definition, create two different fields, eg: data_tab and data_text. Then have a third field where the user can indicate their format, and use the Conditional Fields module to display the correct data input field.


Unable to override Superfish styles in Zen theme

It was just a matter of selection the Aggregate and compress CSS files option under Bandwidth optimization


Allow only the users with the access code to browse the website

create a page, and include the User Login as a block on that page. Theme as desired. You can also set this as a Front page in the system settings if you like.
alternatively, create a customised user login, whereby the password is populated as part of a custom submit function of the form. Then you would use a Code as the user name, and the password would be automatically assigned. The question is too broad to detail how this would be accomplished. Look into the forms API and building forms with customised submit functionality.
get LoginToboggan. It has a setting to redirect users to a specified page on access denied
in permission, for Anonymous Role, uncheck ALL items. This will essentially disallow anonymous user to do anything, or view any content, which should then be redirected to the login page by logintoboggan

Keep in mind that this method is prone to major security breaches by bots. They WILL randomly guess the code and gain access to the site, which is why two fields are required in standard practice (email/user, password)

EDIT FOR OP

I solved it by a custom module. I cant answer my own question due do low reputation so accepting yours as an answer and writing a comment. I created a block, which contains a custom form. This form redirects to home page if the access code is correct and also sets TRUE on $_SESSION['access_code']. And then I created a page and embedded the block In a custom Rule, I redirect user to the access page if $_SESSION['access_code'] is not TRUE and if the user is anonymous whatever the URL it is. So user always redirected to that page, unless they have entered the code before, or a logged in user.


Using drupal_form_submit for pass-through to external login on click

Is there any way to have drupal_form_submit honor redirects from outside the site?

Not really - drupal_form_submit() is invoked as a result of Drupal receiving a form POST  on the relevant action URL - it doesn't care about how it's been invoked, and doesn't care about the URL itself (the form's already been submitted, so the action is obsolete by that point anyway).

If you need to POST form data to an external site, but have the processing done by Drupal, your only option is to use cURL or similar.


No release history available stops dependent modules download

As per @jonhattan comment:

You need to specify projects to download in your makefile as block is not a project, but a module part of Drupal core. Same for comment or node. Simply remove them from the makefile.


Forcing together line items of the same unit type in Rooms and Commerce

When editing the field display formatter for the product reference, there is an option you can select to combine like products in the cart:

If that's selected, then you can dig a bit deeper by looking at commerce_cart_product_add(). The logic to reckon a combination starts about a third of the function down. The biggest thing here is the comparison properties. Commerce uses at least two fields initially to determine if a product is a "like product": type and commerce_product. Then, it will add any fields that are exposed to the add to cart form, and finally you can then view or alter these fields by using hook_commerce_cart_product_comparison_properties_alter().

Effectively, it won't allow any products to be combined that do not sure the same SKU or unique properties that identify it.


When to use different vocabularies vs. one big hierarchical vocabulary with parent terms

In the general term you should think on your requisites for these three things, and the pros/cons of the options provided by Drupal core/contrib to accomplish them:

How to create and maintain the hierarchy of terms
How to pick terms from the hierarchy when creating/editing products
How to filter products with a criteria based on this hierarchy (views or programatically filtering)

The way you decide to go for the 1st point (one hierarchical vobcabulary or two related vocabularies) determines the options available to solve the other two points.

When using one hierarchical vocabulary, the most important thing IMO is to preserve the lineage: when classifying a product as strawberry, also classify it as a fruit. This is very helpful to cleanly address the 3rd point without frustration, neither with inelegant approaches.
Drupal core doesn't provide a way to preserve the lineage when creating entities. There're several modules out there that ensures it. The most powerful, Hierarchical Select.

Also, editing the hierarchy of terms via the core interface is a bad UX when you go above a few dozens of terms. To improve this there're modules like Taxonomy Manager.

Lastly, eventually you may face scale problems if the vocabulary is huge.

OTOH, using two vocabularies brings other pros/cons.

On the pros side:

Configuring different fields in each of the vocabularies. For example, in the first level vocabulary (usually called family) a boolean field indicating whether the product is perishable, and a image field in the second level vocabulary for a photo of the variation.
Preserving the lineage is not an issue, since you are selecting values in two different field/widgets that you enforce to be required.

On the cons:

You're on your own with two independent vocabularies/fields that needs to be dependant somehow. You may want to create entity reference fields from parent to child, or the other side. You also need a dependant selector widget, eventually you want this widget to work also in views exposed filters,...

The Reference field option limit is great for this setup. It is a bit hard to get how it works, and it has some issues (specially I remember problems with i18n) but it does it pretty nice.

In conclusion:

None of both approaches works 100% out of the box
In the one-vocab approach you want to solve the lineage problem
Two vocabularies is more versatile
Two vocabularies is harder to setup


Build menu based in Vocabulary (Taxonomy)?

Try to use the development snapshot for Drupal 7. The update is available in that version.


How can we configure the Master slave concept in Drupal 7?

Yes, Drupal supports master/slave style database replication.
Note: master/slave replication configuration is done at the database server level. Drupal simply utilizes the replicated databases by using the slave server when one database isn't available, or for specific 'slave' marked queries ( see db_query "target" option ).
See the fully commented default.settings.php for Drupal configuration details.

For each database, you may optionally specify multiple "target"
databases. A target database allows Drupal to try to send certain
queries to a different database if it can but fall back to the default
connection if not. That is useful for master/slave replication, as
Drupal may try to connect to a slave server when appropriate and if
one is not available will simply fall back to the single master
server.
The general format for the $databases array is as follows:

$databases['default']['default'] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['extra']['default'] = $info_array;


Loading more content in mobile (Slider) - Views core module

Maybe can you detect with jQuery that the user's screen is near the bottom of the page (or with your 1st approach), then you use an .click() on your invisible "load more" button ? In that way, user will scroll and more content will appear each time ?


In short : Use the Location Distance field in Views.

In detail : Check out the video http://www.youtube.com/watch?v=AxeskzN8BAc


Why is my Language Switcher Dropdown block NOT displayed in my site?

make sure that:

add few languages to site here - admin/config/regional/language
enable one of Detection Methods here - admin/config/regional/language/configure
clear cache


How to combine two filters in search api views?

I used an aggregated field of search api. And combined the Content: content type and Media: bundle fields.
And used that field in the search api views filter.
But the filter was a text field. So to display it as links, I have created a  custom views filter for that aggregated field.


Prevent Entityform Duplicate Submissions

You can try the Hide Submit moddule:

  Some users accidentally click the submit button more than once while
  waiting for their post to be saved. In some cases this may result
  duplicate postings or duplicate e-commerce orders.

  There are few ideas on how to solve duplicate postings but none is
  perfect. One of the solutions is a bit of jQuery to hide or disable
  the submit button after it has been clicked and replace it with an
  informative text such as "Processing..." .

  This module wraps that jQuery code and provides some options. Of
  course this, too, is not a perfect solution as it requires Javascript
  to be enabled. For browsers with Javascript disabled this module will
  have no effect at all.


You seem to be using a version of feeds that is fairly recent (perhaps version 7.x-2.0-beta2). Having said that, the process function of the FeedsProcessor class is fairly inflexible when it comes to modifying the list of imported nodes that it wants to clean out of Drupal, in that it does not provide a hook to modify that list.

Having said that, your best bet is probably to extend the FeedsNodeProcessor class and only override the initEntitiesToBeRemoved function to then exclude "potentially unpublished" node ids from $state->removeList. You'll need to determine how all of the nodes from $state->removeList were created.

How you determine a manually created node from a feeds imported node is up to you but I would recommend querying the feeds_item table. If a node's nid is not found in that table then it's safe to assume that the node was manually created.


How can I add a playlist to content type?

The aptly named AudioField module has the functionality you're describing

  Audio Field module adds new field that allows you to upload and play audio files in HTML5 audio player or one of selected Flash players. Currently it supports 6 different Flash players

It definitely works, I've used it, and it has support for both of the formats you mentioned. Follow the installation instructions and you shouldn't have any problems.

Just to nitpick, and perhaps clear up some confusion: Drupal cannot play audio files, no - your browser can, when it is given the right HTML (or when flash is used). But Drupal just generates the HTML, it doesn't have anything to do with the audio files themselves (beyond facilitating upload/storage) or how the browser interprets them.


Programmatically delete field collection items

Copied from (and then tested):

https://www.drupal.org/node/2757827#comment-11398243

$user = User::load($user_id);
$storage = \Drupal::entityTypeManager()->getStorage('field_collection_item');
$fc_items = [];

foreach ($user->get('field_hobbies') as $item) {
    $fc_items[] = $item->value;
}

if (!empty($fc_items)) {
    $items = $storage->loadMultiple($fc_items);
    $storage->delete(items);
    $user->set('field_hobbies', array());
}

$user->save();


Drupal 7 views contextual filter (taxonomy: summary display), displaying a readable term-name instead of term-id

Set your view to fields and expose the field that contains the associated taxonomy term.
Set your contextual filter to filter for a taxonomy term and select to include a validator.
Set the validator to taxonomy term and check the box for your vocabulary.
Select the option for filter value type as ' Term name converted to Term ID.
Save the filter and go to the preview box.  If you enter the text name of your term, you should see the desired content.

If you are passing the information from the URl you may have to select the 'Transform dashes in URL to spaces in term name filter values' checkbox as well since the machine name uses dashes


How to handle Dev and Production servers having different file structure

If you are using Drush you can run the following commands to fix the module path problem, if you are using multisites then make sure you are in the sites/mysite.com directory (this must not be a symlink) before running these commands.

Drupal 6

drush eval "module_rebuild_cache();"
drush cc all

Drupal 7

drush eval "system_rebuild_module_data();"
drush cc all

(though as I've not tested I'm not sure this is needed on Drupal 7 anymore)

If Drush is new to you then here is the description from the Drush project page:

  Drush is a command line shell and
  scripting interface for Drupal, a
  veritable Swiss Army knife designed to
  make life easier for those of us who
  spend some of our working hours
  hacking away at the command prompt.


Is it dangerous to call a function that deletes nodes based on criteria while a cron job is running that imports them

Depends on the way you import:

If you delete the nodes on some criteria and import the nodes as new nodes ($node->is_new = TRUE), this shouldn't be a problem.
If you are updating the existing nodes while importing and deleting the nodes at the same time, then there could be issues.

This is because the node_save() function internally calls drupal_write_record, which creates a node with an incremental nid value if the $node->is_new is set to TRUE. Or updates the exiting nodes if you are importing.


In hook_form_alter() add a submit function:

$form['#submit'][] = 'my_module_menu_edit_submit';

Where you store the field:

function my_module_menu_edit_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $config->set('main_content', $form_state->getValue('field_menu_content'))
    ->save();
}

The main menu is hard coded in the settings name. If you want this to work for all menus, you can try to get the menu name from the form. I did not investigate where you can get it.

When you build the form field you also need to get the field value from config. More information: https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api


Add values to a list (text) field that stores already content

Yes, that message is very unfortunate. Ignore it.

Adding options is perfectly fine. Removing unused options is fine too. If you try to remove options that are still used, it will prevent you from doing so.


How to give pagination for Rest Service data

$row = pager_array_splice($options, 10);

$form['pagerTop'] = array('#theme' => 'pager');
  $form['entities'] = array(
  '#options' => $row,
  );

please assign $row value in the theme table


Line breaks in site name but not in title tag

Here is what I just found: There is no tags in the title, it's just a string. So the fix is quite simple.

in the html.tpl.php replace:

<title><?php print $head_title ?></title>

With this:

<title><?php
$break_tag = array("&lt;br /&gt;");
$simple_space = array(" ");
$new_head_title = str_replace($break_tag, $simple_space, $head_title);
print $new_head_title;
?></title>

Hope it helps.


Sorry I checked your code again and found the answer , change your code to this :

function omega_starter_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user_login_form') { //form ID was changed
    //dpm($form);
    $form['actions']['submit']['#value'] = t("Custom login button!");
  }
}


Drupal UserLoginForm vs UserAuthenticationController login function - which to override?

UserAuthenticationController is a service that can be used by e.g. apps and decoupled websites.

Either one or the other is used, not both.

But both use the user.auth service, which receives username and password and returns a user ID in case of a match.

So if you want to override a single place to do that, that's what you want to do. Implement a service provider in your module and switch out the class of that service definition.


Re-usable template code should ideally be in its own template, backed by its own theme function:

function THEME_theme() {
  return [
    'foo_partial' => [
      'variables' => ['node' => NULL],
    ],
  ];
}

foo-partial.tpl.php:

      Created by <?php print $node->name; ?> on <?php print format_date($node->created, $type = 'medium'); ?>.

      Last revised by <?php print (user_load($node->revision_uid)->name); ?> on <?php print format_date($node->changed, $type = 'medium'); ?>.

There are a number of different permutations you could use to actually get that HTML into the node template, here's one of them:

function THEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'page' && $vars['display_submitted']) {
    $vars['submitted_html'] = [
      '#theme' => 'foo_partial',
      '#node' => $vars['node'],
    ];
  }
}

node.tpl.php

...
<?php
if ($display_submitted && $submitted_html):
  echo render($submitted_html);
endif;
?>
...


Stop overriding for the development snapshot module

Instead of trying to tie yourself to a specific commit, you might consider using composer patches instead:

{
  ...
  "require": {
    "cweagans/composer-patches": "^1.0",
    "drupal/abc": "~1.0-dev"
  },
  "extra": {
    "patches": {
      "drupal/abc": {
        "Fix for foo": "https://url/to/foo-patch",
        "Fix for bar": "https://url/to/bar-patch"
      }
    }
  }
  ...
}

Patches will be applied on install/update of the relevant packages.


How do I render this code in block/node page?

You cannot use that code in a node or in a block, since in both the cases the $page variable is not available. It seems that code is taken from an implementation of hook_page_alter() or adapted from code used by an implementation of hook_page_alter(). In fact:

hook_page_alter() receives $page as argument
The documentation for hook_page_alter() shows that, for a node page, $page['content']['system_main']['nodes'][$nid]['body'] is the content of a node body

If rc_core_item_avail_form is a node field, in a block you could use code similar to the following one.

// Load the currently shown node.
$node = menu_get_object();

// Render the field.
$elements = field_view_field('node', $node, 'rc_core_item_avail_form');
print render($elements);

In the case the field could not be visible to every user, but you want to make that field visible to every user when it is shown in the block, then I would use the following code.

// Load the currently shown node.
$node = menu_get_object();

// Render the field.
$elements = field_view_field('node', $node, 'rc_core_item_avail_form');
$elements['#access'] = TRUE;
print render($elements);


How to make Drupal highlight the same menu item for 2 different nodes (URLs)

Recently I've the same needs in my site and the fastest and painless approach was doing in CSS instead create preprocess functions.

This was done in Drupal 8, but works independently of what you are using.

First make sure that you have a class or id named with your path in any place of your HTML, and then, just use it to style your link with same 'active' class. Something like this...

HTML:

Home

Products

Contact

  ...

CSS:

.main-menu .active,
.path-product-detail .main-menu a[href="/products"] {
  color: #fff;
  background-color: #c9093e;
}

Try in JSFiddle:
https://jsfiddle.net/t4vny2df/1/

Edit 1: Detailed explanation
First of all, in your html.tpl.php template make sure that the current path is printed as a class, this will be dynamically specified, all the magic is right here in this class (in Drupal 7, by default, seems the class is page-'currentPath' according docs).

Your HTML must print current path in body element.

...

Now, based in this class just use the right CSS selectors to highlight the menu item. I'm going to use the 'products' html code example.

.main-menu /*Note 1*/ .active /*Note 2*/,
.page-product-detail /*Note 3*/ .main-menu a[href="/products"] /*Note 4*/,
.page-search-product /*Note 5*/ .main-menu a[href="/products"] /*Note 4*/{
  color: #fff;
  background-color: #c9093e;
}

First, in CSS we can use a combination of selectors do get the right element and we can use 'comma' to specify another selector to the same style (a, p{color: #000} /*Element 'a' and element 'p' will be color black*/)

Note 1 - Considering your menu with a class 'main-menu'.
Note 2 - Considering that you are using a 'active' class for current path.
Note 3 - If body has a class 'page-product-detail' this selector will be considered.
Note 4 - This selector will get the menu item that you want highlight and doesn't have a 'active' class, because you are not in '/products' page.
Note 5 - If body has a class 'page-search-product' this selector will be considered.

For more pages just add another line with your 'page selector'. Any questions just leave a comment and I explain.


How to remove height and width attributes from CCK ImageField tags?

The attributes are there for browser performance reasons. Overriding them with CSS is still possible. If you want to specify the width, set the height to auto, or vice-versa.


Trying to get property of non-obJect Custom Module

This error occurs when you are getting language from a non object. To fix this check that whether the node is a object and check that 'language' exists in the $node or not.

if(is_object($node) && isset($node->language))

Then check the stuff that you are going to do.


How do I create a route with a query string?

You cannot create a route based on the query string, but you still can retrieve query string values in your code:

amu_hal.publicationsPerYear:
  path: '/publications/{year}'
  defaults:
    _controller: '\Drupal\amu_hal\Controller\AmuHalController::publicationPerYear'
    _title: 'publicationPerYear'
    year: 2016
  requirements:
    _permission: 'access content'

public function publicationPerYear($year) {
  $url = \Drupal::request()->query->get('url') ?: 'default';
}