When should I use Apache Solr instead of Drupal core search?

Learning and integrating solr could take no more than a couple days. There is ton of documentation on the API and a wealth of resources on Drupal.org.

Your use case sounds like a great candidate. Here are three good reasons I would use it on a particular site.

You have a significant amount of searches being made from the site and limited server resources, Solr will increase efficiency.
You need specific search control beyond core, core search really is just search content inside of nodes, It will ignore block, pane, etc. content. (There are other options that dont require non-php based environments).
Search is a major part of your site. It is common that users are finding content through google and other major search engines so search is not as important as it once was. However, some sites encourage or even require the user to search the content of the site. For anything like this, I would suggest solr, in addition to the other listed items, SOLR offers more control and search power (facets and related content) and less limitations.


How do I periodically import from a source?

For periodic import of feed, you have to configure cron.

Let say you want to import feed in every 1 hour then configure cron to run after every 1 hour too.

In Drupal 7 you can enable cron via the Administration > Configuration > System > Cron (admin/config/system/cron).

For more information cron setup visit here


How to create Drupal Articles Thumbnails and display it on homepage

You can use Views module to achieve above...

For more details visit documentation page of views module.


Checkout the "Content Access" module:
https://www.drupal.org/project/content_access

Once your client wants to "Lock down" the webform, she can do so within the Role Based and Per Content Node access control settings.

Hope this helps.
-Wrench


How to programmatically list member entities of an Organic Group?

Using directly the Organic Groups API:

og_get_group_members_properties($yourGroupNode, array(), 'members', 'node');

gives you an array of user ids.

To obtain only active, pending or blocked users, you can put 'members__1', 'members__2' or 'members__3' in place of 'members', like in this example:

og_get_group_members_properties($yourGroupNode, array(), 'members__1', 'node');

of, if you prefer, like this one:

og_get_group_members_properties($yourGroupNode, array(), 'members__' . OG_STATE_ACTIVE, 'node');

Example of the returned value:

Array
(
    [0] => 48
    [1] => 49
    [2] => 51
)


archive_page() from archive module in drupal 6 shows all nodes not date specific

I just tested archive page in Drupal 6.26 and using Archive 6.x - 1.4 . It is working as expected.  Maybe you are  date and month in the archive_page. Please find the detailed explanation below.

The parameters of archive_page() are the following ones:

$year
Number of year.
$month
Number of month.
$day
Number of day.

So print archive_page('all', 2012, 10, 12); will return the nodes created on October 12, 2012. I just followed the below process to verify the functionality.

I installed archive module
I enabled the module
I enabled content types in "admin/settings/archive"
I created two pages using Page one, and Page two as titles

Page one's authored date is October 13, 2012
Page two's authored date is October 15, 2012

I enabled the PHP filter module
I created a block with the below code, and enabled it on the right side bar

module_load_include('inc', 'archive', 'archive.pages');
print archive_page('all', 2012, 10,  13);

It does display the following output where only "Page one" is the one authored on October 13, 2012.


Reinstall a module that has .yml file in config\install

See How to remove mymodule configurations on uninstall for a best-practice solution.

Basically, you can enforce the dependency on your module in your configuration files.  So when the module is uninstalled, it's associated configuration will be uninstalled as well.


Sounds like Node comments to me. With it you can use normal Contentypes as comments. There is already a view included in the module.


i18n language switcher don't show on default lang

There is an option under language switcher block configuration.You have to select all the language checkbox to display language switcher block in all languages.


Search API Solr Autocomplete no results when more than x Nodes indexed

RTFM - Today i finally found this: https://www.drupal.org/node/1999392#hidden-variables

  search_api_solr_autocomplete_max_occurrences
      By default, keywords that occur in more than 90% of results are ignored for
      autocomplete suggestions. This setting lets you modify that behaviour by
      providing your own ratio. Use 1 or greater to use all suggestions. Defaults to 0.9.

This makes perfect sense since 90% of my total 25 nodes is 22.5.
I just set in a custom module:

variable_set('search_api_solr_autocomplete_max_occurrences', 0);

And it works.


How do I add rate widget to certain content type?

I cannot find a clear reason for why this happened. The best answer I can give to someone with the same problem (doesn't seem to be a common problem at all) is to start over with a clean Drupal install.


How to I get rid of "Error with menu entry.... " in recent log messages?

Same problem here:

I just created a Vocabulary and set to sync with the Main Menu. When saving the Main menu doesn't show the terms of the vocabulary.

I get this error in the logs: which is fired by the line 1190 of taxonomy_menu.module

  Error with menu entry "" in menu "main-menu"

The vocabulary is set to:

  Translate. Different terms will be allowed for each language and they
  can be translated.


Modify and add of unlimited collection field

Suppose we are in a hook_node_view(), a hook_preprocess_node() or something and we have access to $node, and my collection field is 'field_collection_field':

<?php
if (!empty($node->field_collection_field)) {
  $collection_fields = field_get_items('node', $node, 'field_collection_field');

  // Extract the field collection item ids
  $ids = array();

  foreach ($collection_field as $fc_field) {
      $ids[] = $fc_field['value'];
  }

  //Get the entities
  $collections = field_collection_item_load_multiple($ids);
  // dpm($collections); Devel output the items
  //Loop over the array - if you have more than one entity
  foreach($collections as $collection) {
    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
     // DO STUFF WITH COLLECTION FIELDS VALUES
    }
   }
 }//end if


I would suggest that following best practices this should definitely not be accomplished by modifying template files. If you change your theme for example, this functionality should not be effected.

A custom module would be a better place to accomplish this using hook_user_view() http://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_view/7 and modify $account->content to drop the fields that should not be displayed.


Clean URL state is managed through the Drupal variable clean_url.

clean url disabled: clean_url is 0
clean url enabled: clean_url is 1

You can force this value by:

Using drush

drush vset clean_url 1

Using a direct SQL query

UPDATE variable SET value=1 WHERE name='clean_url';

Force a value in settings.php

$conf['clean_url'] = 1;


Setup right field type and widget for field

For the first issue you can actually add it as a key|label pair.

Where the key would be the number and the Label would be what is displayed. for example 5|buy 1 at 5

this would show "buy 1 at 5" in the dropdown but the value would be five. you want to work with numbers you might want to select List(integer) as your field type.

For the second problem you might want to take a look at the Cloud Zoom Module.

  This addon provides a small, thumbnail sized image, with an on-hover
  popup, zoomed and centred on a larger version of the image.

OR

jQZoom

  The jQZoom module is a wrapper for the jQuery plugin jQZoom. The
  module provides a javascript magnification effect for images. When a
  user mouses over an image, a larger version of the area under the
  cursor will be displayed beside the image.


To check if a cron hook is being invoked, you need to output something to an existing database, for example using one of the following functions:

watchdog() requires you enabled the Database logging module; otherwise, no entry will be added to the watchdog table, and admin/reports/dblog would not show new entries
variable_set() always set a value in a database table, but the value returned from variable_get() could be the value set in the settings.php file for the $conf array
The database API functions can be used, but you need to be use the database table exists; for example, use a database table installed by a module, even if it a module of yours

In the second case, don't use a Drupal variable (e.g. this_is_a_wrong_variable), for which the following code exists in settings.php.

$conf['this_is_a_wrong_variable'] = 'This value will be always returned from variable_get().'

If you do so, whatever you set with variable_set('this_is_a_wrong_variable', 'My hook is invoked: ' . time()) will not be returned from variable_get() which would return 'This value will be always returned from variable_get().', in the example I made.

As you discovered, every Drupal hook must have a name prefixed by the module short name. In fact, the code used by Drupal to invoke a specific hook used by all the modules is the following one.

  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

As you see the function name for the function implementating a hook is $module . '_' . $hook. For the Node module, the hook_cron() implementation would be node_cron(); for an hypothetical module_with_a_long_name module, the hook_cron() implementation would be module_with_a_long_name_cron().

Bear in mind that, if you edit the code of an enabled module to add a new hook, you need to disable and re-enable it, or Drupal will not see you added a new hook has been added to the module, since the list of hooks implemented by a module is cached. See module_implements().

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }


I believe one of the better solutions to this would involve an extension to Storage API. You can't do it out of the box since it your own server, instead of say S3, but it seems like the best fit. When I saw a demo presentation by the maintainer, he showed how one could split thumbnails storage to a low-redundancy system from base image storage, which was stored more safely.


How to render CCK image field within page.tpl.php

file_create_url to get the path of your image:

// $nid is the id of your node
$entity = entity_load('node', array($nid));
$uriImagefromNode = $entity[$nid]->field_image_test_field['und'][0]['uri'];
$urlImagefromNode = file_create_url($uriImagefromNode);
// $urlImagefromNode variable now has the path to the image

I hope this information be useful.


When using Rules to set a value on a taxonomy term reference field, I get choices like "field:0", "field:1", etc. What do these numbers mean?

It's basically letting you have access to a zero-based array for the different instances of a multiple cardinality field (as I think you've already worked out).

It seems the reason there are 4 shown is just a default; a visual cue to let you know there are more than one possible values for that field.

If you have a field with 20 values you'll still only see 0...3 in the Rules data selector, even though you can use 0...19.


Exportable options for views_plugin_display_extender

There is a working implementation of a views display extender in Authcache. The only difference I see between your code and mine is that I'm using options_definition_alter while you've implemented option_definition.


On the 404 page, look for an XML file and read it in. If it doesn't exist, display 404 message

Drupal let you specify custom 403 and 404 error pages:

admin->settings->error-reporting

Your custom error page may be PHP, so you can place any logic in it you want, including the one you suggest.

Edit: As already stated by develkar, if you do not want this indexed by Google or other search engines, you disallow it in you robots.txt.


hook_entity_presave() doesn't get the form ID, and this makes sense: An entity could be programmatically saved from a module or a Drush plugin without showing to the user a form to edit/create the entity.

Since you just want to know if the entity is being edited or created:

You don't need to know the form ID
You can use hook_entity_presave() or hook_ENTITY_TYPE_presave() with code similar to the following one

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->isNew()) {
    // The entity is being created.
  }
}

As side note, $entity->getEntityType()->id() returns 'node' as expected: You are asking to the entity object its entity type, and for nodes that is clearly 'node'.


How to add domain access to custom entity?

You can override the access handler.

You have to add the handler path in the entity anotation and create an access class extending EntityAccessControlHandler. Inside you can manage the entity access using the rules that you want.

You can copy for learning the Node access Handler:
https://api.drupal.org/api/drupal/core%21modules%21node%21src%21NodeAccessControlHandler.php/class/NodeAccessControlHandler/8.2.x


You can edit the field and then click on REWRITE RESULTS and check off the box strip HTML which will strip out all the html that is creating a line break between each tag. If you need more control you can use "Rewrite the output of this field" and wrap your field in its own element.


Restrict user access to several actions in function

In your hook_menu call you can use different access arguments, to make sure only administrators access the callback function. For example,

'access arguments' => array('administer users'), // usually Administrators have this permissions

If users with some other roles try to access the menu, they'll get the Access Denied message by default.

If you want your users to access the function and restrict only certain part, you can check the user role in that case:

if ($user_id == NULL) {
  $user_id = $user->uid;
}
else {
  if(in_array('administrator', array_values($user->roles))) {
    //apply your exit function logic here
  }
}


How do I programmatically add an image while programmatically creating nodes?

Let suppose your image fields in field_body_images ,

first load your node by node_load
and record your image in file tables and add it to your node image field
I hope this sample help you to achieve :

$n=  node_load($nid);
$file = new stdClass();
$file->filename =$file_name;
$file->filemime =file_get_mimetype($localimagepath.$file_name);
$file->filesize = @filesize(file_create_path($localimagepath.$file_name));
$file->uid = $user->uid;
$file->status = 1;
$file->timestamp = time();
$file->list=1;
$file->data=array('alt'=>'','title'=>$n->title);
drupal_write_record('files', $file);
$record->fid=$file->fid;
$n->field_body_images[]=(array)$file;
node_save($n);


Another option without the extra module overhead (still a valid option):

<title>{{ head_title|reverse|safe_join(' | ') }}</title>

Simply add the reverse filter to that part of your html.html.twig file

Twig rulez! Cheers!


Check your content type. what is default image type in manage field display. set it Original image. hope this help!


Use mytheme_preprocess_block() to display HTML (icon fonts) in block titles

In preprocess_block() function you can only define the title prefix and suffix for each title.

For example:

/**
 * Override or insert variables into the block template.
 */
function YOURTHEME_preprocess_block(&$variables) {

  $variables['title_prefix'] = array(
    '#type' => 'markup',
    '#markup' => '<i class="icon-envelope">',
  );
  $variables['title_suffix'] = array(
    '#type' => 'markup',
    '#markup' => '</i>',
  );

}


How to detect a mobile browser using PHP in content?

Mobile detection isn't built into Drupal or most popular themes (I think Adaptive Theme does, though).  You need to install a contrib module to do this.  Three options are Browscap, Mobile Tools, and Mobile Detect.  Where you go from here depends on which module you are using.


Display Suite code field – how to use another image field conditionally

It's because you have nothing in renderable format yet.

Look at function field_view_field

  Returns a renderable array for the value of a single field in an
  entity.

Then change your code like this:

<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    $renderable = field_view_field('node',$entity,'field_main_image',array('settings' => array('image_style' => 'thumbnail')));
    print drupal_render($renderable );
}
?>

Note that this is not the only way to get html from field values. You can use theme functions and load that with values you find on $entity object and print that if you wish.


8.4 - Use entity browser in a module block from in same way as I would in a custom block

No, this is not possible. Block forms in a block plugin are configuration forms and here you can only use Form API fields.

  I (think I) understand that custom block types are actually nodes
  internally and that they are subject to different rules to blocks
  which I define in my custom modules, but I don't fully grasp what the
  differences here are.

Custom blocks are not exactly nodes internally, it's very similar, custom blocks and nodes are both content entities. This doesn't change the rest of what you found out correctly. You can use entity fields and their form elements, widget and formatters only for content entities.


How do I record hook_menu() access statistics

There is no build in stat counter for this. Here is a workaround:

<?php
function mymodule_menu() {
  $items = array();
  $items['foo/bar'] = array(
    'title' => 'example',
    'page callback' => 'mymodule_foo_bar',
    'access callback' => 'mymodule_foo_bar_access_with_stat_counter',
    'access arguments' => array('Something', 'Something else'),
  );
}

function mymodule_foo_bar_access_with_stat_counter($something, $something_else) {
  //Log your stats here!
  // goddess_logs_stats_here($something, $soemthing_else);
}


URL Aliases not recognizing Node Reference Tokens?

The issue I_THINK is that tokens are only generated on content in the current node, eg, it has no inherent intelligence to walk up the hierarchy of node references to find all your other info stored in other nodes.

So, it would appear you have a node ref to the course already in your lecture, so just make sure you have the correct [TOKEN] there (TOKEN-title-raw instead of TOKEN-number-raw perhaps?) but to get up level to the department, you probably have to put a field in your lecture node and populate it behind the scenes with the department node reference (via hook_nodeapi() and $op presave by node_load()ing the nid of the course and getting it from there)


SearchAPI + FacetAPI: How to add a facet programmatically

The above use case may be an exotic one but I post my solution in case anybody else has a similar one and maybe it's a motivation for a more elegant solution.

Versions used:
- Drupal 7.38
- facetapi 7.x-1.5+1-dev
- facetapi_bonus 7.x-1.1+7-dev
- search_api 7.x-1.15
- search_api_solr 7.x-1.8

Steps in short

Add a new facetapi plugin to filter active facet items, using
hook_facetapi_filters() [1]
Plugin method execute(): Add the additional facet items to
the $build array of the active facet items
Alter the Solr query for the newly added facet items to combine the
two with operator OR, using hook_search_api_solr_query_alter() [2]
Activate the new plugin in the index facet configuration

Steps in detail

Add a new facetapi plugin with hook_facetapi_filters()

Documentation see facetapi.api.php and class FacetapiFilter [3]. Note the programmers comments in the docbloc of FacetapiFilter where another solution is suggested by adding an "alter callback". Unfortunately I couldn't get the alter callback to do what I like to do.

/**
 * Implements hook_facetapi_filters().
 * Define the plugin class to add additional facet items to an active facet.
 */
function mymodule_facetapi_filters() {
 return array(
   'add_items' => array(
     'handler' => array(
       'label' => t('Add facet items to facet "region"'),
       'class' => 'MyModuleFacetapiFilterAddItems',
       'query types' => array('term'),
     ),
   ),
 );
}

Plugin method execute(): Add the additional facet item to the  $build array of the active facets

Sample plugin code.

/**
 * Plugin that adds additional facet item(s) to an active facet.
 */
class MyModuleFacetapiFilterAddItems extends FacetapiFilter {

  // Execute active facets.
  public function execute(array $build) {
    // Taxonomy term ids of the facet items to combine into a new facet item.
    $tid1 = 1;
    $tid2 = 2;
    // Create the additional facet item. Check that the original facet items are
    // available.
    if (isset($build[$tid1])  && isset($build[$tid2])) {
      $add = array();
      $add['#markup'] = 'Region AB';  // the label of the new facet item
      $add['#path'] = 'search';  // your base search path
      $add['#html'] = FALSE;
      $add['#indexed_value'] = $tid1;  // @see comments below
      $add['#count'] = $build[$tid1]]['#count'] + $build[$tid2]['#count'];  // accumulate the #count of the two combined facet items
      $add['#active'] = 0;
      $add['#item_parents'] = array();
      $add['#item_children'] = array_merge($build[$tid1]['#item_children'], $build[$tid2]['#item_children']);  // merge the item children
      $add['#query'] = array(
        'f' => array(
          0 => 'field_region:' . $tid1,  // add both term ids in the #query f parameter
          1 => 'field_region:' . $tid2,  // leads to URL parameters like this: f[0]=field_region:1&f[1]=field_region:2
        ),
      );
      $build[] = $add;
    }
    return $build;
  }

  // Adds settings to the filter form, here only used for users' documentation. Inspired by facetapi_bonus.
  public function settingsForm(&$form, &$form_state) {
    $form['add_items'] = array(
      '#title' => t('Add a facet item for facet "region"'),
      '#type' => 'checkbox',
      '#default_value' => TRUE,
      '#suffix' => t('
        By enabling this filter, an additional facet item is added to facet "region".

        At the moment this list is hard coded and consists of

        - Region AB (combines Region A + Region B, with operator OR)
      '),
    );

    // TODO
    // - add UI settings to avoid hard coding stuff in code
    // - would be nice to be able to specify the operator (conjuntion) OR or AND in the $form array to pass it to the Solr query
  }
}

So far is achieved that the new facet item in facet "region" shows up. But it has zero results.

  Region A  (10)
  Region AB (0)
  Region B  (15)

As the operator (conjunction) for the facet "region" in my case is configured with "AND", the result of the newly added facet item "Region AB" is zero. So I need to combine the two filters with OR in the Solr query.

Alter the Solr query for the newly added facet items to combine the  two with operator OR.

Sample hook_search_api_solr_query_alter() code.

/**
 * Implementation of hook_search_api_solr_query_alter()
 */
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  // Only alter queries on the node index.
  if ($query->getIndex()->machine_name != 'node_index') {
    return;
  }

  // Facet query params array.
  $fq = $call_args['params']['fq'];

  // Get the key of the query that we need to alter. Depending on the active facets and if the
  // visitor is logged in or not, the fq array contains more or less queries in our environment.
  // The code below assures we modify the correct query.
  //
  // In this demonstration we use taxonomy term ids: tid1 = 1, tid2 = 2 for Region AB.
  // If both facet queries are present in the fq array, combine them to one query with operator OR.
  // Afterwards unset the second query.
  if ( (false !== $key1 = array_search('{!tag=facet:field_region_ref}im_field_region_ref:"1"', $fq))
  && (false !== $key2 = array_search('{!tag=facet:field_region_ref}im_field_region_ref:"2"', $fq))
  ) {
    $call_args['params']['fq'][$key1] = '{!tag=facet:field_region_ref}im_field_region_ref:"1" OR im_field_region_ref:"2"';
    unset($call_args['params']['fq'][$key2]);
    return;
  }
}

Now the counter of the newly added facet item shows up correctly.

  Region A  (10)
  Region AB (25)
  Region B  (15)

That's it about the coding. Of course "mymodule" has to be changed to the name of your module.

Remains just the last step to active the new plugin.

Activate the new facetapi plugin in the index facet configuration

In the Drupal administration UI visit "Configuration" > "Search and metadata" > Search API
- edit the Solr node index, visit tab "Facets"
- find facet "region" and select the "configure filters"
- active the new plugin "Add facet items .."
- store the changed settings

Note some drawbacks with this solution

1) Hard coded facet item properties
2) Facet item property: #indexed_value: can only specify one value. Don't know if this has implications on the counters when dependent facets are clicked. So far everything seems to be fine in my implementation.
3) Kind of complicated code to alter the query of the newly added combined facet items. It would be much more elegant if I could specify the operator as a parameter of the #query property when creating a new facet item. Or even easier: specify the fq query right in the wanted way like this: fq[0]=tid:(1 OR 2) -- only possible right now in module "ApacheSolr".

Links

[1] http://www.drupalcontrib.org/api/drupal/contributions!facetapi!facetapi.api.php/function/hook_facetapi_filters/7
[2] http://www.drupalcontrib.org/api/drupal/contributions!search_api_solr!search_api_solr.api.php/function/hook_search_api_solr_query_alter/7
[3] http://www.drupalcontrib.org/api/drupal/contributions!facetapi!plugins!facetapi!filter.inc/class/FacetapiFilter/7


It depends somewhat on your use case. For example are you scraping the images off a web page or are you using a direct image file URL.

If you are scraping from a web page you can use the feeds image grabber module.

That module provides additional settings where you can configure a CSS selector for the page that is in your XML file.

The module will then request that page and scrape the image from it based on the selector you configured then add the image to the imported item.


I too am using autocomplete for a term reference field and multiples are working fine - are you sure you're putting commas between terms? e.g. I type "one, t" and as I type "t", "two" will come up as a suggestion if the term is in the vocabulary.


address field hides if country is changed

It works as designed.
For some countries there is no need to enter ZIP code.

You can change this behavior by implementing this alter in your custom module:

/**
 * Allows modules to alter the predefined address formats.
 *
 * @param $address_formats
 *   The array of all predefined address formats.
 *
 * @see addressfield_get_address_format()
 */
function hook_addressfield_address_formats_alter(&$address_formats) {
  $address_formats['AF']['required_fields'] = array('postal_code');
  $address_formats['AF']['used_fields'] = array('administrative_area', 'postal_code');
}

Change required_fields and used_fields as desired.
More code you can find in this file:

addressfield/addressfield.address_formats.inc


View to show user relationships with different fields

You need to first add a users view and then you add a contextual filter to the view using the user field that the relation will have now exposed in the contextual admin selection. Then add a default value of currently logged in user to the contextual filter and with that it will expose the relevant fields.

Add new view of type users
Add contextual filter of type user relationships: User who accepted the relationship
Add default value of logged in user
(optional but will expose even further info) add views relations to expose further data
profit


Is it possible to include external libraries in a twig template?

Add external files in libraries: https://www.drupal.org/developing/api/8/assets

See the section on "CDN / externally hosted libraries".


Monitoring strategies for infrastructure

If you want monitor several Drupal sites from the same place with alerts, etc... I can say you are not the only one . It's starting to be a business niche, by now filled by:

Droptor
New Relic   (Acquia is using it for their
customers)

Both are commercial SaaS approaches, with free limited options to try the service.

Also there is the Open Source Zabbix monitoring option with its Drupal module http://drupal.org/project/zabbix , but then you should configure and build yourself the server.

All these options have their Drupal modules to send server and drupal-specific information to the monitor server.

UPDATE.  Munin has also a specific Drupal Module , with a 2.x branch based on Drush.


As I'm also looking for a solution to this issue I've come a bit further and maybe it will get you in the right direction.

To load a menu in Drupal 8 you can put this in a theme_preprocess_page in your .theme-file.

  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);
  $menu_html = \Drupal::service('renderer')->renderPlain($menu);

I have not yet worked out how to merge different menus into one big menu but I will let you know if I come up with a solution.
You can find out more about the code above at Drupal 8.2.x » menu.api.php which is where I found it.

Ok, I now have found the solution which I found in the module Responsive and off-canvas menu

  $menus = array("main-menu","footer-menu","utility-menu");

  $combined_tree = array();
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters(trim($menus[0]));
  $manipulators = array(
    // Show links to nodes that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkNodeAccess'),
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  // Force the entire tree to be build by setting expandParents to an
  // empty array.
  $parameters->expandedParents = array();
  // Iterate over the menus and merge them together.
  foreach($menus as $menu_name) {
    $tree_items = $menu_tree->load(trim($menu_name), $parameters);
    $tree_manipulated = $menu_tree->transform($tree_items, $manipulators);
    $combined_tree = array_merge($combined_tree, $tree_manipulated);
  }

  $menu = $menu_tree->build($combined_tree);

  $vars['mobile_menu'] = array(
    '#prefix' => '

',
    '#suffix' => '

',
    '#markup' => \Drupal::service("renderer")->renderRoot($menu),
  );

If you put this in your theme_preprocess_page in your .theme-file you could then in your page.html.twig print the twig variable {{ mobile_menu }}.


Module WYSIWYG with the 4.4.7 Ckeditor library stopped working

I would "downgrade" to the 3.6.x vrsion of CKEditor (such as CKEditor version 3.6.6.1.7696), since the WYSIWYG module does not support the 4.x version yet ...). In this case, you may also want to experiment with the various 'cleanup and output' options within /admin/config/content/wysiwyg/profile/your_txt_fmt/edit (with 'your_txt_fmt' the text format you're using, eg 'filtered_html').

Another option is to switch to the CKeditor module (which is in core in D8 now ...), and no longer use the WYSIWYG module in combination with the CKEditor library.


How to get replacement pattern for Search API's fulltext search in global text area header

The problem I was having here is my view that I was trying to build for search API was using a full text search exposed filter rather than a contextual filter. The contextual filter provides the search term title and search term input tokens that are pictured above. The exposed filter will not produce them. Live and learn.
EDIT: There is a bit of a workaround I found but it was an implementation I would not recommend. I was using Drupal core search blocks with Search API view's contextual filters together. I was able to add the contextual filter, get the token, then remove the contextual filter. That somehow allowed the token to work in that context.


If you want to get an easy to use search, you should consider using Search API where you can use a Solr backend and index entities, fields and even relations to other entities.

The apache solr module is more an API to Solr then a ready made search engine (though the module does offer some various search addons), which means you can index whatever you like, but you might need to write some code for custom entities.


This is a problem that raises it head in some or other form quite regularly. The answer is to change the jQuery version. Use jQuery Update. Set it to 1.7 or 1.8 for admin pages.


Is there a way to restore a field (in views) which has been removed using 'this block (override)'

You can basically revert the fields on the sub-view back to the master settings and list by:

-- clicking on the down arrow on the top right of the FIELDS section.

-- In the popup, change the For dropdown value to Revert to Default. This should effectively bring back the master list of fields, assuming that's where your missing field is.

-- any customisation for this specific view's fields must be re-done.

This same process can be done on any of the panes on the view's edit page - /admin/structure/views/view/my-view - if you want to revert anything.


Have an exposed filter on a view be a list of US states

AL|AL
AK|AK
AS|AS
AZ|AZ
AR|AR
CA|CA
CO|CO
CT|CT
DE|DE
DC|DC
FM|FM
FL|FL
GA|GA
GU|GU
HI|HI
ID|ID
IL|IL
IN|IN
IA|IA
KS|KS
KY|KY
LA|LA
ME|ME
MH|MH
MD|MD
MA|MA
MI|MI
MN|MN
MS|MS
MO|MO
MT|MT
NE|NE
NV|NV
NH|NH
NJ|NJ
NM|NM
NY|NY
NC|NC
ND|ND
MP|MP
OH|OH
OK|OK
OR|OR
PW|PW
PA|PA
PR|PR
RI|RI
SC|SC
SD|SD
TN|TN
TX|TX
UT|UT
VT|VT
VI|VI
VA|VA
WA|WA
WV|WV
WI|WI
WY|WY
AE|AE
AA|AA
AP|AP


How do I display a field from a referenced user?

You might achieve this with Views, by creating a view for nodes of that content type, and then adding a "relationship" to the user. The user fields will then become available for you to display.

You can find an introductory tutorial to start using Relationships with Views in "How relationships work in Views and how to add a referencing entity relationship".


Reference Based on Two Fields of a Content Type

Is there any reason why you could not just reconfigure auto node title to generate a node title based on a composit account number and environment -- say, something like "[account_number] ([environment])"?  It seems like if you did this, then your reference_account_number configuration would remain unchanged, your feeds will not get confused, and users can still add references by typing the account number only thanks to the standard autocomplete feature of node references.

If you did not like the way that "[account_number] ([environment])" looks in the output of your site, you could alter the render array, maybe in a hook_process_field.  For a good description on hooking the Drupal 7 render process, see The Scary Render Array.


Considerations displaying page titles in page or node template

It would be a much better practice to move most of this logic to the theme's preprocess_page: http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess_page function so you can keep the separation of logic and presentation and make things easier on your designers.

You could add variables that could contain the different fields and classes that change based on the nodes content type in the preprocess_page.


How to grant permission to specifc role to perform CRUD operations on a particular content type only?

Use Rule module. And create action assign role.

How to use.


while category/year/2525 is an alias for taxonomy/term/xxx you should restrict access to taxonomy/term/* for all anonymous users.

if you want do this via simple module:

function mymodule_init(){
  global $user;
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && !$user->uid) {
     drupal_access_denied();
     exit;
  }
}


How to use daterange field programmatically?

If you programatically need to set a datetime range field when creating a node in a custom form submit handler for example, you need to to fill two values:
The start date value and the end date end_value.
$node = \Drupal\node\Entity\Node::create([
  'type' => $type,
  'title' => $title,
  'field_dates' => [
    'value'=> '2018-02-02T12:12:12',
    'end_value' => '2018-05-05T12:12:12'
  ],
]);
$node->save();


How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field?

Your question is not clear (enough), at least not yet, so I'll try with 2 variations ...

Field C is about Single values

It think your rule needs at least 2 corrections:

Add a Rules condition like "entity has field", for each "token" that you want to use in any rules Action, but which is not (yet) showing up to actually select it in some Rules Action.
When using a Rules Action like "Set a data value", you can indeed only set such value for 1 variable. However if you want to "Set a data value" for another variable, just add a 2nd Rules Action to do so for that other variable.

Field C is about Multiple values

Maybe your question is rather something like so:

  If this Rules Event happens, then I want to add the node reference in field A to field C, and I also want to add the node reference in field B to field C (and field C is a multi value node reference field".

In this case, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". I.e.:

Rules Action 1 is to add A to the list C (possibly you also need a Rules Condition like "Entity has field" (for A)).
Rules Action 2 is to add B to the list C (possibly you also need a Rules Condition like "Entity has field" (for B)).

Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "Add item to a list".

Recommendations to improve the alternative answer

Now (after about a day of extra questions/comments to the question from No Sssweat and myself), it finally became clear what the real question was ...

Here is a variation of the Rule in the alternative answer:

{ "rules_improved_combination_of_taxonomy_terms" : {
    "LABEL" : "Improved combination of taxonomy terms",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "[node:field-a][node:field-b]" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[variable-added:value]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "entity-created" ] } },
      { "entity_save" : { "data" : [ "node:field-c" ], "immediate" : "1" } }
    ]
  }
}

These are the extra refinements needed to make it work:

Add an action to save an entity (twice), because since you used Rules Event to just wake up after viewing a node, you need to remind the Rules module to also save what you've been creating/updating.
Remove the Fetch entity (no need for that).

By the way, the clue to debug the rule in the other answer can be found if you turn on rules logging: you'll see that the fetch entity didn't return any results, so blank, which is also what got saved in field C ...

Demo:

Field A: Bonjour
Field B: World
Field C: BonjourWorld

At least that's what happened in my tests. If I change A to Hello (or No), B to Liu (or Sssweat), then C gets updated to HelloLiu (or NoSssweat) ...

Be Aware: I can think of some further improvements of all this, but for now I consider this rule as "Make it right before you make it better" ... try it in your own setup to confirm it does answer the quetion (but please don't post enhancement requests via extra comments, instead post a new question if needed).

Disclaimer: I don't have a clue what those non-English "pictures" are (I bet they are characters in your native language ...).


Drupal 7 login form redirect back to page which they logged in on

Create a action (admin/config/system/actions)

You have to use the token module and find the right token for the needed path. (Maybe someone else can point the right token for this behavior.)

Create a trigger (admin/structure/trigger/user)

AFTER A USER HAS LOGGED IN -> redirect to the path


Provide additional Status option for user_profile_form

You have implemented hook_form_FORM_ID_alter(), which only fires for a single form (user_register_form in this case).

If you want to use multiple forms in a single function, you need hook_form_alter():

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
  ...
}


Views field: how to add html 'title' attribute to link

This will add title attributes to most links, depends with some modules though.

/**
 * Add title attribute to any link that doesnt have a title already
 */
function YOURTHEME_preprocess_link(&$vars) {
    // If title set and not empty dont do anything
    if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
        return;
    }

    // Use the link text as the title
    $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}


what action can trigger clearing of caches?

Have you checked whether Cron is configured on your site under Configuration options.

When trying to speed up my site, this article was very useful as Cron will clear cache.

http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer


WYSIWYG editor on Paragraphs text field?

If you want to have a multi line textarea with an WYSIWYG editor, you'll have to create, for your paragraph type, a field of type "Text (formatted, long)" and while editing your field, you should choose "Full HTML" as "Text format". Hope this works for you.


Drupal has a built-in tableselect element type for situations just like this, it would be a lot easier to use that instead:

$disputes = array(
  1 => array('Joe', 'Smith'),
  2 => array('Susan', 'Doe'),
  3 => array('John', 'Doe')
);

$header = array(t('First Name'), t('Last Name'));

$form['checkboxes'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $disputes,
  '#empty' => 'No users were found.'
);

The above code produces this table:

In your form submit function you can get the selected user ids with code like this:

$selected_uids = array_filter($form_state['values']['checkboxes']);

EDIT

The above is for Drupal 7, if you're using Drupal 6 you can use the same code but you need to install the Elements module.


Node custom property exposed as extra field

Looking at Entity module's hook_field_extra_fields() implementation:

/**
 * Implements hook_field_extra_fields().
 */
function entity_field_extra_fields() {
  // Invoke specified controllers for entity types provided by the CRUD API.
  $items = array();
  foreach (entity_crud_get_info() as $type => $info) { ... }
  return $items;
}

It only looks for entity types provided by the CRUD API -- in other words, entities whose controllers inherit from EntityAPIControllerInterface. Node entities use NodeController.

You can still do this conventionally, outside of Entity API -- implement hook_node_view() to insert your pseudo-field in $node['content'], then implement hook_field_extra_fields() to expose that pseudo-field to the node's "Manage display" tab.


How can I display a block on view page, excluding paginated/paged/pager output pages?

Thanks to Clive's post above, this can be accomplished with the early dev module Request Data Conditions:

https://drupal.org/project/request_data_conditions


For views, how do I display only one of a series with the same title?

To only show one immediate next upcoming event:

add Sort criteria by date (ascending so you get the events that are soonest to happen as first on the list), make sure the correct one come up top
and then limit your results to only show 1 row (Display a specified number of items to 1 under Pager options, but don't output the Pager).


The Best way is to do it with core Book module

  A book is a set of pages tied together in a hierarchical sequence,
  perhaps with chapters, sections, subsections, and so on. You can use
  books for manuals, site resource guides, Frequently Asked Questions
  (FAQs), or whatever you'd like.


Displaying multiple node add forms using panels and contexts

I doubt that panels can handle it.

I would try creating a custom page with hook_menu and outputting all the forms on it via a page callback like
   $output = drupal_get_form('foo_node_form');
   $output .= drupal_get_form('bar_node_form');
   return $output;


Fetch data from database and show in custom block

depending on the information you want to retrieve, Views is probably your simplest option:

  You need Views if

  You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.

Views allows you create a block or a page in order to display formatted data.


How do I filter a view page with contextual filter?

You could use this module to set up the date field for the events: http://drupal.org/project/date.

This video explains how to use arguments with the date module:
http://www.drupaltherapy.com/date_d7

Then create 3 view pages, with the only difference being the arguments of each page view to determine if the date is:
1) in the past
2) in the future
3) doesn't need to be filtered by date

Each view page would get its own path.
Then you could create a menu with the different paths as links.

Once you have your menu set up, go to Structure- Blocks - and you can configure the menu to be in the content area, and paste the paths of the 3 pages you've created, separated by commas in the section that says SHow Blocks on Specific Pages.

Hopefully that gets you on the right track.


Need to add filter with more than one word in view filter criteria Drupal7


Drush Make for a custom module hosted at github

According to the documentation, you have to write the download url line this way:

projects[mytheme][download][url] = "git://github.com/jane_doe/mytheme.git"


Provide variable to page.tpl.php to mark page as Access Denied or 404?

If I uderstand your question perhaps try: Drupal 7 Custom 404 Page Template - use this method to setup a custom page template (tpl) file for your 404 page. This will give you a specific page template that you can hard code classes you're wanting - "access-404" or "access-denied" in the body tag.


The configuration is in Drupal itself. Just visit /admin/config/search/clean-urls and enable it :

Note : It needs to be enabled in Apache as well. In Apache rewrite module should be enabled.


Reverting blocks and other pseudo-exportables in an install hook

In short: the workaround is to call drupal_flush_all_caches() and drupal_static_reset() before reverting the module containing exported features again from an install task.

In detail: The main symptom observed was that blocks (exported as fe_block_settings components), were not correctly applied on the new site when they depended on a Views block display defined in the same features module.  This remained true even after adding an additional call to features_revert_module() in an installation task.  (There were also problems at one point with variables and permissions, but these were cleared up more easily by the addition of the call to features_revert_module()).

The problem with settings for views blocks is that Views caches all views loaded from the database in a static variable, making any views loaded or enabled for the first time during a single request or drush command invisible to later calls to views_block_info().  One possible (tested) workaround is the following:

views_get_all_views(TRUE);
drupal_flush_all_caches();
features_revert_module('xyz');

Supplying TRUE for the $reset parameter to views_get_all_views() forces the module to discard its static cache and re-compute the list of blocks from scratch.  This allows the revert of block settings to go through correctly.

Because I suspect this will not be the only problem caused by invalid static variable caches, I am trying the more drastic approach of resetting all static variables and clearing all caches before reverting the module:

drupal_static_reset();
drupal_flush_all_caches();
features_revert_module('xyz');

(Resetting all static variables does produce a few extra PHP warnings, which hopefully are spurious.)

The above lines are run as an installation task, and are combined with the approach described in https://www.drupal.org/node/1901116: i.e., remove the module with exported blocks from the dependencies[] list, and enable it manually in hook_install() after enabling themes for the site.  The complete implementation in the profile .install file then looks more like this, where the installation profile is named foo, the features module is named xyz and the site theme quux:

/**
 * Implements hook_install().
 */
function foo_install() {

  // ... other setup code here ...

  // Enable themes
  theme_enable(array('seven', 'quux'));
  variable_set('admin_theme', 'seven');
  variable_set('node_admin_theme', '1');
  variable_set('theme_default', 'quux');

  // Enable module containing features-exported block settings
  module_enable(array('xyz'));
}

/**
 * Implements hook_install_tasks().
 */
function foo_install_tasks(&$install_state) {
  $tasks = array(
    'foo_revert_xyz' => array(
      'display_name' => st('Apply all settings in "xyz" module'),
      'type' => 'normal',
    ),
  );
  return $tasks;
}

function foo_revert_xyz() {
  drupal_flush_all_caches();
  drupal_static_reset();
  features_revert_module('xyz');
}

Tracking this down was a real headache, so I hope the solution is useful to someone else.


Advanced search: USASearch compared to Apache Solr Search implemented by Acquia

I didn't go too deep into USASearch, but it seems to me as a tool similar to Google Custom Search Engine.

So, let's classify them first. We'll call all such services as Search Providers. On the other hand, we'll call ApacheSOLR instances (whether through Acquia or otherwise), regular search index in Drupal or other such index hosting services as Indexes.

The general difference between Search Providers and Indexes is mostly in the level of control.

Search Providers

Quicker to setup for static websites as it is just HTML/JS code.
Ideal for simple static content with limited customization.
You don't have to worry about the index at all. That is your provider's job.

Indexes

For Drupal, it is just a matter of installing a module.
You get complete control over results, templating, filtering, facet search, etc...
You have to take care of indexing content, permissions, and search configuration.

Generally speaking, go for Indexes, or in your case, Acquia Search. The configuration and indexing is one time (and sometimes not even that) and the added benefits are huge. There are very few scenarios where I would pick a search provider instead.


I had a similar issue to deal with. I need to generate form IDs programmatically so I implemented below code.

function voci_comment_form($form, &$form_state, $cid) {
     $form['#attributes']['id'] = 'voci-comment-form-' . $cid;
     $form['#attributes']['class'][] = 'voci-comment-form';
     $form['body'] = array(
      '#title' => 'Post a comment',
      '#type' => 'textarea',
      '#resizable' => FALSE,
      '#rows' => 1,
     );
     $form['comment'] = array(
      '#type' => 'submit',
      '#value' => 'Comment',
     );

      return $form;
   }

It's true that you can set $element['#attributes']['id'] and that will apply to the form field.

I hope this helps... :)


Is there any way to alter the "field type" of a field?

Drupal itself does not support changing the field type, only the widget. This is because different types have different database structure. On the other hand, it is possible to change some types with custom code (e.g. see http://www.up2technology.com/blog/converting-drupal-fields) but in general, you would need to write migration to do this.

So in general, it is not possible to change the field type without loosing the data stored in it, especially not things like text -> image etc.


How to change labels on node add/edit form inside Authoring information box?

Those are the uid and created base fields, so yes hook_form_alter() or using interface translation are your options.

To add a new element in there, you need to set the right group, from NodeForm:

<?php
if (isset($form['uid'])) {
  $form['uid']['#group'] = 'author';
}


Can I programmatically create a new node revision, without the new revision becoming the "current" one?

A standard Drupal install does not allow you to create a "Pending" revision.  You have two options:

Programatically create a new revision but programatically revert back to the original revision (which creates an even newer revision, but it has the original content)
(Recommended) Use Workbench Moderation, Revisioning or Workflow which are well thought-out solutions for version control and/or access control.

For option 1:
You can add this code as a new Rule or use it in a new module

<?php
  // Programatically load the existing revision and save it
  // Taken from http://api.drupal.org/api/drupal/modules!node!node.module/function/node_save/7
  // Load the revision
  $original_revision = node_load($nid);
  $original_revision->revision = 1;
  $original_revision->log = t('Copy of the revision from %date.', array('%date' => format_date($original_revision->revision_timestamp)));

  $new_revision = node_load($nid);
  // Make any changes to the new revision here...
  $new_revision->revision = 1;
  $new_revision->log = t('Summarize your changes here');

  // Save the new revision first
  node_save($new_revision);

  // Save the original one again so that it is still the current revision
  node_save($original_revision);

  watchdog('content', '@type: reverted %title revision %revision.', array('@type' => $node_revision->type, '%title' => $node_revision->title, '%revision' => $node_revision->vid));
  drupal_set_message(t('@type %title was saved with a new revision, but reverting to original revision from %revision-date.', array('@type' => node_type_get_name($node_revision), '%title' => $node_revision->title, '%revision-date' => format_date($node_revision->revision_timestamp))));
  drupal_goto('node/' . $node_revision->nid . '/revisions');
?>

For option 2:
I would recommend Workbench over Revisioning or Workflow, but each is different depending on your needs.  Workbench is kind of the successor to Revisioning, and Workflow is a lot more than just version control, so it may or may not be a good fit for your needs.

Here's a quick breakdown on the differences between Workbench and Workflow.


Check content type of node in preprocess hook

To get the content type of a node, you just use $variables['node']->getType() or $variables['node']->bundle(). The first method just calls the second, so calling one or the other one doesn't make much difference.

public function getType() {
  return $this->bundle();
}

The only difference is that bundle() is defined for every entity, since the concept of bundle is common for all the entities, while content type is the property Drupal used for nodes before changing them in one of the entities Drupal core modules implement; using bundle() makes easier to adapt the code for other entity types, but I don't think it is the case for the code you are using.


How to customize registration process in Drupal 7?

You can create three roles named:

Personal
Business
Organization

Now you can use profile2 Registration Path module. This module will give you three separate profile for each roles. You can add separate fields for each profile. And from the configuration of profile pages you can enable separate registration path also.

Thus you can have three registration path for three roles and three registration forms also.

Now to create multistep form for profile2 module you can follow this question from this site.


I need a field that will allow content editors to enter a rating while editing a node...

You could use Drupal's built in Field API to do this. Given that a node will already be in edit mode while being rated, you wont need any additional add-on modules.

If you use the integer type, calculations should be simple.  You can override the text like this:

To add the images next to each item, you could use CSS.  Each element should have the necessary classes to theme them as required.


How do I display/edit the machine name for a View?

You can export view, change values, delete original and import view back.

There is a import option in the views listing page. Just paste this url after your current url and you will see the import views page. By seeing your tags I am assuming you are using Drupal 7, so the given below url will work only for Drupal 7.

Below is the url to be added :

#overlay=admin/structure/views/import

To export view:

go to /admin/structure/views
under 'operations' column click on arrow and select 'export'
copy code and edit/change in external editor
go to /admin/structure/views/import and import changed view You can first delete existing view or select 'Replace an existing view if one exists with the same name' on the import settings –


Form redirect in hook alter submit is not working in Drupal 8

I was executing setRebuild()! I added another submit button and started doing the steps in my previous submit logic one by one, then it hit me. Form redirection will not happen if your submit is rebuilding the same form :)

$form_state->setRebuild();


The best and cleanest way to achieve what you want is with a product pricing rule and a custom action with what you have above. That way it goes through the normal Commerce hooks. You just create a rule reacting on "Calculate the sell price of a product."

If you only want the rule to fire on cart and checkout pages, you can also create a custom condition that checks your current path (or there might be a module that adds that condition for you.)

So instead of a hook_form_alter, you want to declare a hook_rules_action_info().


Taken from this comment, written by zifiniti:

  I was having trouble getting a menu item to display with the following code:

function mymodule_menu() {
  $items['custom-page'] = array(
    'title' => 'Custom Page',
    'menu_name' => 'main-menu',
    'access arguments' => array('access custom pages')
  );

  return $items;
}

  It was continuously denying me access to the specified path in addition to not displaying the item in the menu. I discovered that the reason behind this is if you do not specify a page callback, then the access callback will acquire a value of 0 in the database and thus render that path/menu item inaccessible.

  Working code:

function mymodule_menu() {
  $items['custom-page'] = array(
    'title' => 'Custom Page',
    'menu_name' => 'main-menu',
    'page callback' => 'mymodule_custom_page',
    'access arguments' => array('access custom pages')
  );
}


Ah, just found it in pretty much the first few lines of menu.inc. It does indeed look one level higher until it finds a match.


How do I find the user ID  knowing the username, when using drush?


What is the difference between an 'Attachment display' and a 'Global: View area' put into header/footer of a view?

Background: View is a view,  a view can have many displays, such as page, feed, attachment, block.

With Attachment display, you can attached one display of a view to another display.   A good video demo can be found by Doug Vann (its a drupal 6 demo, that can relate to drupal 7).

With Global: View area (Drupal 7 only)  you can add a view inside a view header or footer.

This is no huge pro/con of doing it one way over another.    The only thing I can think of is templating a view and styling it. There will be different html tags and classes for you to style.


This table is actually the rendered view 'Line items (Commerce Line Item)' which is created in code by Drupal Commerce. So all you have to do is to modify this view to your needs.

To further customize the display of your invoice, you can make a copy of css/pdf.css and themes/commerce_order--commerce_order--pdf.tpl.php located in commerce_billy_pdf folder into your custom theme and experiment.


You definitely want to create a views handler with your custom php code. This is the standard way to do custom php stuff on views module.

Here you have an example:

mymodule.info

...
files[] = views/handlers/views_handler_field_node_link_custom_stuff.inc
...

mymodule.module

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/views',
  );
}

In MYMODULE/views/mymodule.views.inc:

function mymodule_views_data() {
  $data['node']['custom_stuff'] = array(
    'field' => array(
      'title' => t('Custom link'),
      'help' => t('Provide a custom content link.'),
      'handler' => 'views_handler_field_node_custom_stuff',
    ),
  );
  return $data;
}

MYMODULE/views/handlers/'views_handler_field_node_link_custom_stuff.inc

/**
 * Field handler to present some custom HTML.
 */
class views_handler_field_node_custom_stuff extends views_handler_field_node {
  function construct() {
    parent::construct();
    $this->additional_fields['type'] = 'type';
  }
  function query() {
  $this->ensure_my_table();
  $this->add_additional_fields();
  }
  function render($values) {
    $type = $this->get_value($values, 'type');
    $nid = $this->get_value($values, 'nid');
    return mymodule_print_my_link($nid, $type);
  }
};


Your implementation is most probably correct, I use the following code to customize access to the register page in some projects:

function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = 'MYMODULE_user_register_access';
  unset($items['user/register']['access arguments']);
  $items['user/register']['type'] = MENU_CALLBACK;
}

Make sure that the custom module is enabled, make sure that the module name is spelled correctly, also make sure that there really is an & prepended to the $items parameter. It happened to me in the past that I forgot the reference operator on hook_X_alter implementations. Also flush caches after adding new hook implementation functions.


how to make a field disabled, greyed out

I am pretty sure you are looking for the #disabled property, eg the Form API Reference Disabled Property that...

  Disables (greys out) a form input element. Setting #disabled to TRUE results in user input being ignored, regardless of how the element is themed or whether JavaScript is used to change the control's attributes.


How can I manually change image orientation?

1 Read an image in JS from attached file https://developer.mozilla.org/ru/docs/Web/API/URL/createObjectURL

2 Use Lib for reading Exif data from jpg for autorotation as default option https://github.com/exif-js/exif-js

3 Create controls for manual rotate image on canvas as manual tool https://stackoverflow.com/questions/17411991/html5-canvas-rotate-image

4 Send on server additional param with rotation value (for apply rotation to orig image on server side)
    OR
  Apply rotation on original size image on JS and send result on server as base64 code. Decode to binary data in server side and put it on disk.

sorry for my english


TableSort has methods to retrieve the sorting order and the field being sorted directly from the query arguments. You can use the values returned by ::getSort() and ::getOrder() to do a custom sorting of your data.
In your render array you can use some (undocumented) options in the #header declaration to control the way the table is initially sorted:

field: the name to use in the query arguments to indicate that the table should be sorted by this column.
sort: one (and only one) of the columns can be given this option (with value either asc or desc). This will be the column that is sorted by default.
initial_click_sort: this can be set to desc if the data should be sorted in descending order if the column header is initially clicked. This defaults to asc but for some data you want to show larger numbers at the top by default.

Here is an example of a controller using data from a custom array:
<?php

declare(strict_types = 1);

namespace Drupal\my_project\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Utility\TableSort;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Demo of a table with sortable columns using data from a custom source.
 */
class SortableTableDemoController extends ControllerBase {

  /**
   * The Symfony request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a new SortableTableDemoController.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new static(
      $container->get('request_stack')
    );
  }

  /**
   * Returns a render array containing data about Linux distributions.
   *
   * @return array
   *   The render array.
   */
  public function linuxDistributionsTable(): array {
    $headers = [
      // The distribution label has the 'sort' option, making it the default.
      [
        'data' => $this->t('Distribution'),
        'field' => 'label',
        'sort' => 'asc',
      ],
      [
        'data' => $this->t('Initial release'),
        'field' => 'year',
      ],
      // Sorted from highest to lowest on initial click.
      [
        'data' => $this->t('Packages'),
        'field' => 'packages',
        'initial_click_sort' => 'desc',
      ],
    ];

    $data = [
      ['label' => 'Arch Linux', 'year' => 2002, 'packages' => 77264],
      ['label' => 'Debian', 'year' => 1993, 'packages' => 118326],
      ['label' => 'Red Hat', 'year' => 2002, 'packages' => 12155],
      ['label' => 'Gentoo Linux', 'year' => 2002, 'packages' => 29092],
      ['label' => 'OpenSUSE', 'year' => 2006, 'packages' => 76236],
      ['label' => 'Ubuntu', 'year' => 2004, 'packages' => 89403],
    ];

    // Sort the table according to the options passed in the query arguments.
    $request = $this->requestStack->getCurrentRequest();
    $sort = TableSort::getSort($headers, $request);
    $order_by = TableSort::getOrder($headers, $request)['sql'];

    usort($data, function (array $a, array $b) use ($sort, $order_by): int {
      $result = $a[$order_by] <=> $b[$order_by];
      return $sort === 'asc' ? $result : -$result;
    });

    return [
      'table' => [
        '#type' => 'table',
        '#header' => $headers,
        '#rows' => $data,
      ],
    ];
  }

}


Why does my view duplicate the same content ( translation )?

after searching I found the solution for my problem :

This may happen if you have applied filters on any date field.
So.

in Views Advanced Settings under OTHER options, select "Query Setting" and check "Distinct" option.

That's it .


How to set the tabs on node pages to always display in the site's default language?

You can use this function (inspired from this solution wich was for Drupal 6)

/**
 * Reverse translation: find source string for a given translated string.
 */
function rt($string) {
  global $language;
  $langcode = $language->language;
  $query = db_select('locales_source', 'ls');
  $query->leftJoin('locales_target', 'lt', 'ls.lid = lt.lid');
  $query->fields('ls', array('source'));
  $query->condition('lt.language', $langcode);
  $query->condition('lt.translation', $string);
  $result = $query->execute();
  $records = $result->fetchAssoc();

  return $records ? $records['source'] : $string;
}

Then via hook_menu_local_tasks_alter

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && isset($argument->type)) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        $data['tabs'][0]['output'][$key]['#link']['title'] = rt($value['#link']['title']);
      }
    }
  }
}


I have an INT field that's the problem. You need to use a Date field and not an integer field. As INT fields are not meant/designed to hold dates. Drupal cannot know that your INT it's actually a time stamp and not a number.

As per my Q here: Unix timestamp time is not saving to DB, I was never able to figure out how to save unix time to the DB.

So you could stick with the INT field and use jQuery to convert your unix time to what ever time you need. The big downside is that if you will not be able to sort or filter by a certain month or year.

The better solution is to  use Date field, but transform your Unix time stamp to some format accepted by the Date field. By using PHP, with hook_node_presave or using jQuery.

In conclusion, use a date field.


I'm not sure exactly why but it's got something to do with the double quotes in the query. Replacing them with single quotes makes queries of that nature run just fine.

You should really be using parameters rather than putting values straight into the query string though. db_query() accepts an array as its second argument to perform parameter replacement, and doing things this way means you don't even need to worry about quotes; PDO will take care of that for you.

Plus if you extend your query to accept that argument from a variable rather than a static string, you don't need to worry about SQL injection (again PDO will take care of it).

Your query would look like this:

$args = array(':product_id' => 'mnbvcxz');
$result = db_query('SELECT * FROM field_data_field_product_id WHERE field_product_id_value = :product_id', $args);

To offer another alternative, the preferred way of querying by field data is to use the  EntityFieldQuery class. There are several benefits, possibly the most important being that it's storage engine agnostic - if you decide to move your field data to (say) MongoDB, the query will still work.

e.g.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_product_id', 'value', 'mnbvcxz');

$results = $query->execute();
if (!empty($results['node'])) {
  $matching_nodes = node_load_multiple(array_keys($results['node']));

  // Do something with those nodes
}


How can I add a log entry to watchdog every time form_set_error() is triggered on user_account_form_validate()?

To add a new validation handler to a form, you need to implement hook_form_alter(). In your case, I would use the following code, which adds an extra validation handler that is executed before the other ones added by the User module.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  array_unshift($form['#validate'], 'mymodule_user_register_validate');
}

function mymodule_user_register_validate($form, &$form_state) {
  $account = $form['#user'];

  if (isset($form_state['values']['name'])) {
    if ($error = user_validate_name($form_state['values']['name'])) {
      // This is intentionally empty.
    }
    elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
      // Log the error with watchdog().
    }
  }
}


As D8 uses Symfony responses it's as simple as:

use Symfony\Component\HttpFoundation\Response;

...

$response = new Response(
  'Your HTML content here',
  Response::HTTP_OK,
  array('content-type' => 'text/html')
);

return $response;

See the docs for more information.


you cant create custom region in a theme using custom module in a drupal way . however you can fetch available regions


Set body format for a node when it is updated via REST API

Kind of surprised this even works. The value of a field is a list of field items. Try something like this:

body: [ { value: this.state.body, format: "basic_html" } ],


How do I retrieve a plugin block field's translated value?

Little did I know, the translation was correctly loaded, but not used in the twig files. Both the fields' content and configuration were loaded, were content was ie an image and a link, and configuration the field's translation.
Somehow, still, the configuration needed several cache rebuilds to show up, but then went ok and kept being updated if I made any modifications.
The twig files were using variables such as {{ content['field_worldwide_text'] }}, so I needed it to use config[] instead.
Additional notes for future self, here is how to load content and configuration:
$content = $this->blockConfigFactory->getBlockConfig($this->getPluginId());
$config = $this->getConfiguration();


How do I modify Drupal so that ONLY relative URLs are used through the whole site?

You can alter all Drupal generated URLs to make them root relative using hook_file_url_alter

function mymodule_file_url_alter(&$uri) {
  global $base_path;

  $scheme = file_uri_scheme($uri);

  if (!$scheme || $scheme == 'public') {
    if (!$scheme) {
      $path = $uri;
    }
    else {
      $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
      $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
    }

    // Clean up Windows paths.
    $path = str_replace('\\', '/', $path);

    $uri = $base_path . ltrim($path, '/');
  }
}

For links in content you can apply the filter supplied by Pathologic


How to create 2 or more different registration pages in Drupal 7

Could Rules and Webform suffice for what you need to accomplish with the second registration form?

I actually did something similar recently, using a webform as a second registration form. I used the original registration form for the basic registration and on the second form I used Webform Rules to perform actions when the webform was submitted. Of course, this could also be done with a simple fielded node and Rules, but I liked the extra features that webform offered in doing this. If this project can be accomplished with nodes/Rules or Webform/Webform Rules then that can certainly offer you a lot of flexibility in updating the forms in the future as well.


Complex Drupal setup using Views, Entity/Node Reference and custom content type

You should be able to add a node reference field on the Feedback content type. When your user creates a new Feedback node, they should be able to select the correct Delivery node to associate it with.

You will most likely want to constrain the user's selection options to Delivery nodes associated with that particular user so that User 1 doesn't leave feedback about User 2's delivery. One way to do this is to create a custom autocomplete function and use hook_form_alter() to edit the Delivery node reference field on the Feedback node create/edit form.

On a Delivery node, to display Feedback nodes that are associated with that Delivery node, you can create a View that has shows Feedback nodes that are associated with the currently logged in user and references the current node nid (use contextual filters for both).


This information is valid for Drupal 6 and 7. In Drupal 8, hook_menu() has been replaced by new routing system. Below we implement hook_menu() in three simple steps.

Step one

Create an empty module following the instructions in How to create an empty module. In the code shown here, it's assumed the module is named helloworld.

Step two

Add the following code to the module file.

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return 'Hello world!';
}

Step three

Enable the module, and visit http://example.com/hello. (Replace example.com with the domain name for your server.)
You should see the message "Hello world!". That's it! You have a fully working hook_menu() implementation. What follows are various more advanced topics regarding hook_menu(). In particular, you may want to read about permissions, as the page above will be viewable by anyone.

Arguments

If you want to pass more data to the page callback, you can use page arguments to achieve this. Page arguments should be an array of arguments to pass on to the page callback. If an integer is used as an argument it will represent a part of the URL, starting from 0, incremented once for each slash (/). In the following example, this means the 0 will be turned into 'hello'.

function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(0),
  );

  return $items;
}

function helloworld_page($argument1) {
  return $argument1;
}

Strings will be sent on verbatim, so array(0, 'world') could be used to get hello world out again.

function helloworld_page($argument1, $argument2) {
  return $argument1 . ' ' . $argument2;
}

"Wildcards" can be used to accept arbitrary data from the URL.

function helloworld_menu() {
  $items['hello/%'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
  );

  return $items;
}

function helloworld_page($argument1) {
  return $argument1;
}

Visiting hello/world, $argument1 will equal world.

Argument autoloading

Often a URL argument will be the number identifying, for example, an entity. To avoid duplicating code that converts this ID into its corresponding object, Drupal support autoloading for "named" wildcards. When a named wildcard is used, Drupal will check for a function with the same name as the wildcard, suffixed by _load. If such a function is found, it will be called with the value of the value in the URL, and whatever is returned by the loader function will be passed to the page callback in place of the original value. Since Drupal already has such a function for loading nodes, node_load(), we can get nodes autoloaded and passed to the page callback.

function helloworld_menu() {
  $items['hello/%node'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
  );

  return $items;
}

function helloworld_page($node) {
  return t('Hello node (ID = !nid)', array('!nid' => $node->nid));
}

Advanced autoloading

Sometimes, it will be necessary to auto-load more based on more than one argument. Since only the named argument is passed to the loader by default, one needs to explicitly tell Drupal which extra load arguments should be passed on to the loader. For example, to load a specific revision of a node, it is necessary to pass to node_load() a node ID and a revision ID. That can be accomplished by the following code.

function helloworld_menu() {
  $items['hello/%node/revision/%'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
    'load arguments' => array(3),
  );

  return $items;
}

function helloworld_page($node) {
  return t('Hello node (ID = !nid, revision ID = !rid)', array('!nid' => $node->nid, '!rid' => $node->vid));
}

Permissions

'access callback' => TRUE, is necessary to make the simple example above viewable at all, but it's hardly ideal, as it allows no control what so ever. Anyone that tries to visit /hello will be granted access. The easiest way to provide some measure of control, is to provide a access callback, much like the page callback from above. The following code still allows access to anyone, but shows how to move the logic to a function called at access time, thereby allowing more complex logic.

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_access',
  );

  return $items;
}

/**
 * Access callback for /hello.
 */
function helloworld_access() {
  return TRUE;
}

This isn't necessarily the best way, as using a custom function will often needlessly duplicate code. A better way will be, most of the time, to use user_access(). Together the access callback it is possible to set access arguments. It is possible to require the page to be viewable from the users with the access user profiles permission with the following code.

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
  );

  return $items;
}

Since the access callback by default is user_access, it can be left out, as in the above code.

More advanced topics

The official hook_menu() documentation provides a lot more information about the most complex use-cases for the hook.


How to make a theme hook suggestion for menu according to region?

Joery Lemmens posted an answer to a similar question on Drupal's forums:

use Drupal\block\Entity\Block;

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

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

All credit to Joery for this elegant solution.


How make patch in PHPStorm suitable for Drupal.org?

PHPStorm patching issues have a long history. I have corresponded with their staff more than once, about a year ago. They told me then, that my issue was taken up to developers, but never actually corrected it. Right now, PHPStorm issues patches incompatible with Drupal.org, and we can do nothing about it.

To create a working legit patch, you need git, and create a patch like this: git diff > patch_name.patch

See http://drupal.org/node/707484

A number of PHP Storm request related to this issue have been merged into a single issue http://youtrack.jetbrains.com/issue/IDEA-92793


Perhaps a view with exposed filters may be a quicker solution for this kind of thing.


Add description to files uploaded by the Media file selector widget

With the file_entity module you can add fields to files.  So in your case add a "Description" field to your image file type.

When selecting how the field will be rendered, make sure to choose "Rendered file" and it display the file with the extra fields.


PHP filter is a core module in Drupal 7 but in Drupal 8 it is removed because of some security reason but still you can use this module PHP.

Note: Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site.


How to validate email on webform if the field type is textfield and you have data

After a couple days asking google for the solution, I did this.
1. Install the module  https://drupal.org/project/webform_validation
this will add another tab on your webform.
2. select "Regular expression, case-insensitive"
3. add the next regex (regular expresion)   ^[_a-z0-9-]+(.[_a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,3})$
4. select your email field to validate and add some text to the error message.
that's it...
from now on all your email will be validate,  but the old data must be fixed by hand...
the good thing, is you do not need to migrate your data just for  fix it..

hopefully this will be helpful to someone...
 best


What is the difference between page callback and access callback?

page_callback is a function called which will be used to generate contents of the page
access_callback is a function called which will be used determine if a user has access to view the page. This can be used where a simple permission isn't enough. An example would be that the author of the node would be allowed to edit the node or any user with a special admin permission.
Note the access_callback will by default be the user_access function which will check that the user has a specific permission.

Both of these keys have a sidekick, [page/access] arguments which should be an array of arguments that is passed to the function. arguments can either be static or you can use numbers to reference the URL. If a load function us used on a URL arg, like %user, referencing it will yield the return of the load function, like the user object instead of the user id (uid).

Page callbacks will receive any URL args that aren't used for pattern matching. So if you define an URL foo/bar and user goes to foo/bar/baz, baz will be added to the list of args passed to the page callback. This can be handy in some cases where you can provide a default argument that can be overridden in the URL.

If in doubt always check the api refference api.drupal.org


First of all make alter in your view and place the code.

// Set an index if there are multiple terms used.

    $index = 0;
    // Used for the array's string index.
    $string_index = '';
    // Continue for each vocabulary that is used.
    while (isset($form['tid' . $string_index])) {
        // Cycle through each of the terms.
        foreach ($form['tid' . $string_index]['#options'] as $tid => $option) {
            // Build a query to get the nodes for this term that have been
            // specified as filters.
            $query = db_select('node', 'n')
                    ->fields('n', array('title'))
                    ->condition('n.type', $form_state['view']->display_handler->handlers['filter']['type']->value, 'IN')
                    ->condition('fa.field_advertisements_value', 'forsale', '=')
                    ->condition('ti.tid', $tid, '=');
            // A quirk in db_select(). You need to add the join separately.
            $query->innerJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
            $query->innerJoin('field_data_field_advertisements', 'fa', 'fa.entity_id = n.nid');
            $results = $query->execute();
            $count = $results->rowCount();

// get the count of nodes or watever with your costom query

            $val = $form['tid' . $string_index]['#options'][$tid];
            $form['tid' . $string_index]['#options'][$tid] = str_replace("(" . $count . ")(" . $count . ")", "(" . $count . ")", $val . '(' . $count . ')');
        }
        // Increment for the next tid index in the array.
        $index += 1;
        $string_index = '-' . $index;
        //$string_index = '_' . $index;


but I'd like to actually modify the buttons and text fields at the top
  of the search page.

They do not have templates by default, because they are forms. You could create a twig template for the search form by follow this tutorial: How to manipulate forms in Drupal 8

But in my opinion, it is easier to use hook_form_alter on your .theme file and add the classes here.

This is how, the drupal default theme, Bartik changes the search button to a magnifying glass icon by adding a custom class to the submit button in bartik.theme

/**
 * Implements hook_form_alter() to add classes to the search form.
 */
function bartik_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['search_block_form', 'search_form'])) {
    $key = ($form_id == 'search_block_form') ? 'actions' : 'basic';
    if (!isset($form[$key]['submit']['#attributes'])) {
      $form[$key]['submit']['#attributes'] = new Attribute();
    }
    $form[$key]['submit']['#attributes']->addClass('search-form__submit');
  }
}

You can use Devel and use dpm($form) to see what's inside the $form array.

Example:

/**
 * Implements hook_form_alter() to add classes to the search form.
 */
function bartik_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['search_block_form', 'search_form'])) {
    $key = ($form_id == 'search_block_form') ? 'actions' : 'basic';
        drupal_set_message(dpm($form));
  }
}

Make sure you don't have the search block on the search page, other wise it will print the array for both forms and might confuse you which one is which.


Create your first list as the block view itself and give it a title
of "News".
Now add the other two lists as attachments to the block
view and set the titles to be blank.
Finally, add a "Global: Text
area" to the Header of each display, containing your "Sports",
"Politics" and "Business" titles, perhaps inside <h3> tags.


Drupal sitemap still contains urls of deleted pages

if you are using the XMLSitemap module, uninstall it and run cron to delete its tables from the database, then reinstall it, it will generate the right urls


how can i remove the login form from the home page

Try going to Admin/Structure/Blocks and set User account menu's region to None.


Take a look at http://drupal.org/project/menu_block.  It allows you to slice up your menus and might do what you need.


Is this for Drupal 7?

If so you can create a custom module using hook_menu_local_tasks_alter, maybe in the hook get the arg for the nid for the current page. Then do a node load on the current pages nid to check a reference is set, then from this reference field which will contain the nid... do another node load to get its title. Finally the title local menu tab.


Drupal 7 Ubercart Rest Services Module (API)

You could use the Bee Colony - Ubercart synchronization Web Service module.

  Bee Colony is a communication service (based on services module) for Ubercart based sites. Bee Colony allows site administrator to provide full remote control over Ubercart orders and products.

  Main objective is to build a client/server system to allow external software to synchronize its database with Ubercart.

  This project mission is to evolve Bee Colony to provide an easy and powerful way to create client-side software for companies and promote in this way Ubercart use.


Displaying multiple child-grandchild-relationships properly through Views

So you've tried going into your 'Settings' for the unformatted list style and setting a 'Grouping field' already?

If not, try the following, and make sure to check the box I've checked here as well:


How do I avoid "geo:" is removed from links?

You need to add geo as an allowed scheme. See https://blog.werk21.de/en/2017/06/06/change-list-valid-uri-schemes-drupal-8 for details.


How to run module code on a specific page/path?

You can use OAuth2 Authentication. Some details about it, from its project page:

... allows users to log into your Drupal site authenticating against a remote identity provider (IDP) via OAuth2.
That is, if a user's credentials can be used to retrieve a valid access token, he/she will be logged into the site with those credentials and the token will be added to his/her session. If the user doesn't exist yet, it will be created.


You can use the rules module for this if you don't want to write PHP.

If you want it to be an ajax event you will need to write a custom login form.

The user.module has a set of functions you can call for validation: user_login_final_validate().

I suggest rules module, save yourself some time.