How to show a list of users subscribed to the current node's taxonomy terms

You can set the same vocabulary for users and your content type, so they will be related with the same terms, then you will be able to achieve your goal with these four steps:

#1

Create a View block with these settings:

View->name: Related users
Show -> taxonomy terms -> of type -> your vocabulary

#2

Create relationship:  Taxonomy term: User using [field_name]

* field_name: the name of the field with term reference in users account settings

check: Require this relationship

#3

Add field: (field_name) User: Name

* field_name: the name of the field with term reference in users account settings

#4

Add contextual filter: Taxonomy term: Term ID

Configure the contextual settings:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

provide default value: taxonomy term id from URL

check: Load default filter from term page

check:  Load default filter from node page,  that's good for related taxonomy blocks

Select your vocabulary

Check: Filter to items that share any term

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED:

Specify validation criteria -> basic validation

Action to take if filter value does not validate -> hide view

MORE:

check: Allow multiple values

That's all. If the current node will have a relation with some user or users, then the block with the related users will be displayed.


Get entity reference node object from within rendered entity reference

You're setting $node to the current request. On any node/* route that will be the node in question, not other nodes included on the page.

Since it is an entity reference field, you can access it like (for example, in a preprocess):

$foo_id = $node->field_reference_name->value;
$referenced_node = Node::load($foo_id);

// or
$referenced_file = File::load($foo_id);

If $node->field_name->value returns the id (node id).

However it isn't really clear if you are talking about a file, or, a node.


It is necessary that you want to display this using code?

I have a better solution for you. You can try with this module Menu Block for above achievement


Entities and Plugins. What's the relationship?

I am not sure that I quite get your question but in Drupal 8 things like nodes, files and users are entities. They all inherit from ContentEntityBase. Plugins are a way to implement/extend Drupal functionality such as Views filters and Field widgets.

From the docs:

Entity API

  Drupal 7 - entities were generic stdClass objects.

  Drupal 8 - entities are now specifically typed objects, with each entity type defining a class that will be used for instances of the given entity.

  Entity types in core comes in two variants.

  Configuration Entity

  Used by the Configuration System. Supports translations and can provide custom defaults for installations.

  Content Entity

  Consist of configurable and base fields, can have revisions and support translations.

Plugin API

  Plugins are small pieces of functionality that are swappable. Plugins
  that perform similar functionality are of the same plugin type.

  Drupal contains many different plugins, of different types. For
  example, 'Field widget' is a plugin type, and each different field
  widget type is a plugin. The admin user may select from the list of
  field widget plugins to set the widget that a field uses.

After author edit:

Your specific use case would call for a event subscriber approach in my opninion. More specifically an event subscribed to the KernelEvents::REQUEST event. You can check at every page request if there are open Alert entities for the user and display them accordingly.

Your question as to if there are use cases for combined entities and plugins I wouldn't know. I only ever created Views and Block plugins and never combined entities and plugins. Perhaps you could create a Block plugin and show your Alert entities in there?


Advanced forum how to change the html without modifying the core

The easiest way to find the correct file name for your custom template files is to use the Theme Developer moduel. It allows you to point and click on anything in the browser and it tells you which part of the theme framwork rendered it and what options you have to override it.

Please note: You have to clear the theme registery after you added new templates, otherwise they are not shown.


How do I change submit URL for exposed search filter?

Seems that specific problem is with Panels.

The exposed form is basically a block which have no sense of context, therefore setting the URL from the view pane doesn't affect exposed filters in a block.

Therefore one way to go is to use hook_form_alter:

/**
 * Implements hook_form_alter().
 */
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#action'] = current_path();
  }
}

Or:

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function foo_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-foo-default') { // Or: if ($form['#action'] === '/foo')
    $form['#action'] = '/bar';
  }
}

Or by extending Views handler, for example:

class foo_handler extends views_handler_field {

  /**
   * Add to and alter the form.
   */
  function views_form(&$form, &$form_state) {

    // Submit to the current page if not a page display.
    if ($this->view->display_handler->plugin_name != 'page') {
      $form['#action'] = current_path();
    }
  }

}

Alternatively content pane can be used which can override the path, instead of using exposed form. See this issue for more details.


Odd log entries: is it indicative of an attack?, is there anything other than IP blocking that I should do?

Well continued my research and a day without no answer was enough time for me to figure it out. As I suspected yes this is an attempted attack/test. It is not specifically an attack on Drupal although it does show up in the Drupal log.

Specifically this is checking to see if your server is set up in such a way that it can be used as an open proxy; in other words if you give it a get request for a domain it doesn't serve will it GET the content from the right server and pass it on. This is bad without a login, since it lets anyone appear to be your server while they are spamming/etc - see the Apache Proxy Abuse Page.

In this case since Apache passed the request on to the virtual hosts it shows that the server is not configured as an open proxy and is safe (at least from that attack vector at this time). The server logs show a 404 as well which confirms that either the url was invalid or that there is no open proxy:

125.64.35.67 - - [03/Dec/2014:08:08:52 -0500] "GET http://6.url.cn/zc/chs/img/body.png HTTP/1.1" 404 716 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.3072; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0)"

If it was a successful attack test/attack it wouldn't appear in the Drupal logs, only in the server logs. In the server logs it would appear something like:

125.64.35.67 - - [03/Dec/2014:08:08:52 -0500] "GET http://6.url.cn/zc/chs/img/body.png HTTP/1.1" 200 716 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.3072; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0)"

with a response code that indicates a valid resource.

As to why the Drupal log strips the initial h for the message I don't know and it doesn't really matter; that being said if I have time I'll probably investigate it and submit a patch to fix it.


You should be able to get this to work using the Rules module, using a variation of the rule shown/explained in the answer to "How to make the permissions of a module more granular?". I.e in your case:

you can use the same Rules Event (Drupal is initializing), which to my knowledge is the only Rules Event you can use for this (for any other Rules Event you're just "too late", i.e. the content is already being displayed).
you can perform similar Rules Actions (to perform an appropriate redirect and display a message that fits your needs).
you should use one or more of these Rules Conditions (combined with "OR", not with "AND"!):

check if the current user's role is "anonymous".
related to your field field_module_preview.


To answer the general question how do you do that with plugins: Each plugin type is managed by a plugin manager. You can list all plugin manager classes with this console command:

drupal debug:plugin

Most plugin managers provide an alter hook to change the plugin definitions. Look in the plugin manager class method __construct for a line with $this->alterInfo():

public function __construct(...) {
  ...
  $this->alterInfo('example_plugin_info');

In this alter hook you can replace the class of plugins managed by this plugin manager:

function mymodule_example_plugin_info_alter(array &$info) {
  if (isset($info['foo_plugin'])) {
    $info['foo_plugin']['class'] = '\Drupal\mymodule\Plugin\ExamplePlugin\MyCustomFooPlugin';
  }
}

You can check the result by executing the same console command, now providing the plugin type as parameter, to list the plugins of this type and their classes:

drupal debug:plugin example_plugin

Entity type classes

About your specific question, the plugin manager for entities is EntityTypeManager (not listed by the console command because it doesn't use the standard service name scheme). It provides an alter hook to alter entity types as well, so if you are referring to the bundle entity type class of Block Content, then you can change it here:

/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['block_content_type']->setClass('...');
}


Have followed instructions to disable cache for development but it's still caching

You've disabled the render, dynamic_page_cache, and page cache bins; plugin discovery is stored in a different bin (discovery). You probably don't want to disable that bin, as it's likely to slow the site down appreciably (the project will be scanned for plugins on every request).

If you just keep in mind that you need to rebuild caches manually when you add a plugin, implement a hook, or add/change a .yml file in the module's root, you'll be able to work a lot faster.


User/register Page is not found in Drupal 6 site

Have you checked the clean URLs? There might be a problem with clean URLs.

Try www.sitename/?q=user/login.


You can create a view and add a contextual filter

Contextual filter :

Author filter :

Accept the author's name in the url :


It has been a while since I created this question, and as such I might be missing quite a few details, but I eventually did find a solution.

  TL;DR It should probably relate to NGINX, so cover all the bases related to it. NGINX's official Drupal recipe helped me a lot,
  you might want to check that first. Although, if you're using Drupal 8, you'll need to update/change some settings for it. You might find some of them here.

Can't recall much about my specific case, but this checklist might be worth checking out in your setup:

settings.php be careful and mindful of the options you have setup in your settings file. IIRC, I think the private folder path value was all I changed regarding this issue.
Drupal configuration - in Drupal's admin backend, go to Configuration > Media > File System and make sure you have the correct option selected for your use case, either public/private. This will setup your default file upload location, but can be overridden in the content type's definition, if I'm not mistaken.
Content type definition - make sure that your content type using the file field is setup properly and also according to your needs. I think at some point I even re-created my content-types just to make sure there wasn't stale info in the DB.
Drupal role permissions -  this was probably one of my biggest headaches with this issue. Make sure they are properly setup and test them thoroughly. In this process I discovered the Masquerade module, which has helped me a lot ever since.
Folder permissions - The folders you want to use for both private and public uploads should be writable by Drupal/NGINX, but NGINX should not enable HTTP access to them.
NGINX -  this is definitely the most important part. What you basically need to absolutely make sure of is that Drupal handles it's own URLs, and everything else is handled by NGINX accordingly. This can get confusing really fast, so here are some more tips:

Drupal will have it's own file URL being generated internally and saved to the DB. This should make Drupal respond and take over HTTP requests to a system/files/YEAR-MONTH-type URL.
NGINX on the other hand, must let Drupal handle those requests, while intercepting and preventing direct access to sites/default/files/private, or whatever folder you have setup for private files.
This should be fixed by setting up the correct NGINX directive regarding the path you want/need it to handle. This might help. Also, go read about Perusio's NGINX setup, as there are a lot of valuable nuggets of information there (D8's setup is equivalent to D7).
I think some specific NGINX directives may target certain file-types differently (maybe something related to MIME types, not sure). This could explain if your issue happens with, ie, JPG, but not PDF or vice-versa. Couldn't find info on this, though.

@GokulNK I'm sorry if this isn't enough help, but I really can't recall what I did to fix it. Hopefully it'll point you in the right direction, though.

EDIT: I found an old email with the webserver's maintainer discussing some NGINX directives that has some info that might be relevant:

# handled by NGINX
location ~ ^/sites/default/files/private/ {
    return 403;
}

# Handle private files through Drupal.
location ~ ^/system/files/ { # For Drupal >= 7
    try_files $uri /index.php?$query_string;
}


Add dividers for each year on View table

You can use "Grouping field" option inside view formate settings for year field. Here is example of grouping
1. https://stackoverflow.com/questions/13828952/drupal-7-views-list-group-by-field?answertab=active#tab-top
2. https://www.drupal.org/node/1578512


Custom css is not applying to bootstrap subtheme

In the Theme settings Under Bootstrap Settings, Go to Advanced -> BootstrapCDN and choose Disabled from the dropdown.

Then in the theme info file uncomment the Method 1 section. Download the bootstrap files from Bootstrap Download and extract it to the subtheme folder. The extracted folder should be named - bootstrap and should contain all the necessary bootstrap js, css files.

You may get more info from this link Bootstrap sub-theming "how to"


I have used same thing in Drupal 7 . Please check if this can help

Function custom_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  $resultTypes = array();

  // Divide results
  foreach ($variables['results'] as $result) {
    $resultTypes[$result['bundle']][] = $result;
  }

  // Create fieldsets
  foreach ($resultTypes as $resultType => $resultTypeResults) {
    $value = '';

    foreach ($resultTypeResults as $result) {
      $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));

  $variables['search_results'] .= theme('fieldset', array('element' => array('#title' => $resultType, '#children' => $value));
  }
}


How to allow arbitrary query string with url alias?

Drupal doesn't treat the query string as part of the URL alias, the problem is that your URL has the q parameter as part of it (q=dom).

Google obviously uses that for some purpose, but Drupal uses $_GET['q'] to determine the path of the page that should be shown. So when you visit a URL with q=dom in the query string, Drupal will try to find a page with the path dom...which obviously doesn't exist on your server.

Short of some crazy hacking of Drupal core (and probably dozens of contrib modules) I think the only way you're going to solve this is by somehow changing the original query string and removing the q parameter from it.


How add menu to my node programmatically?

After look into the database and some test, this is how i add a menu to my node on the creation or on node update :

For this example, i load a node :

  $nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->load(312);

  After you create the link :

$menu_link = MenuLinkContent::create([
    'title' => 'name of your menu',
    'link' => ['uri' => 'internal:/node/' . $nodeEntity->id()],
    'menu_name' => 'main',
    'expanded' => TRUE,
]);

$menu_link->save();

If you want add a parent to your menu just add this in $menu_link :

  $menu parent is the uuid of the parent menu

'parent' => 'menu_link_content:' . $menuParent,

  Then you need to update menu_link_content_data

  $this->database->update('menu_link_content_data')
            ->fields([
                'link__uri' => 'entity:node/'.$nodeEntity->id(),
            ])
            ->condition('id', $menu_link->id())
            ->execute();

The link between the menu and the node is the link__uri, you need to tell him to reference the entity node.

After that, you ll see your menu link on your node.

I haven't find better solution with Drupal API for now.


how to setup blocks that differentiate 'node edit' case from 'node add' case in MULTISTEP forms

I dont know how to retrieve the multistep completion state from a block but there's a simple way, by testing the published status (not published ? not complete ADD/PENDING - published ? complete EDIT)

in admin/settings/multistep :
select Publishing > at node completion

in the ADD block that must be displayed when adding a multistep node :
only display block on the pages below :

node/add/multistep-content-A*
node/add/multistep-content-B*
node/*/edit*

in the ADD block body :

Title : add

<?php
$show = FALSE ;
if ( arg(0) == 'node' && arg(1) == 'add' ) {
  if (in_array(arg(2), array( "multistep-content-A", "multistep-content-B" ))) {
    $show = TRUE ;
    $node = False ;
  }
}
elseif ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 0) {
    $show = TRUE ;
  }
}
if ($show) {
  if ($node) print 'id : '.$node->nid . '' ;
  print "

some info about creating this node.

be sure to complete every step blah blah the italic ones

" ;
}
?>

in the EDIT block :

Title : modify

node/*/edit*

body :

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
  if (in_array($node->type, array( "multistep-content-A", "multistep-content-B" )) && $node->status == 1) {
    print 'id fiche : '.$node->nid . '' ;
    print "

some info about editing an existing node.

browse directly to the steps you need to modify by using the link below.

" ;
  }
}
?>

there might be a way to only have one block, that could change its title itself, I didn't investigate.


run-tests.sh error: Test class not found

The solution ended up being:

Make sure the test file is named as the test class, in this case RSVPListServiceTest.php.
Make sure my unit tests are placed in the correct directory structure, in my case my RSVPListServiceTest.php file had to be in modules/custom/rsvplist/tests/src/Unit/EnablerServiceTest.php (as opposed to unit with a lowercase u)

The ERROR: No valid tests were specified. message ended up being a bit of a red herring, and I've submitted a patch to drupal to make this message clearer: https://www.drupal.org/project/drupal/issues/3170651


Remove SKU label from product reference select list

In a custom module (or theme) you could implement hook_field_widget_WIDGET_TYPE_form_alter() and alter the labels of the options (i.e., stored in the $element['#options'] variable). If I'm not mistaken your function would be mymodule_field_widget_options_select_form_alter(&$element, &$form_state, $context), where mymodule is your custom module (theme) name. Don't forget to check for which field you're altering the options, you can find this in $context['field']['field_name'].

If you don't want to write custom code, you could as an alternative use the Entity reference module in combination with Views. Hereby you can use the output generated by a view as an option list for the (entity) reference field (pointing to your product).


Restrict Drupal Search to few content types

I guess that Custom Search module can help you: http://drupal.org/project/custom_search. acording Custom Search module description:

  The module adds options to select:

* which content type(s) to search

here a snapshot of Custom Search settings related with content type configuration:

Other alternative seems to be Search Configuration module http://drupal.org/project/search_config that give to Search settings (in Additional Node Search Configuration > Only of the type(s) settings) options to filter search by content type:


How do I create a new Group after installing OG?

You have to do it in the content type. Go to a content type you would like to use as a group and you will see a fieldset Organic groups

Also check your permissions, you will have permissions for creating the content types and for administering og


Sharing files privately individual users

Drupal private files can only be downloaded by someone who has access to the node the file is attached to.

So you can set up a content type that allow an unlimited number of files attached to a node. Then you set up an Access Control List to that node, where you make sure only the specific user has access to the node.  Let the admin create one node per user, and upload all files to be shared privatly with a specific user to the user's node.

To mange access control lists to nodes, you can use Flexi Access module.


by the sounds of it, you're looking for Views Conditional module:

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

 Equal To
 Not Equal To
 Greater Than
 Less Than
 Empty
 Not Empty

  Views conditional allows you to output text based on the result of the condition.


Changing module code is usually a bad idea because it makes it hard to impossible to update to a newer version of the module.

Without knowing the structure of that module, changing the HTML/output should always be possible by overriding theme functions, which you can do without changing the original code.

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


Group by taxonomy term, show node multiple times for every reference

In the taxonomy term's settings, you need to uncheck the option for displaying the values in the same row.


A hook implementation is simply a my_module_name_function implentation.
Your module's internal name is what you have used in the .module file's name.

So for in this case, it's node_from_rss (I'd recommend you to rename the folder name to node_from_rss as well so it reduces any confusion).

If you rename your cron function to comply with the above my_module_name_function pattern, function name has to be node_from_rss_cron

function node_from_rss_cron() {
 $interval = variable_get('get_node_from_rss_interval', 60 * 60);
 if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }
}

Other than these changes, here are some of the Drupal best practices.

Drupal 7 has a REQUEST_TIME constant defined at the beginning of page processing. If this code is for D7, use it instead of time().

drupal_set_message() function sets a message to the screen. but cron functions will run without use interaction. You will not see this message unless you are running cron manually at admin/reports/status page.

Avoid placing folders such as 'node' inside sites/all/modules folder. Technically it's completely ok to do so. But I think it will confuse you and others in the long run. Usually we place modules like:

sites/all/modules/MY_MODULE/MY_MODULE.module


Actually in order for this to work you need the token filter module:

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

Otherwise there is no option in text format config.


How do I create a list of Nodes within a list of taxonomy terms, within a node?

You could create a view which will display content filtered by a category, note that the category filter should be a contextual one.

In the node, you should have a taxonomy term reference field and then in preprocess, you can create your own variable by rendering the view with a contextual filter.
The contextual filter in this case will be the value of the taxonomy term reference field.

This will handle the desired behavior but won't be as flexible. It will cover choosing a different term for each node, but you will be stuck to the same view.


Add element to form during (element) validation checks

Here's how I've got around this issue.

When defining the element, add in:

#pre_render
#form_id
#element_validate

Here's the algorithm:

User completes normal form, entering something suspect.
The validation function picks up the suspect value and stores a note that this form (uses #form_id) and element has a suspect value on a global variable. It also uses form_error() to inform the user of the problem.
The #pre_render function is called for the element. This function does not get the form object at all, which is why we specifically added #form_id to the element. Using this we can check the global variable for this form and see whether suspect data was found. It was, so add another form element in asking for confirmation. This element is not part of the Form API, so as well as the usual ('#type' => 'textfield' etc. we need to explicitly set '#name').
User confirms the data on the new form element and re-submits form.
The validation function notices the confirm data in $form_state['input'] (it won't be in values because this element is not part of the Form API's form) and compares it to the submitted value. It matches, so it does not call form_error().
Assuming no more errors, form submission continues.

I've also implemented a thing for storing the confirmed suspect value in a hidden field in case other fields fail verification, meaning the user only has to confirm the data once.

Use case

My specific use case is an email validator module. Beyond the drupal sytax check it can lookup DNS records and then conduct an SMTP conversation with a server to see if mail is accepted. Some of the SMTP errors can be temporary and so we use this chance to tell the user "hmmm. we got this error (user-friendly version of error goes here) - might be a temporary thing but can you double check your email?" allowing them to complete the form while still helping them avoid typos.

My email_validator module on github


Simplenews automatically send out email notifications when new content is published

Recommend to try the Newsletter module. This may also help you.
This may also be another solution for you.


Scald : How to add several medias to a node using entity metadata wrapper?

Your issue is that your field_atom field is not configured as multiple.

When it's not, an EntityDrupalWrapper object will give you direct access to the field, instead of having to go through the 0 delta.

Just fix the field_atom options to accept multiple medias, and your code will work fine.


It all depends on what you want to do exactly.  I have a block that is dependent on the user thats logged in, and it may also be changed from time to time based on some other code being run.

In this example

'#cache'=>[
        'contexts'=> [
            'user',
            'route',
        ],
        'tags' => [
          'Block:smn',
        ],
      ],

It gives it context for which to cache and the tag allows me to invalidate the cache for just this block if I run some other code that will affect what is rendered

in this example if some entity is deleted i use hook_entity_delete

function foo_entity_delete($entity){
    $cache = \Drupal::service('cache_tags.invalidator')->invalidateTags(array('Block:smn'));

}

and my block will be removed from cache and the next time I visit the page it will be rendered with new information.

for more info on tags, and contexts you can cache with:
https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x


How can I get the currently submitted form state in a block on the same page?

As with most things you are learning. The answer is often simpler than first thought.

To resolve my issue I was able to use hook_form_alter and implement my own submission handler.

From here I was able to disable the redirect to prevent the page reloading.

Once redirect was disabled then my block plugin was able to get access to the form and use the validated results within it.

My block build for demo purposes contained the following

public function build() {

  // Get the current form.
  $form = \Drupal::formBuilder()->getForm('Drupal\modulename\Form\moduleForm');

  return [
    '#markup' => "<pre>" . print_r($form, TRUE) . "</pre>",
  ];
}

The important point is \Drupal::formBuilder()->getForm('name') returns the cached form results and therefore does not require any further validation.

This can be verified by checking $form['#validated'] == 1.


hook_block_view_MODULE_DELTA_alter gets fired twice

I faced a similar issue recently and the problem was the team had created both a module and a theme with the same name so Drupal was executing the same hook twice (once for the module and once for the theme). Renaming the theme solved the problem.


Simpletest assertions are working on user created in Simpletest with $this->drupalCreateUser().


UPDATE

You might also try Drupal Console's drupal config:export:content:type command.

It's description says:

  The config:export:content:type command Export a specific content type
  and their fields.

Content types and Fields are 2 separate configuration in Drupal 8, so if you want to export content type with fields you have to export all it's fields configurations too.

Features module might be helpful for grouping configurations, it's not stable yet, I haven't tried it but I think it might worth trying.


How to change a views block ID attribute to use it as anchor

you should place this function in your themes/YOURTHEME/YOURTHEME.theme file:

function YOURTHEME_preprocess_block(&$variables) {
  dump($variables);
}

and you will see the name of your block. You have to look for block_html_id. Based on your description the value of the block_html_id will be block-views-block-services-block-1.

Then you can simply owerdefine it this way:

function YOURTHEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-block-services-block-1") {
    $variables['block_html_id'] = "services";
  }
}

Or you can create a custom module and you can put this function there too. In that case you have to replace the YOURTHEME to the name of the custom module.


How to resolve the warning on my homepage, after deleting mini panel?

It seems like your problem is caused by what is detailed in the issue about PHP 5.3.9 Strict Warning on Panels Empty Value. It was first reported in Panels 3.2, and has status 'Closed (Fixed)'.

The patch in comment # 15 of it should help you resolve the error. And according to comment # 26, this patch is included as of Panels 3.4.


What you want to do is create a sub-theme so that updating your contributed theme does not overwrite custom changes you've made.


What I understood from your question and comments, you are looking String Overrides module.


Redirect customer to specific order checkout later

Sounds to me like the sandbox isn't using pricing rules to set the "new offer."

Here's what I would do (without knowing what the sandbox is doing):

I would create a custom line item type using commerce_custom_product
I would then add a price field called "price_override"
I would then create a pricing rule that overrides the original price of the line item with the "overridden price" if it exists.
I would then make sure that the sandbox or a custom module sets that line item field when a new offer is made

The above approach has the benefit that the price is actually using pricing rules, but the "custom price" is per-line-item instead of per-order. Now it might be possible, depending on how the sandbox is functioning, to access the "custom pricing" and use it in a pricing rule. But the same approach would still be taken above.

// Edit

You can always just send users to "/checkout" ... but likely they would need to be logged in first to be connected to their order (this would be based on default permissions). So I would use the Drupal system to your advantage, this little link will present anonymous users with a login form, then redirect to checkout (and will simply redirect to checkout if logged in):

/user/login?destination=checkout


Printing current node workflow state name as the page body classes

I think once you get the node object in your preprocess function then you will be able to add the class. Body classes are only applied in template_preprocess_html so you can do the following,

function sattari_preprocess_html(&$vars) {
  // If on an individual node page, add the node type to body classes.
  if ($node = menu_get_object()) {
    // debug($node);
    // Change as per your node object values added by workflow module.
    $variables['classes_array'][] = drupal_html_class('node-status-' . $node->status);
  }
}

For more reference have a look at template_preprocess_html


How to deal with Bubbleable Metadata when there's no rendering context and no render array

Yes, when rendering email data you have to take care that you don't bubble up metadata to the render context of the main response.

There is a third option, and in most cases the best option: The method Renderer::renderPlain, which not only discards bubbleable metadata, but also makes sure your email doesn't contain leftover placeholders:

  Renders final HTML in situations where no assets are needed.

  Calls ::render() in such a way that placeholders are replaced.

  Useful for instance when rendering the values of tokens or emails,
  which need a render array being turned into a string, but do not need
  any of the bubbleable metadata (the attached assets and cache tags).

  Some of these are a relatively common use case and happen within a
  ::renderRoot() call, but that is generally highly problematic (and
  hence an exception is thrown when a ::renderRoot() call happens within
  another ::renderRoot() call). However, in this case, we only care
  about the output, not about the bubbling. Hence this uses a separate
  render context, to not affect the parent ::renderRoot() call.

  (Can be executed within another render context: it runs in isolation.)

And it's always a good idea to build a render array to produce HTML. For example if you have a formatted text field then build a processed text render element: How to safely render node body on a custom variable?


"Unable to send e-mail" Error in drupal 7

It's very likely that your new server does not allow mail to be sent from the web service.   This could be because it blocks the SMTP port, or because it doesn't allow PHP to use mail().  You should be able to contact their tech support to ask.  If not,  you can try uploading your own PHP script that uses the mail() function and see what errors it gives you.

IMO, this is a good thing... web servers shouldn't be sending emails for a variety of reasons.

I would recommend using something like this:  https://drupal.org/project/smtp

It will let you send email through a real email account, of course you'll have to make sure there's not a block on the port it uses.


Check if there are a user with uid=0 in users database table.
If not, just add a new row with 0 uid and it'll resolve the problem.
Good luck!


Adding a field to a content type for Apache Solr search and Facets

Figured it out. Adding the answer in case anyone else needs it. Code below...

function issue_archive_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id) {
  if($node->type == "article") {
    $node = node_load($node->nid);
    $journal = node_load($node->field_journal['und'][0]['target_id']);
    $document->addField('its_field_year', $journal->field_year['und'][0]['value'] + 0);
    $document->addField('itm_field_year', $journal->field_year['und'][0]['value'] + 0);
  }
}

function issue_archive_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  $query->addParam('qf', 'its_field_year');
  $query->addParam('qf', 'itm_field_year');
}

Using the solr_devel module, I saw that the journal type had two fields listed in the entity/document for year, one with the its_ prefix, and the other with the itm_prefix. I added both of those, and added the query field (I think that's what it stands for?) parameters to the query.

This got me the exact results I was looking for.


How owerride entity node delete core function

The only way I can think to do this is to override the entity's storage handler in hook_entity_type_alter() with a storage handler that provides the delete functionality you want.

Something like

// You're going to want to be sure you're extending the entity's original
// storage handler.
class CustomStorageHandler extends EntityStorageBase {

  /*
   * {@inheritdoc}
   */
  public function delete(array $entities) {
    array_filter($entities, function ($entity) {
      // Do your logic to determine if the entity should be deleted here.
      // This example only allows entities with odd ids to be deleted.
      return (bool) $entity_id % 2;
    }
    parent::delete($entities)
  }
}

It is probably a better idea, however, to use the entity's access system to prevent users from deleting entities as it will be confusing to try to delete an entity, then for that to not happen.


How can one automatically rename files uploaded in a webform?

The sandbox project is removed as the issue queue get continued, the latest patch has been failed in simpletest, but you can still check this patch


How to send user created articles to approval queue?

I'm not sure this is what you need but maybe you can achieve this using Rules. I've created a rule for nodes of type 'forum topic' and this is an example:

Event: Before saving content of type your type
Conditions: Data comparison -- Parameter: Data to compare: [node:is-new], Data value: true
Actions:

Conditional

If: User has role(s): Parameter: User: [node:author], Roles: new, Match roles: any

Set a data value: Parameter: Data: [node:status], Value: Unpublished
Show a message on the site: Parameter: Message: your message, Message type: Warning, Repeat message: false

The exported rule:

{ "rules_forum_needs_approval" : {
    "LABEL" : "Forum needs approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "rules_i18n" ],
    "ON" : { "node_presave--forum" : { "bundle" : "forum" } },
    "IF" : [ { "data_is" : { "data" : [ "node:is-new" ], "value" : 1 } } ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "user_has_role" : {
                "account" : [ "node:author" ],
                "roles" : { "value" : { "14" : "14" } },
                "operation" : "OR"
              }
            },
            "DO" : [
              { "data_set" : { "data" : [ "node:status" ], "value" : "0" } },
              { "drupal_message" : {
                  "message" : "[node:title] needs approval.",
                  "type" : "warning",
                  "repeat" : 0
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


How to alter node url or toUrl function output?

Path outbound processing still exists: OutboundPathProcessorInterface, check the implementations, like path alias handling. It's a tagged service.

That said, not sure if that's the approach that I'd take, I usually implemented something like that simply by overriding the necessary node templates/preprocess.


How do I pass a context filter to a block loaded by ajax?

If the block you generated uses a contextual filter, maybe this could be the answer: https://drupal.stackexchange.com/a/205731/98697


Is it possible to get  form submission diff with Diff module

Problem is - diff compares entities and their revisions. But node_form_submit() happens before revision is created. If you will inspect node_save, you will see no hooks are called after actual save.

To get your code executed and be sure revision is there, it would be tempting to use Rules, but existing bug "After updating existing content" runs before content is saved. shows it has just the same issues as hooks. Maintainers say:

  We just rely on the hooks drupal provides us here.

So now you have 2 options:

Give up on using diff module and just borrow some of it's code (it's open source after all)
On save, set a hidden field "test with diff" to true, and on cron make actual testing. With */5 minutes CRON it will be almost as good, as instantaneous test.


Does Apachr Solr use Taxonomy or CCK fields for faceted search?

Out of the box, apachesolr.module 6.x and its friends can facet on taxonomy and cck text fields (with certain limitations). You just need to enable the desired facets in the settings, having made sure that the vocabulary is actually connected to your content type in the vocabulary settings.

For price range / any numeric range faceting I have not found a working contrib module. There is a module though, http://drupal.org/project/apachesolr_facetbuilder which allows you to build at least categorized facets for your numeric values.


Is there a difference between "Clear cached data" button on the performance page and drush cc all?

Short answer:  There is no significant difference.

Drupal:

function system_clear_cache_submit($form, &$form_state) {
  drupal_flush_all_caches();
  drupal_set_message(t('Caches cleared.'));
}

Drush:

function drush_cache_clear_both() {
  drush_cache_clear_drush();
  if (drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL)) {
    drupal_flush_all_caches();
  }
}

Both end up calling drupal_flush_all_caches, which clears the standard Drupal caches, cached CSS/JS files, and everything declared by a hook_flush_caches.

drush_cache_clear_both is what is called by 'cc all'.  drush_cache_clear_drush clears some drush caches that have no effect on the Drupal site.


You can try something like this:

 $form['sample'] = array(
     '#type' => 'item',
     '#markup' => print_r($sample_values, TRUE),
 );

or simply just

print_r($sample_values);

or install Devel module and use dsm function.

dsm($sample_values);

UPDATE:

Try this:

$form['sample'] = array(
    '#type' => 'item',
    '#markup' => print_array_values($sample_values),
);

Then declare the function below:

function print_array_values($sample_values){
    $content = '';
    foreach($sample_values as $val){
            $content .= '<div>' . $val . '</div>';
    }

    return $content;
}


Generate h1 et h2 inside link with theme function

You need to set the html-Option of l() to true:

l( $date, '', array(
  'fragment' => $vars['timelinr_dates_id'] . '_' . $i,
  'external' => TRUE,
  'html' => TRUE
));

Otherwise all html-tags get escaped by l().


How to resend same newsletter from Simplenews?

Perhaps easier to clone and then resend the newsletter node with the node_clone module.

The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy.


How to pass views link as a variable to a node?

Have a look at the Rules Link module to generate a custom link that can trigger a rule (from the Rules module). So that via the Rules module you can then implement your logic about the "specific node and that variable" that you mentioned in your question.

Some more details about the Rules Link module (from its project page):

  This module lets you create links which trigger arbitrary functionality with the help of Rules.

  Features

  Attach the link to any entities.
  Show the link only for certain bundles.
  Narrow the entities on which the link will be shown using the visibility conditions.
  The links are usually displayed using Views.
  For entities that can be displayed, the links can be shown on node view.
  Supports an arbitrary number of additional Rules parameters for passing context via Views.
  3 types of links: Javascript, Normal and Confirmation form links.
  Use individual permissions for each link.


How to show taxonomy terms' description field on a node/add form instead of term title only in drupal 7?

The following solution slightly alters your requirement. Instead of having the term description field showing up as part of the term select widget, create a view block set to be visible on node/add pages which provides a table listing of each term and its description field.

To do this, create a new view of type "Taxonomy." It will have two fields: taxonomy term, and taxonomy term definition.

You could put help text associated with term_reference field which alerts the user to the block which holds the terms and description.

It would be very difficult to alter any select widget to include the description field in a way that wouldn't make a mess of the page.


Mapping a csv field to Meta Title and Meta Description using feeds and metatag

You could create fields for the metadata, hide them in "Manage display" and map them to the Metatag module (add the field tokens as content), as I described in the answer to "How can to make required the fields keywords and description of the metatags module?".

Now in your CSV import you add the metadata to your manually created fields, and the Metatag module will fetch the content.


Is there a more performant alternative than overriding template files?

You can eliminate unnecessary markup through the Views UI.

When you add a field, hidden under Style Settings, they always have this default unnecessary checkmark

Also, you can remove more markup here

and here


how to remove all slashes from all path aliases

one solution is using Views Bulk Operation, create a view  and with using  run arbitrary Php option in VBO try to remove all / from aliases,

something like ( I didn't test this )

  $entity->path['alias'] = rtrim($entity->path['alias'] ,'/');

and another and faster solution is using MYSQL TRIM in order to  update in database
go to phpadmin my admin ( or mysql command line ) and  run below command

 UPDATE `url_alias` SET `alias`= TRIM(TRAILING '/' FROM `alias` )


Apache Solr own grouping in autocomplete

You can try to write your own query according to results you want to get.
below link may help you in this.

https://www.drupal.org/node/2203775


How to set which node a module loads on?

Check the current user having admin role, if you are using drupal superadmin, then check current logedin user's id equals 1.

<?php
  function custommodule1_user($op, &$edit, &$account, $category = NULL) {
    global $user;
    if($op == 'update') {
      if (in_array("administrator", $user->roles) || $user->uid == 1) {
          // Show message that only for admin.
          // Do whatever you want do for admin.
          drupal_set_message('You are Administrator you are allowed to send data');
      }
      else {
          // Show message for author users.
          drupal_set_message('Sorry you do not have the rights to send data');
      }
    }
  }
?>


How to change the text of the "checkout" button in Drupal commerce cart?

By using the hook_form_alter() function, you can change the text of the buttons. It would be something like

$action['#value'] = 'continue';

Please provide us with more code so I can work out a decent example.


The Solr server could not be reached. Further data is therefore unavailable

Maybe your path for solr is wrong. If you setup solr by drupal instructions then your solr path must be:
/solr/drupal


Custom image style is not honored on new content

Images are only rendered to a given style when something actually tries to use that style. If you want to force generation, you need to use image_style_url to obtain URL for the image, and then download it via regular HTTP request. It becomes more complicated if you don't want to download (aka show) it. In that case, use image_style_deliver.


In your development.services.yaml file set twig debug to true and disable the cache by setting value to false.

After that you will see theme suggestions by inspecting element in browser.


How to perform a redirect based on the value entered in a Webform component?

You can achieve by altering the Webform.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'YOURFORMID') {
    $form['#submit'][] = 'ctm_redirect';
  }
}

function ctm_redirect(&$form, &$form_state) {
  if (CONDITIONS) {
    $form_state['redirect'] = 'foo';
   }
   else{
     $form_state['redirect'] = 'bar';
   }
}

You can also check Webform Rules module.

This module adds rules integration on webforms.

  Did you ever want to react on webform submission using rules but
  couldn't find the proper event? Webform Rules makes it possible to
  catch webform submissions by rules and do whatever you'd like to do
  with it (meaning: do whatever rules let you do with it).


Entities are statically cached in memory, so there is no performance impact if you load the same entity multiple times within the same request.


How do I use hook_preprocess_page_title() on a Bootstrap subtheme?

How do I add hook_preprocess_page_title() in a Bootstrap theme?

In your sub-theme's .theme file you add:

/*
 * Implements hook_preprocess_page_title()
 */
SUB_THEME_NAME_preprocess_page_title(&$variables) {
  // your logic goes here
}


why not redirect to another page after form submit

If that's a node form, the problem is the node submit handler sets the redirect already in node_form_submit

If you want to redirect to checkout after a node form submit, you can do it by adding a submit handler to the $form['actions']:

/**
 * Implements hook_form_alter
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'NODE_TYPE_node_form') {
    $form['actions']['submit']['#submit'][] = 'MODULE_NODE_TYPE_submit';
  }
}

/**
 * NODE_TYPE submit handler
 */
function MODULE_NODE_TYPE_submit($form, &$form_state) {
  // You don't need order_id as /checkout will route to the correct location for user
  $form_state['redirect'] = 'checkout';
}

Note: You could also do it with Rules.


Adding Content to the top of a form Page

Create a simple block (/block/add?destination=/admin/structure/block/block-content) and make it appear on the form's page.

If you can not setup the necessary restrictions for the block to appear, you have to go for hook_form_alter (but this means programming your own module).


Activate menu item with preprocess_page function

I would suggest looking at the Menu position module


Create a page filter with the last article of each category

Yeah that's possible.

Add a new taxonomy view
Add a relationship: Representative node.
There configure to sort by node created DESC.

That's it


How to use other properties in hook_entity_property_info_alter()

If you use hook_entity_property_info_alter() you have access to the entity in question in the callback as well.

function mymodule_callback($item){
  //$item is the entity in question in my case $og_membership
  //hence I can acces the gid like this:
  $og_membership = $item; //redundant, just to show what I mean
  $gid = $og_membership->gid;

  //either do some more stuff or just return the gid as an example
  return $gid;
}

Now I can access the property and it returns the gid. For example in rules:

[og_membership:og_custom_property]

Hope this is useful to others as well.


First, I would suggest using the Backup and Migrate module to move Drupal databases between hosts. That may solve your line breaks issues, and YMMV, but loading Drupal dbs via other MySQL methods can cause other issues.

Second, have you tried setting the $base_url config variable on your production server? You shouldn't have to change URLs in the SQL files. It's a best practice to use relative paths in content. There are modules/filters that will convert them to absolute paths on the fly.

Cheers!


Ok, so I have now realised that the Members tab I displayed above for the site admin, was actually just a tab to show the User-Group relationship, which in way no way links to the user's profile.

So I've applied a solution (which I'm happy with) using Views module. For now I'll just link to my pastebin for this and explain the solution a little later.


I think it is best to create a hook_preprocess_node in your custom module. There, you can check the node id and call the required functions.


Flag, flag link, and flagging: create an advanced relationship

Using Drupal rules module you can set up the right triggering conditions. It is possible to use rules to alter the data in fields arbitrarily, however your question is a little confusing because bands are also described as users, so you would need to make use of user related fields in the rules configuration. Take a look at the large rules documentation section and this intro to the rules module to get an idea. Flag module is compatible with rules.


This is a known issue in views.

The issue is that the route parameter for entities needs to be named:

  This view will be displayed by visiting this path on your site. You
  may use "%" or named route parameters like "%node" in your URL to
  represent values that will be used for contextual filters: For
  example, "node/%node/feed" or "view_path/%". The named route
  parameters are necessary when used within paths used by entities such
  as "taxonomy/term/%taxonomy_term" or "user/%user/custom-view

This is for the first error message.

The second one is caused by the devel module. If you still get this error after renaming the route parameter, you have to check the issue queue from this module.


Get field names of view from within module

There is an array of fields in the display object:

$view->display['YOURDISPLAYNAME']->display_options['fields']

for example if you want to retrieve list of field names of the view arbitrary display, you'd need to do something like this:

function get_views_field_names($view_name, $display = 'default') {
   $view = views_get_view($view_name);
   $result = array();
   foreach($view->display[$display]->display_options['fields'] as $field){
       $result[] = $field->label;
   }
   return $result;
}

and somewhere in the code

$fields = get_views_field_names('YOURVIEWNAME', 'YOURDISPLAYNAME');


<?php
public function behave() {
  $account = \Drupal::currentUser();
  if ($account->id() == 1) {
    return "Hi, boss!";
  }
  else {
    return "You are not the site administrator.";
  }
}
?>

Note that in neither case is the value an actual User object. Rather, as of Drupal 8 it is a UserSession object, which duplicates some, but not all, of the information of a user. It may also represent the Anonymous User rather than a saved User entity. See link for more information.


How to change non-color-related CSS after the color module has been used?

Resave the color settings in the theme; see color_scheme_form_submit().

I'll look into what can be done inside the AdvAgg module: https://www.drupal.org/node/2461039

Edit: I've added this into advagg now. It will regenerate the color css.


How to create a Webform pre-build option list via a query to an external database?

I changed this:

function webform_pre_build_list_db() {
db_set_active('external_db');
return db_query('SELECT id, name FROM table')->fetchAllKeyed();
db_set_active('default');
}

to this

function webform_pre_build_list_db() {
  db_set_active('external_db');
  $options = db_query('SELECT id, name FROM table')->fetchAllKeyed();
  db_set_active('default');
  return $options;
}

And it's working!

(Explanation: return immediately ends the execution of a function, in this case before db_set_active() could be called.)

Thanks to Nevets


slideshow module where editor can upload images

There are many options, but I am rather fond of Views Slideshow

It allows you to create a slideshow from a view. What is nice is this basically means the possibilities are endless. Plus, it allows your user to easily upload images, assuming of course you have created a content type they can use.


In views, how to create link to field visible through relationship connection?

You need to have the path field set to use the story relationship. http://cl.ly/372U1S1b2s3V


Is there a way to disable username for logging in?

I don't know of an existing module that does this, but it would only take a few lines of code in a custom module to get the effect you're looking for:

function MYMODULE_form_user_login_alter(&$form, &$form_state) {
  // Add an extra validation step to the form.
  // The user is actually authenticated during the validation stage
  // so we have to make sure this validate function runs before any others
  array_unshift($form['#validate'], 'MYMODULE_user_login_validate');
}

function MYMODULE_user_login_validate($form, &$form_state) {
  // Make sure the provided username field is in the form of an email address.
  // If not we can safely say the user shouldn't be allowed to log in,
  // regardless of whether or not a user exists with that username.
  if (!valid_email_address($form_state['values']['name'])) {
    form_set_error('name', 'The email address you have entered was not found in the system.');

    // Empty the name variable so further validation definitely fails.
    // There are probably better ways to do this so be creative :)
    $form_state['values']['name'] = '';
  }
}


how can I manipulate functionality or the structure of an existing form?

You should separate functional and visual changes.

All the functional changes should done by hook_form_alter and the rest with preprocess functions (if needed) but rather with twig.

If you use devel module, you can use the kint() function in twig, so you will see you can also filter page.content. But if that's not enough you can make an own template to this particular form, you will need twig debug enabled, which will show you HOW TO change a part of the dom (once again preprocess function and template naming convention suggestions).


Your data-fetching logic should be in its own service(s).

Symfony and by extension Drupal are not traditional implementations of the MVC architecture as there's no separate Model layer, like for instance in CodeIgniter.

One of the most important features in Symfony and Drupal are services, which are (or should be :p ) independent and reusable implementations of various functionalities.

So if you want data-fetching logic, then you can create your own service that does that and use that service in your controller, instead of polluting it with the queries (entity queries or otherwise).

I'll leave with a comment from Fabien Potencier (the creator of Symfony):

"It's up to you to create your model by hand or use any other tool, like an ORM" [...]I don't like MVC because that's not how the web works. Symfony2 is an HTTP framework; it is a Request/Response framework."

This statement might be debatable, but what I want to show here is the intent behind the choice of leaving out a well defined Model layer.


Installation profile - Can I create nodes via yml files? What's the best practice for it?

That's exactly what the Default content module was built for:

  Default content gives your module and install profile a way to ship default content as well as configuration.

I'm not sure it supports YAML, but definitely JSON and others, so it's basically the same thing.

The docs can be found here.


If you've got it working with entity_view, you probably just need to use:

print render($entity);

where $entity is the render array returned from entity_view.


Passing in URL parameters to menu callbacks

The drupal menu system does not care about $_GET arguments, you can do whatever you want with them, it doesn't affect the hook_menu() implementation **.

So, the error lies somewhere else. The result of hook_menu() is stored, it is not called on every page. If you change/add anything in that function, you need to rebuild the menus. The fastest way to do that is using the drush command "drush cc all" or "rebuild menus" in devel.module's Development links block. You can also submit the modules page, though.

** That said, it is much more common to pass arguments through the menu system as additional path arguments. Anything passed after the path will be passed as arguments to your page callback automatically. So calling user-login/2/3/sd7wdah will pass these three arguments to your function as user_login_callback(2, 3, 'sd7wdah'). You can also make these arguments required by specifying the path like this in hook_menu(): user-login/%/%/% and defining the path arguments like this: 'path arguments' => array(1, 2, 3),. This will make sure that your function can only be called with these three arguments and that they aren't optional.


Author name in comment preview not rendering apostrophe properly: a bug or by-design?

Interesting problem to solve ... Here are the findings of above problem.. I do see this issue in latest Drupal..  I believe it's a bug since check_plain method is not used in any other comment rendering features where as we can see proper name while viewing comment...

Comment preview is rendered from comment_preview function defined in 2062 Line in comment module..

/**
 * Generate a comment preview.
 */
function comment_preview($comment) {
  global $user;

  drupal_set_title(t('Preview comment'), PASS_THROUGH);

  $node = node_load($comment->nid);

  if (!form_get_errors()) {
    $comment_body = field_get_items('comment', $comment, 'comment_body');
    $comment->format = $comment_body[0]['format'];
    // Attach the user and time information.
    if (!empty($comment->name)) {
      $account = user_load_by_name($comment->name);
    }
    elseif ($user->uid && empty($comment->is_anonymous)) {
      $account = $user;
    }

    if (!empty($account->uid)) {
      $comment->uid = $account->uid;
      $comment->name = check_plain($account->name);
      $comment->signature = $account->signature;
      $comment->signature_format = $account->signature_format;
      $comment->picture = $account->picture;
    }
    elseif (empty($comment->name)) {
      $comment->name = variable_get('anonymous', t('Anonymous'));
    }

    $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
    $comment->changed = REQUEST_TIME;
    $comment->in_preview = TRUE;
    $comment_build = comment_view($comment, $node);
    $comment_build['#weight'] = -100;

    $form['comment_preview'] = $comment_build;
  }

  if ($comment->pid) {
    $build = array();
    if ($comments = comment_load_multiple(array($comment->pid), array('status' => COMMENT_PUBLISHED))) {
      $parent_comment = $comments[$comment->pid];
      $build = comment_view($parent_comment, $node);
    }
  }
  else {
    $build = node_view($node);
  }

  $form['comment_output_below'] = $build;
  $form['comment_output_below']['#weight'] = 100;

  return $form;
}

As you can see

$comment->name = check_plain($account->name);

Comment name is rendered using above statement which takes $account->name as input and wraps using check_plain function which "Encodes special characters in a plain-text string for display as HTML."

Coming to the solution..

Comment Preview is rendered using Comment_view Function which gives us hook "hook_comment_view"
By Implementing above hook in your custom module you can check for $account->name and use htmlspecialchars_decode to decode back to original value...


You need to associate content with that term.. To do that create a field term reference in content type.. And then edit your content and select term which you would like to associate with your content..

Login as admin
Navigate to list of content types "admin/structure/types"
Choose content type using which your are creating content. Click on Manage Fields next to it.
Add Term Reference field and choose Vocabulary Categories in settings
Create Content or Edit your existing content to associate terms to content using above field you have created.


How to customize the subject of a Commerce order confirmation e-mail?

In a custom module you can try something like:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(array &$message) {
  // Order receipt.
  if ($message['id'] === 'commerce_order_receipt') {
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $message['params']['order'];

    // Change the email subject.
    // @todo Remove this if/when it becomes configurable.
    //   https://www.drupal.org/project/commerce/issues/2924159
    $message['subject'] = t('Some other email subject #@number', [
      '@number' => $order->getOrderNumber(),
    ]);
  }
}


There is none, and there probably will not be one. Drupal is modularised, pluggable system. Each and every module can provide it's own field types, validators, widgets. They have custom settings defined in their modules. There are per field settings, and settings specific for a field in a given content type. Module to provide it all on one screen would need to know about all these modules and their form elements, and there are no hooks for that now. It would be a big job to hack it together with what's provided.


I think I found the answer:With the use of Taxonomy manager module,I can move the term to another vocabulary(selecting Double Tree),and when I need the term I can again move to the original voacabulary.
cheers


Transliteration- Is it possible to transliterate filenames (and update the DB) after files have been uploaded?

As far as I am able to tell, the script works OK with Unicode.

But the script doesn't sanitize the file names, and that is what invalidates the query.

It could be a a lot worse. If somebody uploads an image named image'); DROP TABLE *;--.jpg, and you use that script, they would erase your site (as shown in the XKCD cartoon below):

Source: xkdc - Exploits of a mom

I would strongly advice postponing the use of that script until somebody who understands database security has cleaned it up.

Suggestion: hand edit the file names with quotes in them by removing the quotes, and edit the corresponding names in table file_managed.

I am also puzzled that the Drupal file upload module does not sanitize file names by not permitting quotes in file names.


How to add an extra field in file upload widget?

This module might be a great way to do what you want. The File Entity module is a module that creates fieldable files. Try to read the module description, hope it helps you.

  File entity provides interfaces for managing files. It also extends
  the core file entity, allowing files to be fieldable, grouped into
  types, viewed (using display modes) and formatted using field
  formatters. File entity integrates with a number of modules, exposing
  files to Views, Entity API, Token and

UPDATE now you want to add an entity reference field on your content type that references your custom file.


Webform show custom composite result at their own line in submissions download

I solved the above issue by creating a new Webform Exporter plugin, extending the default "Delimited text" in a custom module. I assume you download them in either CSV or MS Excel file format. I've only tried the below for the CSV export, but I see no reason for it not working for MS Excel ones as well.

The idea in a short summary is:

Create a custom WebformExporter plugin extending the default "Delimited text" exporter (class DelimitedWebformExporter)
Override the writeSubmission method which adds the data to the CSV string and make it run once for every sub-element of your composite element

How to create a custom WebformExporter plugin

In a custom module, create the file

<custom_module_root>/src/Plugin/WebformExporter/CustomDelimitedWebformExporter.php

And in it create a class CustomDelimitedWebformExporter with the necessary annotations in order to define the WebformExporter plugin. Also since we want to extend the default exporter for delimited text, our class should extend the "Delimited text" class DelimitedWebformExporter.

<?php

namespace Drupal\custom_module\Plugin\WebformExporter;

use Drupal\webform\Plugin\WebformExporter\DelimitedWebformExporter;

/**
 * Defines a delimited text exporter.
 *
 * @WebformExporter(
 *   id = "custom_delimited",
 *   label = @Translation("Custom Delimited text"),
 *   description = @Translation("Exports results as delimited text file, splitting the composite element's multiple values to different rows."),
 * )
 */
class CustomDelimitedWebformExporter extends DelimitedWebformExporter {

}

If you did this correctly you should see (after clearing cache) a new option in the "Export format" dropdown in the Results Download page of the webform.

How to override the submission writing to loop for each subelement

Now override the writeSubmission method. That method in the parent class builds a new row of results for each submission and then puts the data in the CSV handler. Since we want the results in different rows, we therefore need to call the parent method just as many times and print each subelement.

use Drupal\webform\WebformSubmissionInterface;

const COMPOSITE_ELEMENT_KEY = 'composite_element_key';

/**
 * {@inheritdoc}
 */
public function writeSubmission(WebformSubmissionInterface $webform_submission) {
  $element = $webform_submission->getElementData(self::COMPOSITE_ELEMENT_KEY);
  if ($element) {
    for ($i = 0; $i < sizeof($element); $i++) {
      $webform_submission->setElementData(self::COMPOSITE_ELEMENT_KEY, [0 => $element[$i]]);
      parent::writeSubmission($webform_submission);
    }
  } else {
    parent::writeSubmission($webform_submission);
  }
}

A couple of notes:

The above works for one specific composite element in your webform. You can adjust the behaviour if you need it for more that one or for an arbitrary one (i.e. by checking if the element type is composite)
As the above does not change anything for the rest of the webform's elements, the rest of the columns in the results will have their data copied in every extra row created.

End result

<?php

namespace Drupal\custom_module\Plugin\WebformExporter;

use Drupal\webform\Plugin\WebformExporter\DelimitedWebformExporter;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Defines a delimited text exporter.
 *
 * @WebformExporter(
 *   id = "custom_delimited",
 *   label = @Translation("Custom Delimited text"),
 *   description = @Translation("Exports results as delimited text file, splitting the composite element's multiple values to different rows."),
 * )
 */
class CustomDelimitedWebformExporter extends DelimitedWebformExporter {

  const COMPOSITE_ELEMENT_KEY = 'composite_element_key';

  /**
   * {@inheritdoc}
   */
  public function writeSubmission(WebformSubmissionInterface $webform_submission) {
    $element = $webform_submission->getElementData(self::COMPOSITE_ELEMENT_KEY);
    if ($element) {
      for ($i = 0; $i < sizeof($element); $i++) {
        $webform_submission->setElementData(self::COMPOSITE_ELEMENT_KEY, [0 => $element[$i]]);
        parent::writeSubmission($webform_submission);
      }
    } else {
      parent::writeSubmission($webform_submission);
    }
  }

}


You are using "Text formatted" for your description field, so the
 tag is most likely part of the field value (an editor also could enter

Dramatically create 24/7 paradigms via ubiquitous information.

 in that field). It will be much easier to achieve your desired output if you change the description field to plaintext or unformatted long.


Is there a CKeditor / Drupal module that allows for a one-button image upload (without requiring Flash)?

The Insert module should be perfect for this https://www.drupal.org/project/insert

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

  This module was previously known as FileField Insert.


Auto-upload image feature with image browser module (e.g: Image picker)

Not sure it would help, because I don't know what you mean by "auto" uplaod, but here is the configuration I use:

FileField Sources module
https://drupal.org/project/filefield_sources

with IMCE module:
https://drupal.org/project/imce

FileField source is pretty usefull to present user a set of upload options for a single image field.


Where is a UI-configured Views display definition read from?

The table {views_view} has the list of views.  The more or less matches up with what is on admin/structure/views, except for views created by modules.

The table {views_display} has displays for each view, keyed to {views_view} with the vid column.  The id column is the machine name from admin/structure/views/view/foo/edit.  There is one row per display.  The display_options column has a serialized version settings from the edit form, and it more or less matches up with the display section when you export a view from admin/structure/views/view/foo/export.  I am also pretty sure that the actual query is essentially built up from the same column.

In my years of using a sledgehammer to make Drupal do what my clients need, I don't recall ever poking through the views tables for anything.  I will periodically look at an export to see what is going on with a view, and export/edit/import views to adjust things, though.


Enable / Disable comment form in a module?

It looks like I can set the comment display correctly within hook_node_load(). I guess that runs a bit earlier in the process, and tells comment.module to not display the form for a given node.

Here's an example of what I ended up implementing:

<?php
/**
 * Implements hook_node_load().
 */
function custom_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->comment = COMMENT_NODE_CLOSED; // to close comments
  }
}
?>


Create a simpletest test to add additional form elements using the "Add another item" button

The problem was with the drupalPost() method.  I managed to solve the problem by changing the first argument to NULL (e.g. $this->drupalPost(NULL, $edit, t('Save'));), which sets the target to the current page. Still not sure why this works instead of string denoting the path.  Never-the-less it did solve the problem.


How to add a new permission in "node_list_permissions"?

A more experienced user should check the below.. I've only added permissions to contrib modules.

From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_permission/7
This will add the permission to the people page.

function YOURMODULENAME_permission() {
  return array(
    'see history' => array(
      'title' => t('See History'),
      'description' => t('Blah Blah.'),
    ),
  );
}

From
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7
This should check for the permission when viewing that url. I might have gotten the % wrong.

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

  $items['user/%/history'] = array(
    blah
    'access arguments' => array('see history'),
    blah
  );


webform block in a page template , inside a colorbox - validation does not show

The error messages are printed in $messages on a normal page, have you tried adding that?


Form API image upload form and File Entity; images not listed in admin/content/file

I think your problem is coming from calling image_save and not file_save. They are non synonymous so far as I can tell.

A managed_file is an uploaded file, and usually records an owner of the file with file_usage_add(). This is how drupal can manage whether the file is still needed by the system or can be unlinked or deleted when cron is run.

See this other drupal stackexchange answer on how to use the managed_file FAPI element. It should answer your question on how to get the (original) file saved. You could then create derivatives of the file with image processing as you've already successfully done; after the original file is saved.

I don't believe there is a streamlined solution for this in the file_entity module or in any image functions (I doubt it, as one thing is to upload and manage the file itself -- and another is to do proccessing on the image itself).


Error during import (The header record must be an empty or a flat array with unique string values)

Ok so the answer was pretty obvious header_offset should be 0


Language switching does not work when browser language is configuired in drupal 8.3.7

It is very obvious why this is happening. Language selection process the language detection systems from top to bottom. (Top has highest priority.) Your configuration means that the browser will always be selected first and that url and user settings are ignored.

If you move browser below user (drag with the arrows icon), the processing order will be:

url
user (if url resolved no language)
browser (if user had no language configured)


I think you're misunderstanding what the theme link in the advanced section of views. It is meant to help themers choose the right template file, show which template file is being used and get quick access to the default template code.

In order to change the theme on a specific Drupal page, take a look at the ThemeKey module.


Use external class in drupal 8 module with file name and class name

Your use statement is wrong. It should be:

use Drupal\mymodulename\lib\newman; - no Drupal on the end.

Aside from that, you should strive to inject dependencies in the constructor.

Also, there should not be a difference between the file name and classname. It makes it harder to debug and organize. The file should be named newman.php not drupal.php.

The error is referencing the fact that it cannot locate your class at the given namespace. It would help to brush up on PSR-4/autoloading in Drupal 8 as well as naming conventions and standards.


When Drupal requests are not enough, I found cURL a good way.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

It can either be used directly, or via cURL HTTP Request wrapper module.

This is a module intended for developers, as it provides just one API to call: chr_curl_http_request() (use curl_http_request() for versions 1.5 and earlier).
The function chr_curl_http_request() is an alternative implementation of Drupal core function drupal_http_request() using cURL.
The function intends to be backwards compatible with drupal_http_request(), by accepting the same parameters in the same form and by returning the response in the same format.


How can I call node id in template file?

Here is my solution:

<?php
$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(2);

$view = node_view($node, $view_mode);

print render($view);
?>


Creating a user using Services results in user not being able authenticate using HTTP Basic Auth

@Sander van't Veer - I struggled with this same problem recently. It looks like there's a bug in the services module where the password doesn't get set. Try this patch and you should be good.

https://drupal.org/files/issues/user_create-2198005-1.patch


How to find the count of items in a block?

In your view, for HEADER (located in the middle of the edit view screen) Add a Global Result Summary. Then just use the @total token like in the picture below. This will count the number of rows in your view.


The IMCE for FileField module suits your use case. The description given in its project page is the following.

IMCE for FileField allows users to select files from IMCE File Browser. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a FileField.

The latest stable release (7.x-1.1) has been released on April 8, 2015. It's covered by the security advisory policy. The development snapshot for that release has been last update on August 11, 2017.
As of today (April 10, 2021), there are 5 bug reports still open; the older of them has been opened almost 7 years ago. Only one of them got a reply from the project owner, who is also the only project maintainer.


Migrating D5 users to D6 using MigrateDestinationUser

As per http://drupal.org/node/1349758, you need to add a complete function:

$this->addFieldMapping('pass', 'source_password');
...
public function complete($account, $row) {
  db_update('users')
    ->fields(array('pass' => $row->source_password))
    ->condition('uid', $account->uid)
    ->execute();
}


How to set the value of a hidden field using form_set_value?

Insert the the value in $form_state:

$form_state->set('store_value', 1);

And then later for example in submitForm():

$value = $form_state->get('store_value');

Don't use getValue() or setValue(), because this is for submitted values.

If you are migrating more forms from D7 to D8, use this as reference:

Use this as reference


Administration menu - How to remove the number of users + search bar

Navigate to admin/config/administration/admin_menu Under the Plugins tab uncheck Search bar and Account links then click Save configuration


How do I remove frontpage content block?

You cannot remove the content part of a page as it is not a block. The content is suppose to be your main content that always shows and blocks are things that can be conditionally shown around your content.

You can create a page display for your view, then change the front page of your Drupal site to point to your views page display (D7: admin/config/system/site-information, D6: admin/settings/site-information).


One can provide a field.tpl.php file within the theme.

You can copy the existing field.tpl.php file from /modules/field/theme (which btw is just auxilliary and not used by Drupal) into the theme's directory and replace the line:

<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

into

<div class="field-label"<?php print $title_attributes; ?>>
<?php print $label ?>:&nbsp;

or something.


How to automatically populate a field with a value part of another field

You probably need a custom module for this.

Add  MODULENAME directory inside your modules directory.  Inside the directroy create file MODULENAME.info.yml with contents:

name: Last word copy
description: 'gets last word from field_a and saves it to field_b'
core: 8.x
type: module
package: COMPANYNAME
dependencies:
  - node

This module implements hook_form_alter that will make field_b readonly / disabled and hook_entity_presave which will get the last word added to field_b upon save or update of a node of CONTENTTYPE

Create also MODULENAME.module file with contents:

<?php
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if(in_array($form_id,['node_CONTENTTYPE_form','node_CONTENTTYPE_edit_form'])) {
    $form['field_b']['#disabled'] = 'disabled';
  }
}

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if($entity->bundle() == "CONTENTTYPE"){
    $pieces = explode(' ', $entity->field_a->value);
    $last_word = array_pop($pieces);
    $entity->field_b->value = $last_word;
    //save is done automatically
  }
}

You NEED to replace MODULENAME and CONTENTTYPE in the above code.

If all is correct go to Extend (admin/modules) and enable the module.


How can I add a custom attribute to a link field?

On Drupal 7 there are several ways to go about this depending on your setup.

If you are using Display Suite you can add custom attributes to the link field (and all the various wrappers) by setting the field template to Expert:

You could also use template_preprocess_field() in a module or your theme to add additional attributes to the link before it is rendered.

Display Suite is more limiting but often easier (particullarly if it is already in use). Since the preprocess function is in PHP it will give you more flexibility that may or may not be useful.


How to use Docker for a drupal development site and then deploy to online provider?

You're asking 2 questions in the post: a general one (title) & a platform specific one (body), which is off-topic here (we don't write tutorials for Drupal platform integration). I'll answer the general which is useful at-large.

Most of the docker-based Drupal dev tools have decent feature sets. Each tool has one-or-two features that make it uniquely standout for a particular use scenario. You have to judge a dev-tool on who's maintaining, why are doing it, what are its supported features/platforms, how long it's been in development.

Theoretically, everything being Dockerized means you build/test locally and can deploy anywhere that does Docker hosting. In practice, to get from point A to point B, you'll have to figure how what your host platform provides technically (e.g. IaaS vs PaaS, CI tools, etc.) to what you have for your dev setup is (e.g. Dockerized toolchains, source code host, etc.) and match it up to see if all the pieces fit.

You can decide provider or docker-based dev-tools first, but a choice of one is going to impact the other in some way. You basically have to go a through a matrix of:

What the Docker dev-tool provides
What features you want (for platform/dev-tools)
What the platform provides (for integration)

Then the "best" is whatever matches lines up most in your matrix (or tensor since we're talking 3 attributes here). There's a lot of details along the way. You have to do a lot research to fill in the details that work best work for your project.


How to Create a wall of activities (like Facebook wall) in my site, for each user?

You need to give the ability to users to create a relationships.
https://drupal.org/project/user_relationships. You can set up what kind of content is shareable.

Then using https://drupal.org/project/heartbeat you can get activity streams.

Really do yourself a favor and get https://drupal.org/node/1849900. It can save up huge amounts of time, allowing you to set up a facebook-like network in a few hours!


very block has a "visibility setting". Select "Only the listed pages" and enter the pages where you want this block to show.


How to add an icon before (or after) the node title if a field is filled?

I found your answer on drupal.org.

function mytheme_preprocess_page(&$variables) {
  $titleFile = 'myicon.png';
  $titleImage = base_path() . path_to_theme() . "/images/titles/" . $titleFile;

  $newTitle = $variables['title'].' <img alt="' . $variables['title'] .'" src="' . $titleImage.'" />';
  $variables['title'] = $newTitle;
}


running "drush @remote status" gives "bash: drush: command not found"

The other question that you reference answers your question perfectly, except for the fact that Drush is located in a different location on that user's remote system.  Since drush @remote ssh works for you, type which drush on the remote system, to find out where your Drush is located.  You are likely to get an answer similar to /home/USER/.composer/vendor/bin/drush.  You need to insure that the directory /home/USER/.composer/vendor/bin is in your PATH.  This directory might vary if you did not install Drush using Composer, as recommended in the Drush README.
If which drush produces no output at all, this means that you forgot to install Drush on the remote machine.  Use composer, following the same instructions you would for your local machine, in the above-referenced README file.
Pay particular attention to the following part of the installation instructions:

Add Composer's global bin directory to the system PATH (recommended):
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
source $HOME/.bashrc

The 'sed' line shown above adds an export PATH statement to the TOP of your .bashrc file.  It is important to set your PATH early, because .bashrc exits just a few lines in when running in non-interactive mode on most Linux distributions.  Most of the other places you might be tempted to set the PATH (.profile, etc.) are not sourced at all in non-interactive mode.  So, if you do not set the PATH in the right place, then Drush will work from an interactive shell (e.g. after drush @remote ssh), but most remote Drush commands (e.g. drush @remote status) will not.


Get Video URL from Media Entity reference field

If you use the media type Video installed by core, you'll find the URL in the field field_media_video_file:

{{ file_url(node.field_media.entity.field_media_video_file.entity.uri.value) }}


Is there a way to run drush updb without going to maintenance mode

Actually, if you take a look at the drush code for updatedb command, you can find this piece of code in updateBatch() function:

$original_maint_mode = \Drupal::service('state')->get('system.maintenance_mode');
if (!$original_maint_mode) {
    \Drupal::service('state')->set('system.maintenance_mode', true);
    $operations[] = ['\Drush\Commands\core\UpdateDBCommands::restoreMaintMode', [false]];
}

For safety reasons, the drush command puts your site in maintenance mode during the update and then set it back online once it is completed. It prevents your users from accessing the website and generate possible conflicts within the database while it is updating.

There is a pretty clear explanation of this here

If you really wish to avoid the maintenance mode, though, you could run update.php directly from your website.


"The directory sites/default/files is not writable" error

Install the drupal using virtual host, it will be help to manage all the permissions. Here i'm giving an example of a virtual host file with some permissions which might help you install the site.

    <Directory "/var/www/html/mysite">

    Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
        Allow from all

    </Directory>

    ServerName mysite.local
    ServerAlias www.mysite.local
    DocumentRoot /var/www/html/mysite
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>


The code you wrote so far is correct; you just need to add the code for getting the saved setting, and the code to save it.

function mymodule_form_menu_edit_item_alter(&$form, &$form_state) {
  // Get the mlid ID of the menu item.
  $mlid = $form['menu']['mlid']['#value'];

  $form['menu']['newbanner'] = array(
    '#title' => 'New banner',
    '#type' => 'checkboxes',
    '#description' => "Add a 'New' banner to this item?",
    '#default_value' => variable_get("mymodule_newbanner_$mlid", 0),
    '#options' => array('new_banner' => t("This item is new")),
  );

  $form['#submit'][] = 'mymodule_menu_item_submit';
}

function mymodule_menu_item_submit($form, &$form_state) {
  $item = &$form_state['values']['menu'];
  // Get the last ID inserted in the table.
  if (empty($item['mlid'])) {
    $item['mlid'] = db_last_insert_id('menu_links', 'mlid');
  }

  variable_set('mymodule_newbanner_' . $item['mlid'], $item['newbanner']);
}

The mlid could be zero, when the menu item is first created; in that case, the form submission handler gets it from the table, as it is executed after the form submission handler added by menu.module, which saves the menu item in the table using menu_link_save().


It turned out to be a bug in the Drupal extension that is fixed here: https://github.com/jhedstrom/drupalextension/pull/379


How to store additional_settings value when adding a node?

Turned out I simply had to look into nodeapi_example.install to find out about hook_schema() to create a new database table where I then can save my values to. So I created an install file and put the following code inside:

function MY_MODULE_schema() {
  $schema['MY_MODULE_string'] = array(
    'description' => 'Stores information of extended content.',
    'fields' => array(
      'nid'    => array(
        'description' => 'Node ID that the string is applied to.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'vid' => array(
        'description' => 'Revision ID, as we are tracking strings with node revisions',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'url' => array(
        'description' => 'MY MODULE string',
        'type' => 'varchar',
        'length' => 19,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('vid'),
    'indexes' => array(
      'nid'   => array('nid'),
    ),
  );
  return $schema;
}


It seems each content type can only be assigned to one workflow at a time.
Try removing removing a content type from the other working workflow, save it, and then adding it to the new workflow.


How to configure the existing search system to exclude content types and/or nodes from the search index?

There is a new Search Exclude (Node) module

  Exclude content types from node search for Drupal 8.


Is there a way to find internal links to a specific web page?

You may want to look at the Views module (pretty sure you already have that module enabled ...), which includes a Backlinks view. After you activate this view, a What links here-tab is shown on each node.
So on your about page, it'll list all of the pages that have a link to the about page (as in your question).


Masking event title if marked as "private" (Views, Pathauto…)

hook_node_load() should be suitable for changing the title based on the private status and current user.

Changing the path will be the hard bit.

Pathauto can only have 1 configuration per bundle so you'll need to use hook_node_insert() and hook_node_update()
to act on events being added or altered to set the private path alias. path_save() can be used to actually save the new alias, but you will need to code the logic to come up with the alias yourself. This post on drupal.org may help.

Once the additional alias is set you will need to make sure to use the correct alias when building links to the content based on the current users permissions.


How do I specify an image style in my preprocess function?

Have you tried render

// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = render($vars['content'][$field_name]);
        }
      }
    }


How to put multiple fields in an index operation on a GET HTTP request with services?

The simple db_select with fields make it work easy as that :

function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t')
->fields('t', array('field_title_value','entity_id','delta'));//<+++++ whatever you want

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}


Drupal versus with Omni Update: Should I move from Drupal to Omni Update?

I think you might have answered your own question: "it will turn into a LOT of work if they decide to switch to the proprietary platform". Work = time = money, and that is manager-speak.


PHP snippet: why comparing the term id with a number keeps getting the wrong result?

This happens because you can't use tokens in the snippet itself.

When you print the token, PHP outputs the token as-is, but Drupal catches this output with Output buffering, and tokens are processed later.

In the field, see if you get the field item or taxonomy term as a PHP variable. Then, use that variable to extract the term ID.
You need to refer to the information provided by your module. If you have Devel module, you can inspect those variables using dpm function.

You are probably looking for something like this:
$node->field_suscriptor_estado1[LANGUAGE_NONE][0]['tid']


I have never used the Quiz module myself so I can only give you a generic answer.

What I would do, is to create a custom module which contains a hook implementation and a helper function:

In the helper function, check if the current has the permission to create quiz content and if the user has already posted a quiz today. You may need to write a database query to retrieve this information, but I'm not sure, that depends on the way the quiz module was programmed. Return TRUE if the user is allowed to post a quiz, return FALSE if not.
In a hook_menu_alter implementation, change the access callback property of the quiz creation form, setting it to the helper function you just wrote. This will deny access to the quiz creation page if the use is not allowed to create a new quiz.

Hope that helps.


"Login to your account" form block not showing on frontpage when "View published content" is disabled for anonymous

Drupal core does not support a good way to have a site that requires the user to log in.

The Require Login contrib module adds this functionality.  It also allows for public sections of the site (e.g. a login landing page, links to how to get help, and the like.


How to create custom menu link wrapper function in Drupal 7?

Indeed, you need to register a new theme implementation. Looking about the specification of the hook_theme(), each information array must contain either a variables element or a render element. This is missing in your case and causes the empty $variables argument.

function YOURTHEME_theme()
{
    // define a custom theme implementation
    return array(
        'menu_link_custom' => array(
            'render element' => 'element',
        ),
    );
}

function YOURTHEME_menu_link_custom($variables)
{
    //Build and return custom HTML for your link
}