Allow VIEWS accessing PARAGRAPHS fields collection

In D8 your View's are automatically cached; thus, your query is results are cached, so I wouldn't worry too much about this. Nonetheless, you can enable Show performance statistics in views settings (/admin/structure/views/settings), to see how long it takes.

Testing with 1 field, the View Render Time is ~1.20ms faster when you create a View of Show: Field Collection Item and then add relationship to node rather than a View of Show: Content with a relationship of field collection.


Something like this should work. Add it to your template.php file. Using preprocess_node gives you a little more control so you aren't just arbitrarily loading the script on every page.

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'blog' && $variables['view_mode'] == 'teaser') {
    drupal_add_js($theme_path.'/js/new_teaser.js');
  }
}


The HTML attribute removal was documented in change record #2932803, but the example uses the now deprecated SafeMarkup::format function. The FormattableMarkup class allows a non-deprecated way to do this. The API page has some good examples such as below:

Remember that this is has security implications, and to only use FormattableMarkup when you absolutely need it with strict placeholders.

$value = FormattableMarkup::placeholderFormat('@variable', [':url' => $url, @variable => $variable]);

There's probably a better way to do this without printing the anchor element and href attribute yourself.


Yes. Now that Views is integrated into Drupal 8, the admin/content display can be driven by a customizable View.

Make sure the Views/Views UI module is enabled in admin/modules, then navigate to admin/structure/views. You'll see a View named Content which corresponds with admin/content. You can edit that view to add various exposed filters that correspond with your own content setup (e.g. custom taxonomy filtering).


Editing a Field Collection element in a custom module

Strictly speaking on how to edit a field collection entity, once you have the field collection ID (you would get it from a field on your host entity, for example), you can load the collection using entity_metadata_wrapper, change it and them save it back.

$collection = entity_metadata_wrapper('field_collection_item', $collection_id);
// Do your change
// ...
$collection->save();


Create a block with sorting in drop down

You can use table display to manage the listing of all the posts.
Now to filter/sort the data you can user ctools jump menu. Using Ctools jump menu you can create various menu items for different sorting type.

To see the example of Ctools jump menu see the ctools_ajax_sample module which comes with Ctools module package.


Prevent enter to submit form / disable enter

And the answer is :-)

$form['#attributes'] = array('onsubmit' => 'return false');

or alternatively (the above will disable submit all together)

  $('#edit-searchfield').keypress(function(event) {
   if (event.keyCode == '13') {
       event.preventDefault();
   }
});


What's wrong with my plupload implementation?

When using Plupload integration module in custom code, you need to set up size twice. Preferably to the same value. First place you do it is the usual:

'#upload_validators' => array(
  'file_validate_size' => array(variable_get('my_max_file_size', 300 * 1024 * 1024)),
),

This handles display and post-upload verification.

Second place is #plupload_settings:

'#plupload_settings' => array(
  'runtimes' => 'html5',
  'chunk_size' => '10mb',
  'max_file_size' => variable_get('my_max_file_size', 300 * 1024 * 1024) . 'b',
),

This is what actually goes to the plupload JavaScript.


Can't add contextual Filter (taxonomy term ID (with depth)) to a View (User)

In D7, you can only do that with the node table (the content).

If you want to have a working solution for every entity of your system, you have to use this module.

Once installed, don't forget to rebuild the index of your entities, then, in views, you'll have the possibility to add a new relationship ('Taxonomy Entity Index: Taxonomy terms on User') and a filter with depth ('Taxonomy Entity Index: Has taxonomy terms on User (with depth and indexed in taxonomy_entity_index)').


You can use hook_ENTITY_TYPE_update to achieve this.

/**
 * Implements hook_ENTITY_TYPE_update().
*/

function mymodule_node_update(Drupal\Core\Entity\EntityInterface $entity) {

    //Get the current Moderation state;
    if (isset($entity->moderation_state) && isset($entity->moderation_state->getValue()[0]['target_id'])) {
        $currentState = $entity->hasField('moderation_state') ? $entity->moderation_state->getValue()[0]['target_id'] : null;
    }
    //Get the original Moderation state;
    if ( isset($entity->original->moderation_state ) && isset($entity->original->moderation_state->getValue()[0]['target_id']) ) {
        $originalState = $entity->original !== NULL ? $entity->original->moderation_state->getValue()[0]['target_id'] : null;
    }

    #Get the Transition;
    $workflowTransition = rtrim($originalState.'-->'.$currentState);

    switch ($workflowTransition) {
       case 'published-->needs_review':
       case 'draft-->needs_review':
       //Do something.
      break;
       case 'draft-->needs_review':
      //Do something else;
      break;
    }
 }


Where does the Entity Registration module store the signup data and how to delete it?

Where does Entity Registration store the signup data?

Looking at the module's .install file, those data should be stored in  the table with name registration. Especially these columns of it should be close to what you're looking for:

  'count' => array(
    'description' => 'How many spaces this registration should use towards the total capacity for this event.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 1,
  ),
  'user_uid' => array(
    'description' => 'The uid of the user associated with this registration.',
    'type' => 'int',
    'not null' => FALSE,
    'default' => 0,
  ),
  'author_uid' => array(
    'description' => 'The uid of the user who created this registration.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ),
  'state' => array(
    'description' => 'The {registration_state}.name of this registration.',
    'type' => 'varchar',
    'length' => 32,
    'not null' => TRUE,
    'default' => '',
  ),
  'created' => array(
    'description' => 'The Unix timestamp when the registration was created.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ),
  'updated' => array(
    'description' => 'The Unix timestamp when the registration was most recently saved.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,

  How do I see the information collected?

Option 1: Just browse this table, using your preferred tool to do so.

Option 2: Use the Views module to create an appropriate view of it, as suggested also in its community documentation, i.e.: "Not happy with the default tabular list of registrations? No problem, registrations and their fields are all Views friendly. You can override the default event registrations list, create additional ones, etc". You probably want to enable its registration_views submodule for this.

  How do I delete it?

It may be straight forward to just delete the relevant rows in the "registration" table mentioned above. However because of its integration with the Rules module, I'd rather use this module, possibly combined with the Views Bulk Operations module, to perform such deletes


Views row style plugin override not saving in Views UI

The issue was an incomplete namespace in the use statement for the RssFields class. I had

use Drupal\views\Plugin\views\row;

so it was looking for that class in my module. Changing it to

use Drupal\views\Plugin\views\row\RssFields;

made everything work.


How to use (reference) the uploaded file to a media(video) type?

after two days trying , i find the solution myself.
shortly ,

first,  post file , get the fid.

second, post a media , get the Mid (media id)

third , post a node ,use the Mid

I omit the second step.


How do I use the login for an external application?

You can install in your drupal site a contrib module which allow you to create an API which can access another modules.

You can use Services module which implements route to allow users login across external sites, and another route to get the current user logged in.

So you can install this module and enable this routes, and with your php site make http calls to this sites to log in the user and check if he is logged in.


How to embed existing website in my Drupal 8 site?

Creating a subfolder inside your docroot folder such as docroot/elina-noe should suffice.

Put all the subsite files into this folder and if there is a index.html you can access your subsite just by visiting the subfolder http://falzon.xyz/elina-noe/


This sounds like it may be a magic_quotes issue. If at all possible, disable this in your PHP configuration. Instructions on how to disable them are on the PHP website. If this is enabled on a live, shared server and you don't have access to the PHP configuration then I would highly recommend looking for a new host. The magic_quotes_gpc option has been deprecated in PHP 5.3, and will likely be removed very soon.

Magic quotes provide a way of escaping incoming input, and have been frowned on for quite a while in favor of validating input properly in your application, which Drupal does.


Is there any compatibility issue with Amazon Aurora?

We are running a couple of projects on Amazon Aurora  with no issues so far. Our largest project is a D7 project with many contributed modules, and a large amount of data being moved.

We've never noticed any DB related issues aside from normal MySQLisms. It's really transparent to Drupal. We use normal Mysql connection strings and zero core changes.

Aurora is more expensive. A lot more expensive. It only starts at the db.r3.large tier, and works out to a monthly (non upfront rate of 0.190 per hour). So the price difference must be considered.


How do I conditionally add a class to my page title within page-title.html.twig?

In page-title.html.twig you don't have access to content variable.
according to page-title.html.twig comment section:

Available variables are:

title_attributes
title_prefix
title
title_suffix

So you should implement hook_preprocess_HOOK to passe hide_title to your twig like the following:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['hide_title'] = $node->field_hide_title->value;
  }
}

Now you can do the following in your twig:

{% if hide_title == "1" %}

{{ title }}

  {% else %}

{{ title }}

{% endif %}


One working solution:

Create a vocabulary where each term has 3 additional fields - a text field, a Link field, and another text field. Add the Term Reference to the content type. Use something like Chosen for selecting ease in needed.
Use hook_field_formatter_info() in a custom module to define a display of the 3 fields as desired. Unfortunately, displaying term fields on the content/node page doesn't have a quick & easy configurable solution.


How do I remove the information section available below the comment box?

Simplify module is what you are looking for. Besides hiding the text format selection, it has a few more settings to hide, which really "simplifies" the user interface.

  Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


Which hook to use on initial creation of a node?

You're probably looking for hook_node_insert where $node should contain your node reference field.


hook_init() is run on every page load except for cached pages, so depending on your use case that might be an option.

function MYMODULE_init() {
  // Custom logic
}

hook_boot() is run on every page, including cached pages, so might be more useful (again depending on your use case). However if you have complex logic to process this will obviously slow down the build of every page, even those that are cached.

function MYMODULE_boot() {
  // Custom logic
}

If you want to check whether or not the current path falls under '/admin' you can use a check like this in either function:

if (arg(0) == 'admin') {
  // ...
}

This won't work for node edit pages, for example, who's path doesn't have '/admin' in it; but short of invoking hook_admin_paths() and testing the current URL against each of the paths returned, I'm not sure how you'd reliably test for that anyway.


You can try the following code (please note that about-us is merely an example page - you can put whichever page you want here):

$url = 'about-us';
$path = drupal_lookup_path('source', $url);

if ($path) {
  $node = menu_get_object('node', 1, $path);
  return $node->nid;
}
else {
  //Error handling in case path provided does not exist
}

The code above returns a whole node object though, which might be expensive depending on how often you run it - another option would be to run explode() on the output of drupal_lookup_path() and just take the NID that way.

References:

drupal_lookup_path();

menu_get_object();


Where do I find a list of commonly used features?

It looks like the Debut Project collection might be up your alley. From the project description:

  Debut is a set of baseline Drupal features available as apps and designed to work independently yet integrate seamlessly together.


Correct way to link to views (to solve multi-domain problem)

Since you obviously are capable of PHP, the best way I can think of is to write a custom wrapper for l(), something like:

function ml($text, $path, int $domain = NULL, array $options = array()) {
  switch ($domain) {
    case 1:
      return l($text, 'http://first-domain.com/'.$path, $options);
      break;
    case 2:
      return l($text, 'http://second-domain.com/'.$path, $options);
      break;
    default:
      return l($text, $path, $options);
      break;
  }
}

That way, the absolute domains only have to be changed in this one central place with each staging step (domains may even be stored in settings.php).


You want to avoid putting this into your node template. Generally you want to keep "business logic" (any php functions other than print) out of template files. You might be better served by creating this as a block and placing it below or above the node because it is more reuseable. If you don't want to use a block you can use hook_node_view() and add an additional element to $node->content as in the linked example.


Is there a way to input the data of multiple content types all on the same page?

You can use the module Inline Entity Form as widget for student and course in your student-course content type.

This widget loads the node form for student and course in student-course content creation form, so you can fill all the data in the same place.


What's the accepted way to add different prices to commerce products?

As mentioned you can add new field to your product type:

Next enable commerce_product_pricing_ui module or just add new Rule on event “Calculating the sell price of a product”. Rule looks like this (full size):

You can control the order of Product Pricing rules by Rules weight.

But I prefer to create field “Old price” (or “Common price”) and to add simple description:

  If you want to create special offer for this product, please, place new price in the Price field and move crossed out price to “Old price” field.

So, “Old price” is only for theming. It works for small commerce sites and I don't need any crazy Rules.


Using multiple templates in a Drupal 8 module

hook_theme() returns a list of templates that will then be cached in the registry. You don't need conditions there, in fact, you can not, since it will be called only once.

Just return multiple templates and then reference them in your render arrays, like you already have to when using a single one.


You can use New Relic.

  Database performance

  Viewing slow SQL queries is a breeze. Most Drupal sites rely heavily
  on Views and CCK which can generate non-optimal SQL queries. New Relic
  allows you to quickly pinpoint these types of queries.

  Modules Monitoring

  You can identify which modules are slowest by call count or by slowest
  call time. This may help you identify which modules may be running
  rogue within your application.

  Apdex

  New Relic uses Apdex scoring to help you evaluate how well your Drupal
  application is performing for your end-users according to an
  industry-standard measurement. This helps you provide better data as
  well as have a clearer understanding of what percentage of your users
  are frustrated or satisfied. Apdex scoring also provides more specific
  context than a general “the site is slow” complaint that may not even
  get to you until hours after the incident. Apdex also gives you a more
  objective way to measure your end-users’ experience with your
  performance improvements.

  Function Performance

  Using Web Transaction Traces, you can see which functions are the
  slowest in your application. You can use this to identify slow
  functions in custom modules you have written, or to track delays in
  your application caused by community module functions that do things
  like authenticate with third-party systems.

  Front-end performance

  All that wonderful flexibility within blocks, views, and panels can
  sometimes result in complex page renderings that need to be processed
  by the browsers of your end-users. New Relic’s Real User Monitoring
  (RUM) will actually gather timing information and show you which
  hotspots in DOM rendering time may be causing your page to take
  several seconds to load.


How to add css class to block using mytheme_preprocess_block() hook?

function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $vars['classes_array'][] = 'CSS_CLASS_NAME';
  }
}

If you want to add a class to each individual item (li or/and a)use something like this:

function MYTHEME_menu_link(array $variables) {
  // replace MENU-MACHINE-NAME appropriately
  if ($variables['element']['#original_link']['menu_name'] == 'MENU-MACHINE-NAME') {
    // Add menu-li class to each li
    $variables['element']['#attributes']['class'][] = 'menu-li';
    // Add menu-li-a class to each anchor link
    $variables['element']['#localized_options']['attributes']['class'][] = 'menu-li-a';
  }
  return theme_menu_link($variables);
}


How is it possible for users to submit a node without a required image field?

A contributed module was to blame-- the Manual Crop module.  Thankfully, the issue is already fixed.


It has got to do with the line:

`operator` varchar(2) NOT NULL DEFAULT=,

It's because the equals sign isn't surrounded with a space and then quotes, which is breaking everything. If you want to have = be the default operator, that line needs to be:

 `operator` varchar(2) NOT NULL DEFAULT '=',


Contextual filter based on base level of taxonomy

If your content type contains a reference field to a taxonomy term with depth, you can use a view block with a normal filter, no contextual filter needed.

Choose 'add filter' > 'Has taxonomy terms (with depth)'
Next screen, select the taxonomy vocabulary (I don't know what it's name is in your case, it should be the vocabulary in which 'option c' is a term) and
set 'Depth' to 1, this will also select the first level of children
Next screen, select the parent term for c1, c2 and c3 (in your case
'option c')

The block will now show all content where the reference field has been used to select option C or it's children.
I used this technique in this site: www.zorgsaamwonen.nl which uses 3 main themes with a lot of child themes.


How to identify permissions which current user lacks to access node create page?

Devel Node Access (DNA) provides detailed information on permissions that take effect.

  View the node access entries for the node(s) that are shown on a page. Essential for developers of node access modules and useful for site admins in debugging problems with those modules.

Unless some modules abuse access system with dirty hacks, it should pretty reliably identify which module refused access to given user.


Why the template_preprocess_field hook is not called for a custom template?

As @Clive says the problem was that the code didn't use the render() function for the field output, and in this case the template_preprocess_field() hook is not called.

For the moment I have 2 solutions:

Use the render() function in the template file (node--emploi.tpl.php) to create the output of the field. In this case the template_preprocess_field() hook is called.
Use the template_preprocess_node() hook and check $vars['type'] for my content type. In this case the template file remains equal.


Drupal 8 \Drupal calls should be avoided in classes, use | | dependency injection instead

You can check how the dependency injection works in general in this documentation.
https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form

The parts that you need are:

Use statement -

 use Symfony\Component\DependencyInjection\ContainerInterface;

Class property - here we are going to store the whole \Drupal::service('current_user') object.

 protected $account;

The __construct magic method. This is called upon instantiating the class.
The dependency injection bit here is providing all the data required in a later stage as input.

function __construct(AccountInterface $account) {

Built in method that  has a dependency injection
create(ContainerInterface $container)

return new static(
  // Load the service required to construct this class.
  $container->get('current_user')
);

Eventually we are using the whole construction like that:

$uid = $this->account->id();

where $this->account is the same like \Drupal::service('current_user');


How do I print individuals fields in block.html.twig when is a node in a block?

You have to set "node" in the twig-variables of your block. I.e. you can do this in a template_preprocess hook like so:

function mytheme_preprocess_myBlock(&$variables) {
  $variables['node'] = Node:load(50);
}

Then you can access the "node" in your template like {{node.my_field.value}}.

The hard part is to find which node to load in the preprocess function :-)


Form state cache breaks dependency injection

Haha, I've fount it finally. The problem was the properties were private. And the serialization trait wasn't able to save the values and when it loaded back it became null.


My guess is that you're not including the phpunit.xml.dist file, which sits in the core folder.

Either run tests from there (./vendor/bin/phpunit ../modules/your_module) or specify that file with -c.

You can also provide your own phpunit.xml.dist file (see the Payment module as an example); then you can run PHPUnit from your module folder.


Drupal 7.54 DATE_RFC7231 already defined

Are you certain you're running PHP 5 and not a version of PHP 7? I've only ever seen that error when running PHP 7, and it was due to DATE_RFC7231 already defined in PHP 7.0.19 and 7.1.5.

Either way, the patches in that issue were committed and released with 7.55, so it might be worth trying a core update before anything else.


Add class to form-tag in in views exposed form via template_preprocess_views_exposed_form()

Short version: You cannot use hook_preprocess_views_exposed_form() to modify the <form> tag. The <form> tag is independently rendered by a form theme hook set through the #theme_wrappers render property. Which means that it is completely disassociated from the actual views_exposed_form theme hook that renders the (internal) content of the views exposed form.

Long version:

views_theme() defines the views_exposed_form theme hook as returning a form render element. That means that it will eventually be using (unless somehow overridden) the definition provided by the Form render element. If you take a look at that, you will see that that definition  sets the'#theme_wrappers' property to ['form']. No surprises so far. :-)
At some point during the theming of a views page (or block), the theme hook views_view comes into play; this theme hook contains the exposed render variable that is essentially the exposed form you are interested in. The render array of exposed holds the following two relevant properties:

#theme => views_exposed_form (and other more specific ones like views_exposed_form__search_content): This is the theme hook that will provide the content of the form, i.e. everything inside the <form> tag. This is what you get access to and given the option to modify when calling template_preprocess_views_exposed_form(). This theme hook is not responsible for rendering the <form> tag and does not allow you to change it.
#theme_wrappers => ['form'] : This is the #theme_wrappers list of theme hooks; form will provide the actual <form> tag. It will essentially enclose the markup generated by the #theme theme hook into a <form> tag. This is what you get access to when calling template_preprocess_form(). This theme is responsible for rendering the <form> tag and does allow you to change it.

Implementation suggestion

If you would rather let hook_form_alter() implementations handle form-related logic, you could still use another preprocess hook to implement the functionality you want, namely the preprocess_views_view() hook.

function MY_THEME_preprocess_views_view(&$variables) {
  if ($variables['id'] === 'search_content') {
    $variables['exposed']['#attributes']['class'][] = 'row';
  }
}

Good luck, this is a really good question!


In the views are not displayed in the widget attributes field Form add to cart

Try to use instead Content: Product variations field Content: Rendered Node witn selected to render custom view mode like a "Product variation".

In display custom view mode should be disable all fields, but Add to cart form keep enable.


How to hide/show menu items using based on group membership?

A better way of doing this might be to use Drupal's built user permissions. You can use a 3rd party module such as https://www.drupal.org/project/content_access so set specific access

E.g. so that only certain roles have access to those certain pages. Then drupal will automatically handle the showing/hiding of the menu links if they depending if the user does/doesn't have access to that page


I'm afraid that's not really your decision to make...Google will take what it feels is the best representation of your site's description, whether that be the meta description tag or some text from elsewhere in the body.

The best you can do is make sure that you have <meta name="robots" content="noodp">   (which Google supports) somewhere in the document <head>. That will at least mean your title/description will come from somewhere in your page source, and not from the Open Directory Project (which is a distinct possibility otherwise).

The most important thing...don't expect instant results. Google will revisit your site when it's ready, and there's still no guarantee it will use exactly the text you want it to for the SERP description.

If you're not happy with that outcome, contact an SEO specialist who might be able to point you in the right direction.


PDOException: SQLSTATE[42S02] when changing password using Drupal Commons 7

This indicates a database table is missing. Given that the error happens in the oauth module itself, I would assume the error is not caused by incompatible modules working together. I can think of three possible causes:

You need to clear the caches.
Whenever you have a problem like this in Drupal, you should try clearing the caches. This can be done by going to Administer > Site Configuration > Performance on your site.
You need to run some database updates.
When you upgrade modules, they sometime needs to run some update code which can, for instance, add new tables or change table definitions. This can be done by going to /update.php on your site.
There was an error when installing this module.
If neither of the possibilities above work, you might want to try to disable this module, and re-enable it to see if there is any problem during installation.
Warning: this will probably require you to disable other modules, and might cause a loss of data. Try this on a copy of the site.


Domain views module

Part of the Domain Access suite.
Provides Views integration for Domain Access.


Is it possible to use multiple captcha based on language selection?

Well, you should do this in template.php. First check the language then add the captcha based on the language. As an example to do this in webforms:

function THEME_form_alter(&$form, $form_state, $form_id) {
    global $language;
    if($language->name == "ENGLISH")
    {
        if (strstr($form_id, 'webform_client_form')) {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'image_captcha/Image',
            );
        }
     }
}

You can check the language and add the mollom programmatically as well. Follow this link to learn how to add mollom by code.


How can I update this db_query statement to db_insert for D7?

The standard way is to use the db_insert() function with an associative array of field names/values:

$fields = array(
  'id' => $id,
  'name' => $name
);

db_insert('bluga_request')->fields($fields)->execute();

It actually looks like in your case the fields are already set up as an associative array in $args so you would just do this:

db_insert('bluga_request')->fields($args)->execute();


Use created year as condition in Entity Query

Try this function get_nodes_by_authored_month_date('news', '2018-02')

use Drupal\node\NodeInterface;

 /**
 * @param string $bundle_type
 * @param string $year_month
 *
 * @return array|int
 */
function get_nodes_by_authored_month_date($bundle_type = '' , $year_month = '') {

  $full_date = date_parse_from_format('Y-m', $year_month);
  //- Get number of days of month
  $number_of_days_of_month = cal_days_in_month(CAL_GREGORIAN, $full_date['month'], $full_date['year']);
  //- Get the timestamp of the first minute in the month
  $first_minute_of_month = mktime(0, 0, 0, $full_date['month'], 1, $full_date['year']);
  //- Get the timestamp of the last minute in the month
  $last_minute_of_month = mktime(23, 59, 59, $full_date['month'], $number_of_days_of_month, $full_date['year']);

  $query = \Drupal::entityQuery('node')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('type', $bundle_type)
    ->condition('created', [$first_minute_of_month, $last_minute_of_month], 'BETWEEN')
    ->range(0, 10);

  return $query->execute();
}


Hide field results not matching exposed filter

I managed to do this by creating a module that implements hook_views_pre_render()

Your field values will need to be taxonomy references for this to work, like so:

function MyModule_views_pre_render(&$view) {
    // Set the view we want to work with
    if ($view->name=='your_view') {
        // print out your array, so you know what you have (comment out in live site)
        drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');
        // Check to see if the filter has been triggered, otherwise you will get errors
        if (isset($view->exposed_input['exposed_filter_name'])) {
            foreach($view->result as $result_id => $result) {
                // cycle through each view result row, check that each result exists in the exposed filter. if it does not, then remove it.
                foreach ($result->field_your_field as $field_id => $field_val) {
                    //find the TID related to your result
                    $field_tid = $result->field_your_field[$field_id]['raw']['target_id'];
                    // Check if the TID is missing from the exposed filter values
                    if (array_search($field_tid, $view->exposed_input['exposed_filter_name']) === false) {
                        // Now look through your field values to find the TID missing from the values
                        if (($key = array_search($field_val, $result->field_your_field)) !== false) {
                            // And remove it
                            unset($result->field_your_field[$key]);
                        }
                    }
                }
            }
        }
    }
    // Finally re-number array to account for missing elements - i.e. [1],[3],[4],[6] to [1],[2],[3],[4] (optional, but tidier)
    $result->field_your_field = array_values($result->field_your_field);
}

Note that field_your_field is written like that because you need to append an extra field_ to the machine name. e.g. machine name field_my_field would become field_field_my_field


Translation: File upload error. Could not move uploaded file

Try this:

Go to admin/config/media/file-system page
Set Temporary directory field to sites/default/files/temp
Save changes

ALSO

Check that sites/files is writable.


Get the submitted values from $form_state

If you are getting values like form_id, form_token, or form_build_id, which you don't want, then you need to use the following code.

$values = $form_state->cleanValues()->getValues();

The documentation for FormState::cleanValues() says:

  This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

  form_id
  form_token
  form_build_id
  op

FormState::cleanValues() returns $this, so it can be used in chained calls, as in the code I showed.


Why do I get a "Unauthorized" error even though the user is logged-in?

Below code might help you login-in with current user:

function mymodule_user_login_cred($username, $password)
{
  if(user_authenticate($username, $password))
  {
    $user_obj = user_load_by_name($username);
    $form_state = array();
    $form_state['uid'] = $user_obj->uid;
    user_login_submit(array(), $form_state);
    return true;
  }
  else
  {
    return false;
  }
}


Limit reference field to nodes with referenced user

I found this solution that works:

  Permissions (for a given content-type)
  Administrator & Staff - Edit ANY content
  Normal Member - Edit OWN content

  Views Contextual Filter - Content: Author UID

  WHEN THE FILTER VALUE IS NOT AVAILABLE
  - Provide default value: Type - "User ID from Logged in User"

  WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
  - Specify validation criteria: Validator - "USER"
  - Type of user filter value to allow - "Only allow numeric UIDs"
  - Restrict user based on role: Restrict to the selected roles - SELECT the role who can only edit his own content
  - Action to take if filter value does not validate - "Display All Results for the specified data" [important]

  The last step (marked important), makes all the data (view results)
  available to other users, who have access to edit any content.

See https://www.drupal.org/node/2317525


How can I send an e-mail to the admin when use of a view results in an error?

You are describing hook_watchdog(array $log_entry):

  This hook allows modules to route log events to custom destinations, such as SMS, Email, pager, syslog, ...etc.

emphasis mine.

Inside it, you can use $log_entry array to get UID and request URL, and you can also use global $user, and you can call current_path(), so both your requirements seems doable.

$log_entry array is defined as:

  $log_entry: An associative array containing the following keys:

  type: The type of message for this entry.
  user: The user object for the user who was logged in when the event happened.
  uid: The user ID for the user who was logged in when the event happened.
  request_uri: The request URI for the page the event happened in.
  referer: The page that referred the user to the page where the event occurred.
  ip: The IP address where the request for the page came from.
  timestamp: The UNIX timestamp of the date/time the event occurred.
  severity: The severity of the message; one of the following values as defined in RFC 3164:

  WATCHDOG_EMERGENCY: Emergency, system is unusable.
  WATCHDOG_ALERT: Alert, action must be taken immediately.
  WATCHDOG_CRITICAL: Critical conditions.
  WATCHDOG_ERROR: Error conditions.
  WATCHDOG_WARNING: Warning conditions.
  WATCHDOG_NOTICE: Normal but significant conditions.
  WATCHDOG_INFO: Informational messages.
  WATCHDOG_DEBUG: Debug-level messages.

  link: An optional link provided by the module that called the watchdog() function.
  message: The text of the message to be logged. Variables in the message are indicated by using placeholder strings alongside the variables argument to declare the value of the placeholders. See t() for documentation on how the message and variable parameters interact.
  variables: An array of variables to be inserted into the message on display. Will be NULL or missing if a message is already translated or if the message is not possible to translate.

There is no way I know to get form ID of a form that created your error, I don't think it is in ['variables'], so the best you can do is to parse ['message'] for "illegal choice", and test ['request_uri'] and ['referer'] for pages that are your suspects.


Drupal equivalent of WordPress' page templates

There are several ways to suggest/override theme of a page in Drupal.

1. Override core theme files:

Firstly there are core themes defined by Drupal, which can be overridden from your theme. For example, the default user profile page uses user-profile.tpl.php. Though this is defined in Drupal Core, you can override it by copying it to your theme folder and modifying. The list of core file can be found here.

2. Default Theme Suggestions in Core

Drupal has implemented some default theme suggestion patterns in the core. It helps us write a specific theme for a page, path or even a particular article without having to write code. For example, if your about page has a node id 1. You write a template for just that page by creating a template file page--node--1.tpl.php in your theme folder. Similarly, you can suggest a theme for a node, user, block etc.  You can see available core suggestions in this page under respective heading.

3. From UI using context module:

Context module allows you to manage contextual conditions and reactions for different portions of your site. You can, for example, choose 1 or more conditions like path, user type etc and then add theme suggestion as a reaction to that condition/s.

Using context module.
Also, see ThemeKey module.

4. From code:
You can also write custom theme suggestion based on your own logic from code, either in template.php file of your template from a custom module.

An example from documentation:

// Add a single suggestion for nodes that have the "Promoted to front page" box checked.

function drop_preprocess_node(&$variables) {
  if ($variables['promote']) {
    // looks for node--promoted.tpl.php in your theme directory
    $variables['theme_hook_suggestions'] = 'node__promoted';
  }
}

A lot of code example can be seen if you scroll a bit down on this page.

Additionally, change the theme debug settings in setting.php to get additional information in HTML markup with respect to the theme. The setting to change is $conf['theme_debug'] = TRUE;. Once done, you'll get a lot of valuable suggestion in the HTML markup of each page.


Views/Block: Only display if node field has a value

The context module lets you conditionally display blocks on pages. context_entity_field then would let you set a condition based on the boolean field in your node.


Please check out Entity Reference Module.
It might help.


Your test class look OK.

There is no need to install or enable the Simple test module if you're using Drupal 7.  Instead, you should enable the core Testing module.  (Don't know if installing Simple test will make a difference, but it were not present when I went through the routine described below.)

Provided it exists inside your module's directory, you're using Drupal 7, have enabled the core Testing module, cleared the cache, and made sure to declare your test file with the correct name in your module's .info-file, nothing should stop it from appearing in the list included in the "Examples" group when you visit /admin/config/development/testing.

Here is how it looks on my site (after I've gone through the steps outlined above):


You can reder quick tabs using quicktabs_build_quicktabs function..

  Constructs a Quicktabs instance.

  This function can be called by other modules to programmatically build
  a quicktabs instance.

<?php
   $quicktabs = quicktabs_build_quicktabs('recruitment_quicktabs'); // use your qt name here
   print render($quicktabs);
?>


Modules provide their block titles and contents through implementations of hook_block_view(). If you're looking for something similar to your posted code that doesn't rely on calls to private functions, what's below should give you a render-ready array that you can place anywhere within another render array.

$renderable_block_data = module_invoke('views', 'block_view', 'results_anonymous-block');
$renderable_block_contents = $renderable_block_data['content'];

Caveat: while the docs for D7's version of hook_block_view() suggest that the returned "content" key should be a render array, some modules/blocks may be implemented in such a way that they return plain HTML strings, in which case you'd need to put the content in a #markup element before adding them to your parent render array.

Further discussion can be found in this drupal.org post.


Scheduler doesn't have any sort of integration with Ubercart. Unless there's existing module out there (I've never heard of it), you'll need a custom module that can hook into the attribute option form & display/store your expiration for each option (via hook_form_alter) & disable it when your option expires (via hook_cron).


Don't load jQuery, even when modules have it as a dependancy

You should be able to alter the JavaScript files include on the page with an implementation of hook_js_alter().


Instead of 'simple' selection, use a view for your entity reference. Here you can decide yourself how the title is shown.


How to hide the left tool bar of content type for non admin people?

in yourwebsite.com/admin/people/permissions check that the following permission are unchecked under Node (click image to enlarge)

Edit: I did testing, and it's the Administer Content, make sure you uncheck it! Also administer content types as you don't want them to have that either.


Which version of Drush should I install?

Always, always read the docs. Right at the bottom of the first page you'll find this:

Which removes any ambiguity.


How to show People menu in Admin for role restricted user?

I think you need to grant them "Use the administration pages and help"


How to get RAW Html code from my module?

It's not totally clear what you mean by 'from my module' but if you're asking how to get the HTML code of any Url into a variable in your module, you can use the drupal_http_request function. Below example comes from https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_http_request/7.x

$data = 'name=value&name1=value1';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('http://somewhere.com', $options);

You can also use curl via the cURL HTTP Request (chr) module.


Several things are wrong here.

Your hook_theme must return:

return [
  'return_products' => [
    'variables' => [
      'products' => NULL,
    ]
  ]
];

Now you have a template called return_products with a variable called products.

In your controller you must then use '#theme' => 'return_products', instead of '#theme' => 'return-products',.

Then create a template in mymodule/templates/return-products.html.twig.

Notice how your theme name must be with _(underscores) when referred to in PHP, but the file name must be with -(dashes).


How to create a node and populate its fields with info from a completed goal?

To populate some fields of the node to be created using some of the fields of the completed Goal, you need to make those fields (of the Goal) available as row variables in the Views loop of the rule you're using.

Have a look at this improved version of my rule that was included in my answer to your question about "How to fetch the completed goal as an entity with the Rules module?":

{ "rules_create_node_with_details_about_completed_goal" : {
    "LABEL" : "Create a node with details about completed goal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "goal_awarded" : [] },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "goals_info_about_completed_goals",
          "DISPLAY" : "views_rules_1",
          "USING" : { "goal_completed_by_uid" : [ "awarded-user:uid" ] },
          "ROW VARIABLES" : {
            "goal_title" : { "goal_title" : "Title" },
            "goal_id" : { "goal_id" : "Goal ID" },
            "goal_userpoints" : { "goal_userpoints" : "User Points" },
            "field_goal_category" : { "field_goal_category" : "Goal Category" },
            "field_goal_level" : { "field_goal_level" : "Goal Level" }
          },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "goal", "id" : [ "goal-id" ] },
                "PROVIDE" : { "entity_fetched" : { "goal_completed" : "Completed goal" } }
              }
            },
            { "drupal_message" : { "message" : "Details about completed goal:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- Goal ID: [goal-completed:goal-id]\u003Cbr \/\u003E\r\n- Goal Title: [goal-completed:title]\u003Cbr \/\u003E\r\n- Goal Category: [goal-completed:field_goal_category]\u003Cbr \/\u003E\r\n- Goal Level: [goal-completed:field_goal_level]\u003Cbr \/\u003E" } },
            { "entity_create" : {
                "USING" : {
                  "type" : "node",
                  "param_type" : "article",
                  "param_title" : "[goal-completed:title]",
                  "param_author" : [ "awarded-user" ]
                },
                "PROVIDE" : { "entity_created" : { "node_created" : "Created entity" } }
              }
            },
            { "data_set" : {
                "data" : [ "node-created:field-free-format-text" ],
                "value" : "Goal category = [field-goal-category:value] \/ Goal level = [field-goal-level:value]"
              }
            },
            { "data_set" : {
                "data" : [ "node-created:field-free-format-nr" ],
                "value" : [ "goal-userpoints" ]
              }
            },
            { "entity_save" : { "data" : [ "node-created" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

Some more details about the improvements in the above rule:

Note these additional row variables I added (in the Views loop), i.e.:

User Points (goal_userpoints), one of the fields that come with the Goals module.
Goal Category (field_goal_category), a custom field I added to my Goals entity (a single value text field, with values such as Contribution, Participation, Moderation, Privilege).
Goal Level (field_goal_level), a custom field I added to my Goals entity (a single value text field, with values such as Bronze, Silver, Gold).

After I added the extra Rules Action "Create a new entity" (to create the new node), I added these extra Rules Actions to set the values of some of the fields for the node to be created (= node-created):

node-created:field-free-format-text (of type text) is assigned the value of Goal category = [field-goal-category:value] / Goal level = [field-goal-level:value] (using 2 of the row variables I added in my view).
node-created:field-free-format-nr (of type integer) is assigned the value of goal-userpoints (using 1 of the row variables I added in my view).

With the above in mind, I think the real answer to your question (= "... I can't use them for any other fields for some reason") is that you need to pass the values of the fields you want to use as row variables also (and make sure the data types of those fields you pass along in your view are also matching with the node's field in which you want to use them).

BTW, make sure to understand the difference between:

"Goal completed by user", which is specific to a single user who completed a goal.
The actual configuration of a "Goal" itself, with fields such as User Points to be granted, or custom fields such as "Level" and "Category", which is identical for all users (and only changes if you change the configuration of a goal).


How to send an email once every 6 months using the Rules module?

The Rules module together with Rules Scheduler (a sub-module of it), can be used for sending such eMails, as explained in the steps below.

Step 1: Create a field to store the "next renewal" date

Add a field to the "user" entity with machine name (say) field_next_renewal. Allow only 1 date (to store the "next" renewal date).

Step 2: Create a Rules "Component"

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

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Reminder about your next renewal",
          "message" : "This is a reminder about your next renewal on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

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

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

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

{ "rules_email_user_every_6_months" : {
    "LABEL" : "eMail user every 6 months",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-next-renewal" ], "value" : "+6 month" } },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 15552000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

The above rule refers to the Rules Component from the previous step.

Note that the 15552000 is the equivalent of 6 months in seconds. You may want to reduce that a bit, e.g. with a number of seconds equivalent to a few days (or a week or so). That way the eMail will be triggered a few days before the actual renewal.


Including call to drupal_get_form('user_login') causes seemingly endless loop in Firefox

Here's what ended up working. After debugging, Firefox (and my mountains of code) was having an issue with the core module OpenID. I assume that since it only recently became an issue that it's a particular problem for my particular framework.


Implementing i18n string translation in a custom module?

Exactly, you can't wrap variables with t(). They will get printed, but they won't be translatable. I had a form that saves a user-defined string and wanted that string to be translatable from Drupal's translation interface.

Messed around quite a while with i18n_string() and its attribute $name (a $textgroup and a $context glued together with :).

Finally got it: You can provide your own $textgroup via hook_i18n_string_info() and later provide any other custom string as $context (maybe take your module's name to keep things clean).

If you have more than one string in your module pay attention to have every single one of them glued with another custom string to the prior context (textgroup:context:string_1, textgroup:context:string_2, ...).

Here comes a working example:

/**
 * Implements hook_i18n_string_info().
 *
 *   This is the most interesting thing here. You create a new
 *   textgroup your strings will be identified with. Here it's
 *   simply: Custom modules.
 *   When you set the i18n-string later you then only add another
 *   string as context like 'custommodules:any_other_string'.
 *   See the markup example in the form below.
 */
function MYMODULE_i18n_string_info() {

  $groups['custommodules'] = array(
    'title' => t('Custom modules'),
    'format' => FALSE,
    'list' => TRUE,
  );

  return $groups;
}

/**
 * Example form.
 */
function form_example() {

  // Just for testing, the first form element prints the translated
  // string, so you simply can test it after translation by switching
  // your page's language and see it working. This also demonstrates how
  // you will print the string everywhere else.
  $form['markup'] = array(
    '#markup' => i18n_string('custommodules:MYMODULE:string_1', variable_get('user_defined_string', 'Bempo Kohm'), array('update' => TRUE)),
  );

  $form['string'] = array(
    '#type' => 'textfield',
    '#title' => t('A beautiful and pure string'),
    '#default_value' => variable_get('user_defined_string', 'Bempo Kohm'),
  );

  $form['button'] = array(
    '#type' => 'submit',
    '#value' => t('Action'),
  );

  return $form;
}

/**
 * Example form submit handler.
 */
function form_example_submit($form, &$form_state) {

  variable_set('user_defined_string', $form_state['values']['string']);
}


Why taxonomy term view is showing only a single content?

After following @ShawnConn's advice on enabling the Show the SQL query option, I figured out what happened.
The query was indeed returning only one result. But then I remembered the categories were recently changed right on the database. To do that, we've updated the respective field table -- node__field_categories in our case. However, the taxonomy_index table was not updated. I went ahead and manually (again, I know) updated the taxonomy_index table and now the view is showing the expected content. I hope this is the last and only side effect.
The lesson learned is: only touch the database if you really know what you're doing. And even then, think twice. :P


I realized that it must have been a database issue since the live and local sites were in sync except for some module installs -- same with the code. I pulled the live database and imported it into local and re-installed the modules one at a time. Everything is now working fine. All that I can figure is that there was an installation error somewhere along the way that didn't want to show itself.


Use Rules to email all members of a role that is specified within a taxonomy field attached to a node

Preface: there is no need for the "AND" in your Rules Conditions (that's the default). Moreover, that "AND" applies to all Rules Conditions following the "AND" (but you only have 1 Rules Condition that follows it). Therefor, start by simplifying your Rules to get rid of the "AND". Refer to my answer to "How to make an OR statement in rules?" for more details about all this.

What you could do for sure is to rework your 2nd Rule (for role "4"), into a rule that performs a (new) Rules Component. To start, at least perform these changes:

Create a Rules Component which uses a parameter named (say) "Selected term". Use a data type of "Taxonomy term".
In your original Rule:

Replace the Rules Action (to send an eMail) by a Rules Action to just execute the (new) Rules Component. While doing so, pass node:field-category as the value of "Selected term".
Remove the last Rules Condition (with the hardcoded role "4").

The above changes will be a good start, but still it won't be sufficient. The remaining challenge (in the rules Component) will be related to the "Data selector" you need to specify for the Rules Action "Send mail to all users of a role" (= the replacement for your hardcoded "4"). That challenge is because the rules Component parameter "Taxonomy term" is a single value, while for the roles to be emailed you need a list (repeat: list!), as indicated also below the roles label, where it says "Select the roles whose users should receive the mail." (note: "roles", not "role"!).

Too bad, if we don't have a list, we'll massage the single value (Taxonomy term) into a "list". What follows is an example of a Rule and related Rules Component, with which I could make it work in my own setup:

Main rule

Here is my sample rule (in which I'm using 2 Rules Events, just to simplify testing and so that the logic is also triggered when updating content):

{ "rules_notify_users_of_selected_role_about_new_content" : {
    "LABEL" : "Notify users of selected role about new content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } }
    ],
    "DO" : [
      { "component_rules_do_something_with_selected_term" : { "selected_term" : [ "node:field-demo-tags" ] } }
    ]
  }
}

Note that I'm using a field like field-demo-tags (instead of field_category as in your case). I'm NOT using the Role Reference module, no need for it. The Rules Action is to only perform a Rules Component, in which the real magic will happen (see below).

Rules component

Here is my sample Rules Component:

{ "rules_do_something_with_selected_term" : {
    "LABEL" : "Do something with selected term",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_term" : { "label" : "Selected term", "type" : "taxonomy_term" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-term" ], "field" : "field_related_role" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Field \u0022field_related_role\u0022  (for Related role ID) is [selected-term:field-related-role]." } },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cinteger\u003E", "value" : [ "" ] },
          "PROVIDE" : { "variable_added" : { "list_of_roles" : "List of roles" } }
        }
      },
      { "list_add" : {
          "list" : [ "list-of-roles" ],
          "item" : [ "selected-term:field-related-role" ],
          "unique" : "1"
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : [ "list-of-roles" ],
          "subject" : "Some eMail subject (delivered to all users with role id = [selected-term:field-related-role])",
          "message" : "Some message content related to the term named [selected-term:name] (delivered to all users with role id = [selected-term:field-related-role])"
        }
      }
    ]
  }
}

The field field_related_role is an extra field I added to my taxonomy term I'm using (single value, data type integer), instead of field_responsible_team as in your case.

Some more details about this Rules Component:

Rules Conditions:

Check the type of node (in my case "article", adapt to fit your needs).
Check that the entity (node being created or updated) has a field field_demo_tags (the term I'm using).

Rules Action:

Show a message on the site (just for QA-testing purposes, omit if not needed anymore).
Add a variable, i.e. a "list of integers", which will become the "List of roles" we'll need in a subsequent Rules Action.
Add to this list, the value of selected-term:field-related-role (part of the Rules Component parameter).
Send mail to all users of a role, whereas we use the newly created "List of roles" to get it all to work (adapt eMail subject, message, etc to fit your needs).

The above works like a charm, at least in my case/setup: I have 3 users with a role related to a taxonomy term I used while updating an article, and each of those 3 users did receive an eMail as in my last Rules Action.

Voilà ...


comment_form() is expecting the parameter to be an object rather than an array so you should be doing something like this:

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);

Note the lack of a 3rd parameter passed to drupal_get_form(), comment_form() only accepts the comment as a parameter, if you want to add a title you'll have to print that separately.

Finally drupal_get_form() returns a render array rather than a string so you need to pass it through the render() function:

print render($form);

The extra errors you're getting are just side-effects of passing an array rather than an object to the comment_form() function.


FTP sites/all and sites/default/files files zipped and unzip on server or FTP as is?

My first recommendation is for /sites/all that you use a version control system such as Git/Subversion to save then the pull changes. If you must FTP them, I've found it's just as easy to copy them all over at once rather than unpack on the server, mostly because shared host SSH capabilities are sporadic and semi-functional at best.

Things to be careful of: if you're literally copying over /sites/default/files make sure that any .htaccess files were also copied. Additionally, you'll for sure have to do a cache clear because any css or js files saved in those directories will be unlinked from the current database.


How do I get a node based on id in custom content type?

This is exactly what the node references field modules do. For example in your Article content type, you would create a new field 'Related to References' as a node reference field and link it to relevant nodes of the References content type. The field stores the title of the referenced node and its NID which makes it a lot more user-friendly interface than using a nid.

If you're using Drupal 7.x, the current recommendation is to use the Entity Reference module which takes over from the Node Reference module in CCK.

If you're using Drupal 6.x., you want to enable the Node Reference field which is part of the CCK module. This still leaves a migration path to 7.x by upgrading to the 'References' field module, and then migrating your reference fields to Entity Reference fields.


How to convert field labels to search boxes in views

Since these are completely different things you may want to add the autocomplete fields as exposed filters from the view and then add them to the label using javascript. You could use jQuery .append into the label tag with a click listener.


You need to change the image field associated with the user profile to Public, and then you need to migrate any existing private image files to the new public directory.  Here's a write-up on working with files in Drupal 7.


How to make sure the footer is always at the bottom?

You can make use of the calc() expression, and use min-height instead of height. Say your footer height is 100px:

body{
  min-height : 100%;
  min-height: -moz-calc(100% - 100px); /* Firefox */
  min-height: -webkit-calc(100% - 100px); /* Chrome, Safari */
  min-height: calc(100% - 100px); /* IE9+ browsers */
}
footer{
  height: 100px;
}

Get more info about calc() here


How to reuse object between Drupal Behaviors?

I'll focus on the inclusion first, then describe what Clive was referring to, while mentioning that your JS is not valid:

For your use case you should add a common library to your module/theme that extends the Drupal object. (You don't even have to extend the Drupal object, but can create an own one, if you prefer.)

Then use dependencies to make sure the object is available in your basic page JS, as well as in your article JS.

Example

In your *.libraries.yml

mymodule/common:
  js:
    js/mymodule-common.js: {}
  dependencies:
    - core/drupal
    - core/jquery

mymodule/page:
  js:
    js/mymodule-page.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

mymodule/article:
  js:
    js/mymodule-article.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

You can then split your JS to the three separate files containing your code. The dependencies section makes sure the scripts your library depends on are loaded before.

Now to the scripts itself:

mymodule-common.js

(function($) {
  'use strict';

  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

})(jQuery);

mymodule-page.js

(function($) {
  'use strict';

  Drupal.behaviors.customName = {
    attach: function(context, setting) {
      $('body').once('customName').each(function() {
        var func1 = Drupal.customObj;
        var results = func1.function1($('body'));
        //process results
      });
    }
  };

})(jQuery);

And similar in your mymodule-article.js.

And here the promised feedback to the comment of Clive: Compare the attach property in the last example. It expects a callable that will be executed every time a page/ajax load finished. Within its body you can then do your magic.

References:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Term lineage in simple Hierarchical select module

With views you can use SHS which will provide simple Hierarchical select as selection type in expose filter.

To attach the parent term to node, you need to use the combination of Display Suite, Panels and entity module with token.
You can use parent term's token in Display Suit of default layout or any you want to use.


What's the difference between indexed and non-indexed field in Views and Search API?

Simple:

Title provided for Views from Content entity.
Title (indexed field) provided for Views from SOLR.

For example: You have 1000 contents, and you want to show 10 of these, titles of that starts "Z" letter.
If you use Title as filter - Drupal will use it by Views handlers, so:

It will request data from SOLR server, in our case - all 1000 items.
The Views filter on found items, reducing it to the required 10 "Z" contents.

As you see - it's not good for performance. Better is using Title (indexed field)as Views filter, that will request only required 10 records from SOLR server.
p.s. Against it, title will prefer for Views output than indexed field (for some cases).


Ajax submission not working for Webform within a node

This is a gotcha of AJAX forms.
When you load an AJAX form via AJAX it loses its AJAX functionality.
In order to keep it working, for the form that is getting loaded via ajax, you need to add a url and options keys to #ajax
/*
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // I created a webform called "test"
  if ($form_id == 'webform_submission_test_add_form') {
    $webform_id = 'test';
    $form['actions']['submit']['#ajax']['url'] = \Drupal\Core\Url::fromRoute('entity.webform.canonical', ['webform' => $webform_id]);
    $form['actions']['submit']['#ajax']['options'] = [
      'query' => [
        Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ];
  }

}

Side note: this loss of AJAX issue doesn't occur with the HTML way of opening dialog boxes
<a class="use-ajax"
   data-dialog-options="{&quot;width&quot;:600}"
   data-dialog-type="modal"
   href="/form/test">
   Should load Test webform in a Modal
</a>

because it has the URL of the form and knows its an AJAX request from the class name.


How to disable option for users who aren't logged in

Use the premium content module

Restricts access to premium content by role and provides a general API
for other modules to help decide if a user has access to premium
content.
This is useful on a news or membership site where teasers are
available to the general public but the full body is only available to
privileged users. Premium nodes appear in listings with full title and
teaser available to anyone. If a user does not have adequate
privileges, the default behavior is to show a simple message, but you
can use Panels or theme overrides to do more custom things.

All you need to do is enable the module, go to the edit page(admin/structure/types/manage/yourcontenttype) of the content type you want to make premium, and on the publishing options tab, select premium content


Custom migration source plugin not enabled in source site error

Your source module should be "node" since that's what you're extending.
/**
* Drupal 7 node source from database.
*
* @MigrateSource(
*   id = "my_xtra_node",
*   source_module = "node"
* )
*/


Drupal forms don't reside in any particular template. They are defined in the code. When a form is displayed, the code is read, it is then made available for modification by other modules before being rendered by a function called drupal_render() this will then use various template files to build the form which its displayed to the user.

It is fairly simple to add a field to the login form using hook_form_alter().

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form['myfield'] = array(
      '#type' => 'text',
      '#title' => t('code'),
    );
  }
}

What is perhaps more tricky is deciding what to do with this, are you using it for a second form of authentication?

A final note is on where to put the code. Drupal is fairly flexible, in that you can put theme files in modules and functionality in themes. However best practice is to keep features in modules, it leeds to a more manageable system in the long run.


How can I make my site only accessible to logged-in users?

There is a permission in the permissions list called "View published content". The permissions are set under /admin/people/permissions. You can remove this permission from the Anonymous user.

If you want to show some pages but not all of them, more granular access controls can be set up with Content Access.

Custom 404 and 403 pages can be set to use any content on your site, using settings at /admin/config/system/site-information (in Drupal 7). Sidebars are automatically hidden on 404 and 403 pages but if there are any other blocks (such as menus) you want to hide, you can control which roles see those on their block config pages.

The content of these nodes will also be unaccessible to anonymous users unless you install Content Access and make at least th 403 page allowed for anonymous users. I suggest allowing the 404 page too. Otherwise, you can still get info through if you put it in a node-specific template for your custom 404 page.

The login block can also be invoked programmatically in a tpl.php file with the code from this d.o comment or it can be shown to anonymous users via the block settings.


It looks like you have only one state (approve). You really want to have at least two. Try adding draft. Configure the workflow so that on creation the node goes to the draft state. This should work:

From / To     draft      approved
(creation)    author         -
draft                    editor
approved        -


Show referenced nodes as links if they have content in a field

This can be done in Views with no PHP or templating.

Add 2 title fields, one that is a link to the content and one that isnt.

Exclude both fields from display.

Add a body field and rewrite the output of the field. Use a replacement pattern thats the node title which is a link.

Under no results behavior add the token thats the node title which isnt a link. Make sure 'Hide rewriting if empty' is not checked.


How can I generate similar sets of fields in views quickly from within the views ui?

The easiest thing to do it to add all of the common fields to the Master display, and then a few displays to the view that get customized for the individual uses using overrides.


How can I shorten Facet API urls programatically?

You want facetapi_alias.

The facets already have a setting "facet alias" internally, which can be different from the facet machine name.
But this setting is not exposed in the UI natively.

The FacetAPI Alias module simply exposes this setting on the facet display form.

If you want more advanced solutions, you could use facetapi pretty paths (as you mentioned), or write your own FacetapiUrlProcessor. I have done the latter, and I can tell you it was painful :)


Is the "Count content views" settings related to the "Discard access logs older than" option?

According my review, I confirm that "Most popular" default statistics (Drupal 6), give the "most popular" "al time" since "Count content views" option was enabled.

So, I reviewed several modules like Statspro, Visitors, Quickstats, Reports and Radioactivity, and I chose Radioactivity to solve this. Radioactivity give results, per day, very close to Analytics.


drush ard fails with error Database dump failed, drush 5.10.0 drupal 7.39

If mysqldump is not found, it means that you miss the mysql-client or mysql-client-5.5 package (if you are using Debian). Your version of Drush indicates that you are using Debian as it is severely outdated ;-)


Javascript hotel price/availability calendar

I figured it out using the standard Calendar plugin. You need to create the view as normal, then I created a custom block which embeds the view 6 times, calling it with a different month argument each time. Then I added some javascript magic to hide and show the calendars as required.

Create the block - PHP

/**
 * Implements hook_block_info().
  */
function viajes_block_info() {
  $blocks['viajes_room_prices'] = array(
    'info' => t('Viajes: Room prices and availability calendar'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/*
 * Implement hook_block_view()
 * Display the search form in a block
 */
function viajes_block_view($delta = '') {
   $block = array();

switch ($delta) {
    case 'viajes_room_prices':
        $block['subject'] = t('Disponibilidad de habitaciones');
                    $block['content'] = viajes_room_prices();
                    break;
    }

    return $block;
}

function viajes_room_prices() {
$MONTHS_TO_SHOW = 6;
$hotel_nid = arg(1);

//js is already added by the reservation form code, no need to add it again
//drupal_add_js(drupal_get_path('module', 'viajes') . '/js/hotels.js');
drupal_add_js(array('viajes_room_price' => array('max_months' => $MONTHS_TO_SHOW)), 'setting');

//previous/next controls
$ret =
'

' . t('Previous') . '

' . t('Next') . '

';

//calendars
for ($i=0; $i<=$MONTHS_TO_SHOW-1; $i++) {
    $date = strtotime(date('Y-m-d').' +'.$i.' month');

    $ret .=
    '

' .
            date('F',$date) . ' ' . date('Y',$date) .
        '

' .
            views_embed_view('room_prices', 'page_1', $hotel_nid, date('Y',$date).'-'.date('m',$date)) .
        '

';
}

return $ret;
}

The Javascript

(function($) {
Drupal.behaviors.viajes = {
    attach: function(context, settings) {
           /*
        * Room price/availability calendar
        */

        //next button click
        $('#viajes-rooms-next', context).click(function() {
            var curr = getCurrent();

            //re-enable previous button if we've just left the first month
            if (curr == 0) {
                $('#viajes-rooms-previous', context).removeClass('disabled');
            }

            //disable next button if we've just arrived at the last month
            if (curr == (getMaxMonths() - 2) ) {
                $(this).addClass('disabled');
            }

            //roll the calendar if we're not on the last month
            if (curr < (getMaxMonths() - 1) ) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr+1), context).removeClass('hidden');
            }
        });

        //previous button click
        $('#viajes-rooms-previous', context).click(function() {
            var curr = getCurrent();

            //disable previous button if we've just arrived at the first month
            if (curr == 1) {
                $(this).addClass('disabled');
            }

            //re-enable next button if we've just left the last month
            if (curr == (getMaxMonths() - 1) ) {
                $('#viajes-rooms-next', context).removeClass('disabled');
            }

            //roll the calendar back if we're not on the first month
            if (curr > 0) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr-1), context).removeClass('hidden');
            }
        });

        //get currently visible month
        function getCurrent() {
            for (i=0; i<=(getMaxMonths()-1); i++) {
                if (! $('#viajes-rooms-month-'+i, context).hasClass('hidden')) {
                    return i;
                }
            }
        }

        //wrapper for the max_months setting
        function getMaxMonths() {
            return Drupal.settings.viajes_room_price['max_months'];
        }

    }
}
})(jQuery);

Just make sure you have the following classes in your CSS:

.disabled a {
pointer-events: none;
    cursor: default;
color: #979797;
}

.hidden {
    display: none;
}


How to call pages by Ajax using javascript

Here is the code to make POST req to a webpage.

$('#yourid').click(function(e) {
    e.preventDefault();
    var theUrl = base_url + 'myModule/somepage';
    $.ajax({
        url: theUrl,
        type: "POST",
        data: "name=John&location=Boston"
        success: function(msg){
        alert(msg);
        $('#displydiv').html(msg);
    }
    });
});


Form API 'image_button' vs 'submit' breaks my AJAX form

You have to set an unique '#name' tag for EVERY button (submit, image_button, button) on the page. This worked for me.


How to flag node when "event date" has passed and send notice to authors of flagged nodes?

Yes it's perfectly possible to produce such notification using the Rules module. But I don't see any reason why you'd want, or need, to flag (using the Flag module?) such nodes.

Instead you can use an approach which is pretty similar to what I described in my answer to "How to send an email to an author on a specific date using date field specified in a node?", which uses the Rules Scheduler (submodule of Rules):

Change the weaning date to your expiration date.
Add some additional Rules Condition (in Step 3) to avoid sending such notification to checks if the delivery is still outstanding (if it is delivered already, you may not want to send such notification anymore ...). For that you could simply add some boolean field like "Delivered? (Yes/No), which you'd that use in that Rules Condition to be added.

Happy Rules-ing!

PS: should you have some reason to flag the node anyway, then that would be a straight forward enhancement you could add to this solution also.


You can define (extra) config options in a CKEditor profile. Go to example.com/admin/config/content/ckeditor then select the editor profile(s) in which you have enabled autosave and go to the "Advanced Options".

In the "Custom JavaScript configuration" field you can override config options like

config.autosave_saveDetectionSelectors = "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']";
config.autosave_delay = 5;

No need to alter any of the javascript files.


How to add weight to the total weight of the order witn Commerce Shipping with rules?

You should implement this hook in a custom module:

/**
 * Allows modules to alter the weight that has been determined for an order.
 *
 * @param &$weight
 *   The weight field value array representing the weight of the order or NULL
 *   if no weight has yet been determined.
 * @param $order
 *   The order object whose weight is being determined.
 * @param $unit
 *   The unit of measurement to use for the returned weight of the order.
 *
 * @see commerce_physical_order_weight()
 */
function hook_commerce_physical_order_weight_alter(&$weight, $order, $unit) {
  // No example.
}


I used to use the Taxonomy Image module. It has full views integration as well.

Features:

    Image configuration happens within existing admin/taxonomy menu structure.
    Admins can add custom tags to <img> markup when displaying images.
    Allows one-to-one term-to-image relationships.
    Allows many-to-one term-to-image relationships.
    Admin-permitted users can disable the images.
    Administrators can force images to be a standard size.
    May use the ImageCache module if it is available.
    Works with Views.
    Utilizes core file.inc and taxonomy.module APIs.
    Small module with specific, focused functionality.
    Add-on modules that virtually eliminate the need for theme changes.


How to find out which cron jobs are currently running?

The answer can be found in drupal_cron_run.  While it is the case that you can tell if Cron is currently running by calling lock_acquire('cron', ...)), just as Drupal does (don't forget to call lock_release too), Drupal does not in any way set any information about the individual cron hooks that it executes during a cron job.

If you need more control over cron job execution, you could always copy the drupal_cron_run function into your own module and modify it to suit.  drush_core_cron() does nothing other than call drupal_cron_run, so you could call your own cron function via drush ev 'mymodule_cron_run();' from your crontab.  If you did this, you would need to review the implementation of drupal_cron_run on every update of Drupal core, and check for any significant alterations in behavior, so you should only customize cron if it's really important that you do so.


Webform alter with ajax submit callback - field values are empty in callback

Someone guided me in the right direction. My Webform Confirmation setting was set to 'None'. After setting it to 'Inline', calling $form_state->getValues() finally returns the form values.


How does Drupal select default domain for relative links?

You can specify the domain in settings.php - it's the variable called $base_url (around line 271). It is not always necessary, but I've found it can prevent some unexpected errors if the domain is set explicitly. I'm not sure how Drupal decides the domain if the $base_url is not set. By default, the $base_url is commented out. To set it, remove the # in front and change www.example.com to your primary domain.

Are the links in the block built using a Drupal menu? I think when you set the leading slash, you actually circumvented Drupal's menu handling which is probably why it worked. If you set the $base_url, I think you could remove the leading slashes from the links.


You don't usually programmability import views, instead you provides default ones by implementing hook_views_api() (usually in MODULE.module) and hook_views_default_views() (usually in MODULE.views_default.inc). Your module should return an array of views object has build with the code provided by the export views UI:

/**
 * Implementation of hook_views_api().
 */
function MODULE_views_api() {
  return array(
    'api' => '3.0',
  );
}

/**
 * Implements hook_views_default_views().
 */
function MODULE_views_default_views() {
  $export = array();

  $view = new view;
  $view->name = 'foo';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Foo';

  [ ... ]

  $export['foo'] = $view;

  return $export;
}

The Features module can generate the code for this.


Node ID is missing in contextual filters

In the screenshot you show, it's Identifiant (ID), the third rown of the Contenu category (Catégorie in the screenshot).

Since the context filters have a category, the node ID is simply called Identifier or ID. There isn't any possibility to confuse it with other IDs, like the user ID, because other IDs have a different category. You cannot even confuse it with the revision ID (Identifiant (ID) de révision) or the UUID (Identifiant universel unique (UUID)).


You just need to implement hook_theme_registry_alter() to change the theme function that is called when theme('form_element') is invoked; normally the invoked theme function is theme_form_element().

function theme_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  $output = '
\n";
  $required = !empty($element['#required']) ? '*' : '';

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' ' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
    else {
      $output .= ' ' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
  }

  $output .= "
\n";

  return $output;
}

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['form_element']) {
    $theme_registry['form_element']['function'] = "theme_mymodule_form_element";
  }
}

Using the code of theme_form_element(), you can write your own theme function, and remove the HTML tags you don't want. Take in mind that theme('form_element') is invoked for every form element output with the form API; if you want to change the HTML output of just a form element, then you need to check the #type value.
theme_textfield() is the theme function that themes a text field, but it doesn't output the label, or the wrapping
, which is already output by theme_form_element().

Alternatively, this can be done in a theme that overrides theme_form_element().
Which approach you should use depends on if you need to alter the output in a specific theme, or for all the themes enabled in your Drupal site; in the latter case, you need to implement the hooks I reported in a module.


How to enable bootstrap tooltip and popover (on a bootstrap based theme)?

I could enable the tooltip and popover by adding the code below to my node--mytype.tpl.php:

<script>
(function($) {
$(document).ready(function() {
$('[data-toggle=tooltip]').tooltip();
});
})(jQuery);
</script>

I added this JavaScript to my custom node--mytype.tpl.php because I wanted to use tooltip only on that content type.

If you want to use the tooltip anywhere on the website (eg on the blocks), you should add the code above to your theme's html.tpl.php file, just before the closing body tag.


Create a custom template file node--type.tpl.php where type is the machine name of your content type.

Place it in your theme's templates folder /sites/all/themes/YOURTHEME/templates and clear/flush the cache to see changes.

Ex: Article content type: node--article.tpl.php

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

// custom html goes here

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


Search button text not showing in a Bootstrap sub-theme

The solution I found for this was to copy this file from the Bootstrap theme directory

src/Plugin/Form/SearchBlockForm.php

to the same location in your sub-theme.

Then you can set the icon_only property to FALSE.

e.g.

<?php
/**
 * @file
 * Contains \Drupal\subtheme\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\subtheme\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Plugin\Form\FormBase;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function alterFormElement(Element $form, FormStateInterface $form_state, $form_id = NULL) {
    $form->actions->submit->setProperty('icon_only', FALSE);
    $form->keys->setProperty('input_group_button', FALSE);
  }

}

I still think there must be an easier way... but until then.


Producing collapsible field sets with theme functions

You can call theme_fieldset() directly, even if it's not for a form, as long as you structure the $element correctly:
https://api.drupal.org/api/drupal/includes!form.inc/function/theme_fieldset/6

You can see an exemple in core here:
https://api.drupal.org/api/drupal/modules!system!system.admin.inc/function/theme_system_modules/6

$fieldset = array(
  '#title' => t($package),
  '#collapsible' => TRUE,
  '#collapsed' => ($package == 'Core - required'),
  '#value' => theme('table', $header, $rows, array('class' => 'package')),
);
$output .= theme('fieldset', $fieldset);

theme_fieldset() is also valid in Drupal 7, but it seems to have changed in Drupal 8.


Can theme function be implemented in a module file?

Modules can create the initial implementation of a theme function but they can't override existing theme functions.

Modules do have one option available which should be used as a last resort: hook_theme_registry_alter. I would advise against every using this, since it will lead to code that's harder to maintain, and make it hard on those needing to theme the site. Also modules should be design never worry about theme functions of other modules, that is why we have themes. With that being said, if you change the theme registry you can change which function will be used regardless of what is normal practice, meaning that you will overwrite functions defined in themes. You can however use logic to prevent that from happening, but it can easily lead to many WTF moments, especially 6-12 months from now when you or some one else need to maintain the site.


I think the standard way to handle this would be to implement hook_node_access(), make your checks there, and deny access if any of your conditions aren't met.

This will result in the standard 403 page when a user without the correct permissions tries to access the page, which semantically speaking would probably be the best result.

The code might look something like:

function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'my_type' && ($op == 'create' || $op == 'update')) {
    if ($account->something == 'something') { // allow access
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }

  // Return the default ignore value if your module doesn't need to get involved in this decision
  return NODE_ACCESS_IGNORE;
}


It might be possible to add a conditional filter on the node type and then add custom PHP code to get the default value based on the currently viewed node. The code to do this should look like this: (should work both in D6 and D7):

if ($node = menu_get_object()) {
  return $node->type;
}

It would be cleaner to do that in a views handler, that is however quite a bit more complicated to set up than pasting the above code in the textfield in the views UI.


Migration from CSV: how to define a default value for autoincremental id field?

I finally understood that keys in source is the way to make each row of the csv file unique. It may be anything.
So I changed to:

  keys:
    - contract_id
    - member_id

I removed id: idfrom processand it works!
The value of id field in the database is properly auto-incremented.


field is Integer and I am getting PDOException error thrown

Using bigInt module is the best way for achieve this job, there is another solution like altering database table but it not recommanded


Getting index of item in items inside twig template

You can't, because the loop index is local. And you don't need a class with the index in the paragraph when you have it in the surrounding div for targeting it in CSS.

There is also a fundamental aspect with rendering referenced entities. They are cached and not necessarily rebuild when the order in the field changes. This is even more problematic for other entities than paragraphs, which can be used in more than one place in different orders.


Dynamic Payment Method required Input Field for Ubercart Checkout

It's a bit late but just for reference for anyone finding this page as a search result: From what I found out by experimenting, you are right that you need to return an element. Actually what I had to do in my case was to use the following code:

$form = array();
$form['mobile_phone'] = array(
  '#type' => 'textfield',
  '#title' => t('Mobile phone'),
  '#description' => t('Enter your mobile phone number here and a PIN will get sent to you.'),
);
return $form;

You just build a normal form and it gets drupal_rendered when needed.


Is it possible to put existing/shared Content type fields as Feature code each in their own individual file to simplify/avoid git merge conflicts?

We faced similar problems, what we did was, we created a 4 features of similar fields that were used in multiple content types. This made sure that if a person is working on a similar funtionaltiy, he is responsible for all the content types.
Yes, we still need to be careful for this, but dividing it into multiple features did solve many issues.


Override node.tpl.php for the Front Page

You have to create page--front.tpl.php from page.tpl.php. You are changing  your front page, not the node.


You're going to need to override an existing theme function in order alter the HTML output for the date popups. You can override a theme function either from within your template.php file within your theme, or from within a custom module.

Whenever I need to identify the correct theme function to override in a hurry, I use a module called Devel Themer. It allows you to click on any on page element, and provides you with a great break down of all the theme functions and variables associated with the element you're trying to override.

Hope this helps.

EDIT: including theme function link

The theme function you need to override is theme_select


Integer user form field with min 11 digits and max 11 digits

Go to admin/config/people/accounts/fields add an integer field and set the limitations and by hook_user_update you can check the validation after saving the user profile.


Send data from controller to hook_form_alter()

I think you should not load the data in your controller but in your hook_form_alter. Redirect the user to a path containing a query parameter in Url, so that the url may look like "http://www.yoursite.com/node/add/movies_movie?guid=123" and change the guid paramter to the value of the movie.

Then in your hook_form_alter:

$request = \Drupal::request();
$guid = $request->query->get('guid');

if ($system === "IMDB" && $guid) {
    $database = new ImdbDatabase;
    $movie = $database->getDataById($guid);

    // fill in the values of the movie into the form fields
}


Fatal error: Class 'DrupalDefaultEntityController' not found in comment.module

After a bit of research, I found out that the problem might be generated from entity.inc inside the includes folder.
Therefore, I tried to put back the previous entity.inc (from the 7.65 installation); subsequently, I run the update.php script, and after another refresh, the website is finally accessible.
I done few more tests to check if there are warnings or errors, but everything seems to work fine, so somehow I got it sorted.


Better Performance by putting image dimensions

This is a known issue in Drupal 7. A conscious choice, as it were, from the issue Remove unnecessary I/O from theme_image().

There is a patch to fix this here: Images are not printed with height and width.


You can turn it off in the UI at admin/structure/types/manage/type-name with the "Allow comment title" checkbox:


render function receives an arguemnt as reference, you should pass a variable instaed of function:

$var = field_view_field('node', $node, 'field_introduction', array('label'=>'hidden'));
print render($var);


The best way to achieve this is to create a separate page display for all content on a single page.  Then add a Footer to the title display with a link to the full page display.


Layout of multiple items of the same field in Panels node template

Edit your content type and Use a field collection. instead of multiple fields. It's difficult to achieve what you want without explicit entities.

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

Field collection will allow you to add multiple fields into one group, so instead of adding data to each field, you can just keep adding groups of data.
This will allow you to add a collection of Artist, track number, track title, mp3 Then when you call the field collection via panels it will give you the results you want.

You are using multiple fields which will list the values from each individual field right underneath eachother.


Disable user creation at login with Simple LDAP

As you are describing it, this is not possible. You can limit authentication and user creation to only LDAP accounts, but you must have a local Drupal user.


How to truncating url at the word instead of limit

The pathauto module uses the core function truncate_utf8() to truncate the alias. This call by pathauto uses $wordsafe=TRUE in the call to preserve word boundaries.

If you are seeing partial words in the path, this is a core issue for truncate_utf8, not a pathauto issue.


Why is drupal spitting out urls like entity:/node-1474 instead of /node-1474

You have to use .url instead of .uri, like this:

{{ item.content['#paragraph'].field_home_slider_button_link.0.url }}

I don’t think this works on older versions of Drupal 8, so if it doesn’t work you can try this:

{{ item.content['#paragraph'].field_home_slider_button_link.0['#url'] }}


Drupal Webforms arrange fields and labels

There is a module Arrange Fields which will help you.With this modle you can Drag and drop fields into any arrangement you want.