Embedded Media Field Video: Output both Video Flash Object and Video Thumbnail in Node Display?

One way to do it is to set the video field display mode to full video under /content/types/CONTENT_TYPE/display then add the thumbnail via theme_emvideo_video_thumbnail() as a variable using themename_preprocess_node(&$vars) in your theme's template.php -OR- print it directly in your node.tpl

The trick to theme_emvideo_video_thumbnail(($field, $item, $formatter, $node, $no_link = FALSE, $options = array())) is to provide all the right parameters. Especially $options

e.g.

<?php
  // code adapted from emvideo.theme.inc
  // ignore the <?php tag

  $system_types = _content_type_info();
  $field_name = 'field_video'; // the machine name of your video field

  $field = $system_types['fields'][$field_name];
  $field['widget'] = $system_types['content types'][$node->type]['fields'][$field_name]['widget']; // get CCK widget data. includes all formatting settings

  $options['return_url'] = TRUE; //return URL
  $options['raw'] = TRUE; // return image path. Otherwise node path is returned

  print theme('emvideo_video_thumbnail', $field, $node->{$field_name}[0], 'video_thumbnail', $node, FALSE, $options);

In template.php

<?php
// change MYTHEME with the theme's machine name or use phptemplate
function MYTHEME_preprocess_node(&$vars) {
  if ($vars->type == "mynodetype") {
    // see code above
    $vars->video_thumbnail = theme('emvideo_video_thumbnail'...);
  }
}

Then <?php print $video_thumbnail; ?> where you need it in node.tpl.php (-OR- use the first code block directly in the node template)

Hope it helps.


There doesn't seem to be a structured way to shoehorn an advanced join like that into an API query...so you'll probably just have to go manually:

$query = db_select('pop_links_stats', 'p')
  ->fields('p', array('cid'))
  ->fields('n', array('nid'))
  ->fields('nrev', array('vid'))
  ->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')
  ->groupBy('p.nid')
  ->groupBy('p.hostname');

$query->addExpression('FROM_UNIXTIME(p.timestamp)', 'p_timestamp');
$query->addExpression('FROM_UNIXTIME(nrev.timestamp)', 'nrev_timestamp');

$query->join('node', 'n', 'n.nid = p.nid');
$query->join('node_revision', 'nrev', 'nrev.vid = (SELECT max(vid) FROM {node_revision} nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )');

That produces:

SELECT p.cid AS cid, n.nid AS nid, nrev.vid AS vid, FROM_UNIXTIME(p.timestamp) AS p_timestamp, FROM_UNIXTIME(nrev.timestamp) AS nrev_timestamp
FROM
{pop_links_stats} p
INNER JOIN {node} n ON n.nid = p.nid
INNER JOIN {node_revision} nrev ON nrev.vid = (SELECT max(vid) FROM node_revision nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )
GROUP BY DATE(FROM_UNIXTIME(p.timestamp)), p.nid, p.hostname


How to update drupal 7.7 to 7.8 manually?

See this article from the Drupal.org documentation under section "MINOR VERSION UPDATES".

  To update from one minor 7.x version of Drupal to any later 7.x
  version, after following the instructions in the Introduction section
  at the top of this file:

  Log in as a user with the permission "Administer software updates".
  Go to Administration > Configuration > Development > Maintenance mode. Enable the "Put site into maintenance mode"
  checkbox and save     the configuration.
  Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles'
  directory     and any custom files you added elsewhere.
  Download the latest Drupal 7.x release from http://drupal.org/project/drupal to a directory outside of your web
  root. Extract the archive and copy the files into your Drupal
  directory.
  Re-apply any modifications to files such as .htaccess or robots.txt.
  Run update.php by visiting http://www.example.com/update.php (replace www.example.com with your domain name). This will update
  the    core database tables.
  Go to Administration > Reports > Status report. Verify that everything is working as expected.
  Ensure that $update_free_access is FALSE in settings.php.
  Go to Administration > Configuration > Development > Maintenance mode. Disable the "Put site into maintenance mode" checkbox and save
  the configuration.


How to auto-assign a user a particular role when that user gets autocreated in a content form?

Note: I use this in a project and it works (it does not use the Entityreference Autocreate module).

First alter the artist form and add a custom validate and a custom submit

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'artist_node_form') {

            //hidding the Entity Reference field (User), it will be created in the process
            unset($form['field_user']);

            if (!isset($node->nid) || isset($node->is_new)) {
                $form['field_username'] = array(
                    '#type' => 'container',
                    '#weight' => 3,
                    'field_username' => array(
                        '#type' => 'textfield',
                        '#title' => t('Username'),
                        '#maxlength' => 60,
                        '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
                        '#required' => TRUE,
                        '#attributes' => array(
                            'class' => array(
                                'username',
                                ),
                            ),
                        '#default_value' => '',
                        '#access' => TRUE,
                        '#weight' => -10,
                        )
                    );

                $form['field_password'] = array(
                    '#type' => 'container',
                    '#weight' => 4,
                    'field_password' => array(
                        '#type' => 'password_confirm',
                        '#size' => 25,
                        '#description' => t('Provide a password for the new account in both fields.'),
                        '#required' => TRUE,
                        ),
                    );

       $form['#validate'][] = 'artist_node_form_validate';
       $form['#submit'][] = 'artist_node_form_submit';
    }
  }
}

In the custom validate you need to validate the username and check if the username is available.

function artist_node_form_validate($form, &$form_state) {
    $valid_user = user_validate_name($form_state['values']['field_username']);
    if(!is_null($valid_user)) {
        form_set_error('field_username', $valid_user);
    } else {
        $user = user_load_by_name($form_state['values']['field_username']);
        if($user){
            form_set_error('field_username', t('The username @username already exist.', array('@username' => $form_state['values']['field_username'])));
        } else {
            $form['field_username'];
        }
    }
}

In the custom submit you will create the user

function artist_node_form_submit($form, &$form_state) {
    $new_user = array(
        'name' => $form_state['values']['field_username'],
        'pass' => $form_state['values']['field_password'], // note: do not md5 the password
        'mail' => $form_state['values']['field_email'][LANGUAGE_NONE][0]['email'],
        'status' => 1
        );

    //The first parameter is sent blank so a new user is created.
    $new_user = user_save('', $new_user);

    //assigning the role
    $role = user_role_load_by_name("artist");
    user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);

    //field_user is the Entity Reference field
    $form_state['values']['field_user'][LANGUAGE_NONE][0]['target_id'] = $new_user->uid;

}


Reverse geocoding (country) from geofield with coordinates

this is a question that I asked to myself some time ago. I suggest to start from the geocoder module.
This module "translate" an address to a lat./lon. parameter that could be displayed in a map.
Reversing this process - if I understand correctly your question - seems to be a WIP: actually, no out-of-the-box solution.
But you can check and try the suggestions in this discussion.


Dealing with absolute paths while on localhost

You should just set the $base_url in your settings file while you're working on localhost, then you can just change it when you put the site live.

The settings file is at "sites/default/settings.php" and you should add:

$base_url = 'http://localhost:8888/mylocalproject';

Obviously when the site goes live you want to change/remove that line to match your new environment.


Creating a node with PHP cURL client returns 401 error - X-CSRF token always empty

I fixed the DrupalREST class by Randall Kent here https://github.com/RandallKent/DrupalREST.PHP/issues/2


Getting an error while installing drupal 7 using xampp

Try to compare & update these values in php.ini.

  max_execution_time = 300

  max_input_time = 180

  max_input_nesting_level = 300

  memory_limit = 512M

Note : After these changes, restart the server.


Compatible with PHP 7.2?

Yes, currently the only issue I see in the issue queue is:

PHP 7.2 Warning: A non-numeric value encountered in commerce_currency_amount_to_decimal()

You'll have to apply this patch yourself since it has not been committed.


How do I add a  class based on the visibility of a block?

You have to do it via the template_preprocess_html function.

Add this to your theme's template.php file:

function MYTHEME_preprocess_html(&$variables) {
  // dpm($variables);
  $node = menu_get_object();
  if (isset($node) && isset($variables['page']['sidebar_first']['system_navigation'])) {
     $variables['classes_array'][] = 'system-navigation';
  }
}

In the above code I am looking for the system navigation block in the sidebar first region and if it is there I am adding system-navigation class to the classes array. I am also checking if I am on a node page via the call to menu_get_object()

You will have to adapt the code to your use case.

Install the devel module, then uncomment the dpm statement. Then look under the page variable at other variables without a # in front of them.


How do I edit the format of things published to the front page?

It also possible with Views, if you set the Style (listed in the Basic Settings section) to Fields. You can then choose whatever Fields you like to be displayed.

Like you already mention yourself, it is possible with Display Suite. If you choose to work with Display Suite, you can select a Display Suite build mode in the Style option of a View.


listing users filtered by whether they have posted content or not

Have you tried using Relationships instead? User:Nodes authored might be what you are looking for.


Show active taxonomy term as title of product category view

Edit your Contextual filter and you'll see the option to override the title in the section for when the filter argument is present or a default is provided.

You can use tokens from the Replacement patterns section to construct the title text.

Your "menu" is likely also coming from the Contextual filter, set to the "Summary" option.

Another way is to add the title in the Views Header, you can see how it's implemented in the "Taxonomy term" Views.


After DB backup and restore: Call to undefined function user_access() in ...includes/menu.inc

Here are few tips:

make sure your Drupal core has all the files in the right place (especially user module),
upgrade your Drupal core to the latest version (drush fr && drush up drupal)
clear all your caches (drush -y cc all), including your memcached (killall memcached),
rebuild your registry by using Registry Rebuild,
if you're using modules which are implementing drupal_bootstrap() (such as Secure Site), disable them,
try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem,
use XDebug and generate a trace file to analyse the code execution,
or use IDE debugger, breakpoint on the failing line and check why the function doesn't exist,
test it on different environment/machine,
eventually restore your database from the point where it was working before.


How to add unique classes to FlexSlider slides? (default behavior in v 7.1.x - not in v 7.2.x)

OK - I was over thinking this. This script will add id 1, 2, 3 etc to my slides. The slides are just list items - I was all intimidated because only one li is visible at a time, but jQuery doesn't care...

/*Script for assigning each flexslider slide a unique class*/
(function($){
$(document).ready(function(){
    $('.slides li').each(function(i,el){
        el.id = i+1;
        });
    });
})(jQuery);


You want to take advantage of the PagerDefault class.

Write your query as a db_select query which I'll leave as an exercise for the reader because, frankly, I'm not sure if it's possible to create a db_select query with a subquery as part of an expression like that :).  Assuming you build up your select query in a variable called $query, you'd have code along these lines:

$query = db_select('REPORT_LIST_VIEW')->extend('PagerDefault');
...build up $query object here...
$res = $query->execute();

$pager = drupal_render(array('#theme' => 'pager'));

Then just output $pager wherever you want it.

Also, in general, I'd recommend placing this in a block rather than hard-coding it into your theme so that it's more reusable.


How do I modify menu links depending on context?

So finally Menu Token is the way to go. Once installed, created my menu entries and set them up using tokens this way:

Please notice the relative link token together with the one-level-up part before last part of path:  /[current-page:url:relative]/../presentation. This preserves the relative static path before the last dynamic part as in this case I wanted to make the dynamic menu relative to each <department>/<group> path. Also remember to check Use tokens and select Method for Node: Context for Node.

Hope it helps.


Expose a view filter that lists usernames of a specific roll in a roll down menu

It is easy , add new filter , choose your field (the field which takes the user) , in filter settings limit users to users in your specific roles (1 or more roles could be selected) and then expose filter with equal operator for user , and user can restrict shown content to a specific user .


What does parent::form($form, $form_state) do?

If you look at ContentEntityForm::form(), the method called with parent::form() since ContentEntityForm is the parent class, you will notice what exactly it is doing.

  $form = parent::form($form, $form_state);
  // Content entity forms do not use the parent's #after_build callback
  // because they only need to rebuild the entity in the validation and the
  // submit handler because Field API uses its own #after_build callback for
  // its widgets.
  unset($form['#after_build']);

  $this->getFormDisplay($form_state)->buildForm($this->entity, $form, $form_state);
  // Allow modules to act before and after form language is updated.
  $form['#entity_builders']['update_form_langcode'] = [$this, 'updateFormLangcode'];
  return $form;

It doesn't significantly change the form, so it is expected the form doesn't apparently change, or it is rendered the same if you don't call parent::form(), but (as the comment says), it allows modules to act when the form language is updated. You could not see anything different, but you are actually avoiding modules can do anything when the form language is changed.


If you want to add arbitrary code to the <head> element you need to:

Take a copy of the core html.tpl.php file and put it in your theme somewhere
Clear the caches so it gets added to the theme registry
Implement hook_preprocess_html() in your theme's template.php file like so

function MYTHEME_preprocess_html(&$vars) {
  $vars['some_var'] = 'Something';
}

In the html.tpl.php file, use

print $some_var;

wherever that might be appropriate.

If you want to add structured code to the <head> tag then use drupal_add_html_head().

Finally, specifically to add JS to the page, you can use drupal_add_js(). But that needs to happen before the HTML template is processed. hook_preprocess_page() would be one option, but there are many, depending on the context that makes up your page.

You'll find the Theming guide, and questions already asked on this site, invaluable if you're learning the theme system from scratch.


Can I use Feature for development and CMI only for deployment?

Some comments according to the limited experience i have on CMI myself.

I believe that what you ask is pretty much logical, due to the fact that local dev envs usually end up being different than the actual remote Dev instance. Testing modules, code, configuration e.t.c is pretty much the reason for that.
This makes default CMI functionality unusable as you dont want to move the whole configuration into your actual deployment process (DEV->IGR->PROD).

This problem is addressed quite well using Features, however it could also be tackled by some CMI related modules such as Config partial export or Configuration Split

One more argument in favour of Features might be that you are able to have totally different local dev envs than the remote Dev (Dest site UUID != Source site UUID) which i guess would make CMI unusable.


I really think you should dive into Drupal's Examples Module to look at how a lot of the hooks and so forth you are (mis)using actually work.

But, quickly:

function subscription_menu() {

  $items=array();

  $items[ 'subscriptions' ] = array(
    'title' => 'View the Subscribers',
    'description' => 'Subscription form available for subscribers',
    'page callback' => 'subscription_records',
    'access arguments' => array( 'access content' ),
    'file' => 'subscription.pages.inc'
  );

  return $items;

}

and

function subscription_records() {

  $result = db_query('SELECT * FROM {subscribe}');
  $records = $result->fetchAll();

  $content = '<pre>' . print_r($records, TRUE) . '</pre>';

  return $content;

}

clean up most of the glaring misunderstandings.

However, you will still need to look into Render Arrays and Dynamic Queries to really clean up your code, as well as the Drupal Theming Guide with special attention to theme_table() to create the page you seem to be after.  And, of course, if you need user input, the Form API Reference is a must. But, once again, all of these are explained and demonstrated in the Examples Module.


How to display a node in overlay popup effect?

Let me answer my own question. Based on j2r's comments and http://drupal.org/node/1378438 question from this node I was able to solve my issue.

Create href as node/nid/lightbox and rel as lightframe. This will result in displaying the whole page in the lightbox. To avoid this U need to create a page--contenttype.tpl.php (In my case) http://www.digett.com/blog/01/11/2012/overriding-page-templates-content-type-drupal-7 and then remove the header, footer and other unwanted regions in the page.

Once this is done I am sure u will get as what I got.


Changing CCK field value(s) by clicking URL - possible? Advisable?

It's feasible but not advisable. Drupal's standard for changing data via URLs:
1) Use _GET variables (or simple URL paths) to _access_data
2) Use _POST variables to change data

Along with using _POST, you would want to use Drupal's Form API so that tokens and fields are generated and validated.

Options you could do to change the data via URL (e.g. link) is to:
1) Add a token to URL to validate it's only used once (or other validation necessary)
2) Ensure user is logged in (and maybe ensure he is owner of that ticket, etc.)
Hope this helps.


drush sql-sync doesnt extract gzipped sql

In Drush 6, the sql-sync command on the source system composed bash commands, and executed them on the remote system as needed via ssh.

In Drush 7, the sql-sync command on the source system uses drush_invoke_process to operate on the remote system. Drush 6 did not support the gzip features that Drush 7's sql-sync command requires.

You don't specifically mention if the system you are running sql-sync on is Drush 7 or Drush 8 or something else, but Drush 8 is substantially similar to Drush 7 vis-a-vis sql-sync implementation.

You should be able to use gzip to send sql dumps to @tmp.coe, but only if you use Drush 6 on the source. Drush 6 is no longer supported, but I believe it also supported transfer between two remotes. You should therefore be able to install Drush 6 on your local system, and perhaps name it drush6 and use it only for this purpose.


How to implement grouped filters filtered by roles?

Clone the view you already have into an additional views display, add the exposed grouped filters to that cloned views display, and then limited that additional views display to only those "certain roles".


You can use template_proprecess_page hook to achieve this as shown below:

function <THEME_NAME>_preprocess_page(&$vars) {
    if (arg(0) == 'node' && in_array(arg(1), array(9, 11))) {
        $vars['theme_hook_suggestion'][] = 'page__node__9and11'; //For page--node--9and11.tpl.php
    }
}

Add above code to template.php of your theme & clear cache.


You want Admin menu source. It allows you to configure each role with a menu as the source for admin_menu.


Your code is using the following line:

$terms_name = print $term_name->name;

You are assigning to $terms_name the value returned by print $term_name->name, which is 1.
If you try executing $var = print "ciao";, you will notice that the value assigned to $var is 1.

The other issue with that code is that $term_name is not a variable defined from the code you showed; executing that code, you get an "access to a not defined variable" error.


Using Docker4Drupal in Production vs. its commercial Wodby solution

Disclosure: I'm a Docker4Drupal maintainer and Wodby co-founder.

We do not limit usage of our images, it's MIT licensed, so if you want - go ahead and deploy the images in production. However, you'll have to do some work before that, e.g. set up a router, certificates, cron, etc. Configuring usual stuff with containers is not always obvious especially if you're not proficient with containers. Since we already handle all of this in our platform we've added this recommendation (people asked us about production). Also, stability requirements are higher for production (including freezing the docker version).

Originally, we created docker4drupal just to provide a local environment for our customers (instead of connecting Vagrant) but later it became obvious that it is valuable for many drupalers including those who do not use Wodby. In other words, historically, it was prod > local transition, not the other way around.


theming form of block subscription newsletter module

There are many ways. One is this way to theme the blocks.

There is simpler way to add a class to a block then add css in the theme info file.


What you can do is implementing a preprocess function for the node.tpl.php file, and alter the content of $variables['node_url'], which is the variable the template file uses when rendering the title.

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

You should first verify $variables['page'] is not TRUE, since that means the node is being shown in its own page, which is not what happens, for example, when the node is shown as teaser in the front page or in a view.


If I understand correct, no need to hardcode images: Add any image through the Drupal program itself via the API or background images via the css and a relative path:

For example, if your image is at theme/images, do {background: url(images/image.png);} or {background: url(../images/image.png);} if your css is situated in a folder of it's own inside the theme's folder.

You could filter or manipulate specific images with JS globally via a custom js file for your site as explained here.


If you chose auto-complete for your node reference field & if number of item to be added is set to unlimited then you get to re-order the values which appear.

Though my answer is not proper for question which you have asked as you are asking for select field but this way I have done it..


Display a field for a specific amount of time

I don't know what format your date field uses so you'll have to adjust for that, but something along the lines of

if(($content['field_date'] >= $first_date) && ($content['field_date'] <= $second_date)) {
  print render($content['field_date');
} else {
  print($wrong_date_message);
}

...where $first_date and $second_date are the beginning and end of the date window for which you want to display the field, and $wrong_date_message is whatever you want to show up there instead when the field isn't displayed.

For more information about date formats in PHP, check out http://php.net/date.


Emails are not triggering when MIME mail is selected

You can change the email template format From Custom Template to Default Template or you can create your own template using place it in templates folder (/sites/all/themes/your-theme-folder/templates) and name it webform-mail-webform-node-id.tpl.php


What hook is most appropriate for code that should run as early as possible in bootstrapping but only on certain paths?

Similar to the forms, there's hook_page_alter(), but that happens near the end, making it a bad place for redirects.

hook_init() should be fine, but is not invoked on cached pages.

hook_boot() sounds self-explaining; it's run so early that you can't call any module's function, not even drupal's.

however, since you need a conditional redirect and you already have your own module, just add it atop the page callback of 'foo/*'.

if that callback it's not defined in your module, use hook_menu_alter() to have that path pointing to a custom function that will execute your conditional redirect.


Add link to call by Skype in a message - relative reference

your link contains "skype" protocol that is filtered out by filter_xss_bad_protocol() Drupal core function.
You can install Filter Protocols module which allows you to configure allowed protocols. Skype protocol is not included in configuration by default, you'll have to add it yourself - then your skype link will work.


How can I get the current widgets name of a node?

From the docs of field_info_widget_types() :

Returns information about field widgets from hook_field_widget_info().
Parameters:
$widget_type: (optional) A widget type name. If omitted, all widget types will be returned.

You might be leaving the parameter empty. Hence, it is returning all field widgets. Pass the name of the widget from the current node, to get the right information. You can use menu_get_object() to get the node object of the current page, and find the appropriate widget to pass to field_info_widget_types().


hook_field_storage_create_field and hook_field_create are called when the user creates a new field, i.e. from "Manage Fields", "Add new field".  In my tests, hook_field_create was called as expected, but hook_field_storage_create_field was not called.  I did not look into why this was, because (a) you could use hook_field_create here just as well as hook_field_storage_create, and (b) this isn't really the approach you should be taking to implement the functionality you need.  If you were going to modify the schema for the link field, you would do it once when your module was installed, in hook_install.  Your use case is much more complicated than the standard behavior of the link field, though; you would be better off creating your own field type, and do all of your field storage management in one place.  You might want to look at the source for existing fields that have complex data storage needs, such as the date field.


Views Contextual Filters - User Name in URL

You should remove the "User: name" Relationship on the view and add a new relationship "User: uid". Then you can access the author view with /blog/author/123.

Then create a URL alias for "/blog/author/123" and set it to "/blog/author/john-smith". You will then be able to access the view with both the uid 123 or using john-smith.


Twig blocks are named control structures, you can't define them multiple times within the same scope. Either try to move the if statement inside one single block

{% if topic_type %}
  {% embed "node--teaser__field.html.twig" %}
    {%- block field_icon -%}
      {% if topic_type == 'test' %}
        icon 1
      {% else %}
        icon 2
      {% endif%}
    {%- endblock -%}
    {%- block field_value -%} {{ topic_type }} {%- endblock -%}
  {% endembed %}
{% endif %}

or don't overwrite the block at all, instead use variables and pass them down in the embed statement

{% set custom_icon = (topic_type == 'test' ? 'icon1' : 'icon2') %}
{% embed "node--teaser__field.html.twig" with {'icon': custom_icon, 'title': topic_type } %}

I'd recommend the first when there are major overwrites in the HTML output, and the 2nd when only strings/variables/placeholders are replaced.


Use field permissions module.

Add fields for these info & restrict the permissions for them to admin only.


Alter the form using [hook_form_alter][1]

<?php print views_embed_view('<Your view id>', $display_id = '<display id>'); ?>

Make that display:none; from CSS.


Redirect Using Rules Based on Account Role

Check that you are not using any other contrib modules like Login Toboggan which may be setting a redirect after log in.

Failing that, turn on Rules Debugging by going to admin/config/workflow/rules/settings and ticking the 'Log debug information to the system log' checkbox.

Log out and log back into your site as a student user. Then go to admin/reports/dblog and check the debugging messages set by Rules.

You will then be able to see which of your conditions is failing.


Is there a way to use a file field without having to upload the file when creating the content?

You should be able to give it a filename of public://... and use that. Just point it to the file you've uploaded.


The database is not bootstrapped in another docker container

Ok, this is solved now, thanks to leymannx and hansfn. I had to also install mysql-client in the workspace container, where drush was being executed from, in addition to the mysql-server running in its own container; mysql-client must have previously been present in the workspace container for a different reason, but some containers were stopped and restarted at some point, so any container-specific installations must have disappeared.


Job board: Faceted Search with "OR" operator, but sort results by most matching facet criterias/term count

Maybe this approach could be an alternative:
Instead of using the tags as facets/filters, I could use them just as search input.
when i'm typing my terms/tags within the search field of an apache-sold-search-page, i'm getting exactly the results sorted by their relevance:

Searching for filters/term instead of using them as real filters

So, maybe I have just to do a small piece of code, that automatically creates a search query based on the clicked term/tags…


For me, I just needed to uncomment 'RewriteBase /' in '.htacess'. Working now. I had forgotten this little detail.


Show content of custom content type in a block based on taxonomy term

What you're trying to do already come out of the box in "Taxonomy term" content views.

If you have tagged your Store product nodes with taxonomy terms these nodes will appear on the related term pages. You don't need a separate Block, the term pages will show a list of nodes tagged with that term.

You don't even need the Store content type if its whole purpose is to provide categorization. The "Store" Taxonomy Vocabulary is all you need.

Can you try and see if that is enough for you?

In your Contextual configuration you should use the option "Load default filter from term page", and not "Load default filter from node page" because the information is taken from the taxonomy term page, you're not showing a block on a node page.

Why do you need the second Contextual for NID? This is usually used when you want to exclude the current node from the list (Under More > Exclude), but you're not on a node page so there is nothing to comare the NID to. Remove that second Contextual, you don't need it.


How to "featurize" customizations to Answers module (or a content type that is part of a module)

For the customized views, I cloned and disabled the original views. Then I was able to pull the view (cloned one) into the feature.

For the content type customizations, I was able to pull in the new fields I created, and customizations to the other fields, by finding the names of the specific customized fields in field bases and strongarm in features.


How do I properly remove "Powered By Drupal"?

Use this technique

go to yoursite/admin/structure/block

you will see the "Powered by Drupal" as a block

Choose - None - it will go away and you can create your own block with your own footer information


The Ajax callback should only return the named FAPI element that is to be replaced. For example:

function questionaire_4D_selector_form_ajax_callback($form, $form_state) {
  // If the form has errors we show them in the Preview spot. There's not much
  // else we can do because jQuery is replacing out the specified
  // target element in the #ajax FAPI element.
  if (form_get_errors()) {
    return $form['preview-content-area']['esci-questionaire'];
  }
  return $form['preview-content-area']['esci-questionaire'];
}

Your form_builder function which build/rebuilds the form should examine the $form_state and alter the form as necessary based on the ajax submitted values:

/** Our form builder function */
function questionaire_4d_selector_form($form, &$form_state) {
 # for ajax inspection goto /tmp and view file output.
 #dd($form_state);
 #dpm($form_state);

  // This form responds to an AJAX submit button, and also a $_GET argument.
  $form_passed_get_parameter_questionaire_id = $form_state['submitted'] == FALSE &&
          count($form_state['build_info']['args']) &&
          ctype_digit($form_state['build_info']['args'][0]);
  #dpm($form_passed_get_parameter_questionaire_id ? 1 : 0);
  if ($form_passed_get_parameter_questionaire_id) {
    $id = $form_state['build_info']['args'][0];
  } else {
    $id = !empty($form_state['values']['questionaire_id']) ? $form_state['values']['questionaire_id'] : '';
  }
  #dpm($id);
  $form['questionaire_selector'] = array(
    '#type' => 'fieldset',
    '#title' => t('Select 4D Questionaire'),
  );
  $form['questionaire_selector']['access_id'] = array(
    '#type' => 'hidden',
    '#value' => drupal_get_token(QUESTIONAIRE_4D_PREVIEW_AJAX_SECRET_VALUE),
  );
  $form['questionaire_selector']['questionaire_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Questionaire Number'),
    '#default_value' => $id,
    '#element_validate' => array('element_validate_integer_positive'),
    '#size' => 15,
  );
  $form['questionaire_selector']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Preview 4D Questionaire'),
    '#ajax' => array(
      'callback' => 'questionaire_4d_selector_form_ajax_callback',
      'wrapper' => 'questionaire-preview',
      'method' => 'replace',
    ),
  );
  $form['preview-content-area'] = array(
    '#type' => 'fieldset',
  );
  $form['preview-content-area']['esci-questionaire'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'markup',
    '#markup' => '
Your Questionaire Preview will appear here.
',
  );

  // This says if we were given an remote 4D form id of say 23456, load it into the supplied FAPI
  // element.
  if ($form_passed_get_parameter_questionaire_id) {
    $remote_response = retrieve_questionaire_4d_response($id);
    if (strpos($remote_response->data, 'Error',0) === 0) {
      form_set_error('questionaire_selector', "Remote 4D Error
" . $remote_response->data);
    }
    $form['preview-content-area']['esci-questionaire']['#markup'] = questionaire_4d_selector_build_esci_questionaire_preview($id, $remote_response->data);
  }

  $form['#attached']['css'] = array(
    drupal_get_path('module', 'questionaire_4d_preview') . '/assets/questionaire_4d_preview.css',
  );
  return $form;
}

/* Implements hook_menu() */
function questionaire_4d_preview_menu() {
  $items['admin/config/esci-online/questionaire-4d-preview'] = array(
    'title' => '4D Questionaire Preview',
    'description' => 'View a preview of a remote 4D questionare.',
    'page callback' => 'drupal_get_form',
    // I'm not sure we have to, but explicitly pass in the 4th
    // argument on the URL as the questionairre ID. This is added
    // to build_info of form automatically.
    'page arguments' => array('questionaire_4d_selector_form', 4),
    'type' => MENU_CALLBACK,
    'access arguments' => array('administer esci'),
  );
  return $items;
}


How do you rename the "save" comment button?

For Drupal 7, you need to create a custom module that implements hook_form_FORM_ID_alter() using code similar to the following one (replace "mymodule" with the short name of the module you are writing):

function mymodule_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['actions']['submit'])) {
    $form['actions']['submit']['#value'] = t('Post');
  }
}

comment_form() uses the following code, to define the form buttons:

  // Only show the save button if comment previews are optional or if we are
  // already previewing the submission.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#access' => ($comment->cid && user_access('administer comments')) || variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || isset($form_state['comment_preview']),
    '#weight' => 19,
  );
  $form['actions']['preview'] = array(
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#access' => (variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED),
    '#weight' => 20,
    '#submit' => array('comment_form_build_preview'),

For Drupal 6, the code should be the following one:

function mymodule_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['submit'])) {
    $form['submit']['#value'] = t('Post');
  }
}

I added the if (isset($form['submit'])) {} part because in Drupal 6, comment_form() defines the form buttons using the following code, and the button you are trying to change could not be present in the form.

  // Only show save button if preview is optional or if we are in preview mode.
  // We show the save button in preview mode even if there are form errors so that
  // optional form elements (e.g., captcha) can be updated in preview mode.
  if (!form_get_errors() && ((variable_get('comment_preview_' . $node->type, COMMENT_PREVIEW_REQUIRED) == COMMENT_PREVIEW_OPTIONAL) || ($op == t('Preview')) || ($op == t('Save')))) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#weight' => 19,
    );
  }

  $form['preview'] = array(
    '#type' => 'button',
    '#value' => t('Preview'),
    '#weight' => 20,
  );


Using Rules to Prune Inactive Users - will this work?

Your solution "may" work, but another approach is to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of users that are candidate for deletion.
add a loop to perform a Rules Action "delete user", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

The advantage is that, if you first run it manually, you can see which users will get deleted (simply by browsing the Views results). When you feel comfortable enough, just automate this by rescheduling it every day (at the end of the rule itself, after you first triggered the rule manually).


Cron stopped running; logs say: "Attempting to re-run cron while it is already running."

Summary

The error message you are seeing would happen if the following two conditions are met:

You cron jobs do not finish (error) or take more than 4 minutes to finish ;
You invoke cron more often than every 4 minutes (According to your crontab setting, not the setting in Drupal)

This error message is therefore a symptom of a cron tasks that is either failing or taking too long to run. (Note: I realise you have already found the culprit, but I wanted to add an answer for people who find this page via searches, as I did)

Background

The first thing to understand is how Drupal cron tasks are run. The Drupal cron is invoked at regular intervals - either through a cron job on your server, or after every page load if you use the poor man's cron which is Drupal's default.

The cron tasks are not necessarily run every time cron is invoked however - there is a setting in Drupal (default is 3 hours) which says how often cron tasks should be run. But this delay of 3 hours only applies if the cron tasks have finished successfully.

In Drupal 7, cron uses Drupal's locking mechanisms, which provides a cooperative, advisory lock system. One of the features of this lock system is that locks expire after a certain time. In the case of cron, it expires after 4 minutes - so if your cron is invoked every 3 minutes and the previous cron job hadn't finished by that time (either it crashed or was very slow), you would indeed get this error message.

The fact you set the cron to be every 12 hours does not make a difference - because the Drupal cron task is failing/taking too long, Drupal assumes it hasn't been run so tries to run it again as soon as cron is invoked. The twelve hour delay only applies to successful cron runs.

The cron semaphore variable does not exist any more in Drupal 7 - this was for an older version of Drupal. In Drupal 7 there is no reliable way to manually release a lock, because the locking backend might change - however if you are using the core locking mechanism then you can release cron locks by editing the database:

DELETE FROM semaphore WHERE name = 'cron';

But by doing this you would only be fixing the symptoms - the problem that needs addressing is why is cron failing / taking so long to run.


Webform depending on Select List - Number of delegates

I would create conditionals. E.g. if Number of Delegates is 2, then show the second pair of fields. If it is 3, show the third...

You can consider this solution if the number of delegates is limited.


Edit default views (books, basic page, etc)

You can edit any existing view. Go to the views list and click on enable button that you would see on the view that you want to edit. Then you would get access to go inside the view and make your changes.

Hope that Helps.

Best Regards
Shameem


Is it possible to have an entity with fields, which doesn't use bundles?

Technically, yes! For each entity type you must have a bundle.
Since bundle is the implementation of entity type. If you define your entity type without a bundle the bundle will be of the same name with entity types. For example user entity doesn't have a separate bundle so it uses the default one with the same name of entity type.

Please go through this and this for details.


Drupal equivalent of wget (with permissions)?

Is this for your site users to have a preview a static html page or node on your site?!

Cant you use drupal_render at a custom menu callback URL or Rule to get the HTML generated for 1 of your pages and save it to a file in your webroot or sites/all/files/SOMEDIR
then using RewriteCond in your Apache site configuration to ignore these static files so you can access them via a non-drupal URL ...
In drupal 7 at least there is like function node_view that lets you load a node for viewing, it respects user access rigts for visibility of stuff on the node.

There are programmatic ways to create and load a user (with assigned roles as well) in any version of Drupal. So you could tie all these bits together as:

Generate HTML fragment of node/page logic could be:

switch to some user by UID.
node_load() some node owned by user NID.
node_view() the node contents as some user.
drupal_render() get the raw HTML.
save to some filesystem location as .HTML file.


How can I encapsulate Drush command with option to use arguments

The best way to provide default options to a Drush command, whether it is a core Drush command or a custom command you have written, is to place your default values into a drushrc.php file under a command-specific option.

For example, if you wanted the Drush site-install command to always name the site admin 'superuser', and you wanted to always install with the password 'secretsecret', then you could add the following definition:

$command_specific['site-install'] = array(
  'account-name' => 'superuser',
  'account-pass' => 'secretsecret',
);

If you later decided you wanted to use a different account name for a site you were installing, then you could just run drush site-install --account-name=su, and the option from your configuration file would be overridden.

If the only purpose of your install-mysite command was to select default values for site-install, then the above configuration is all that you will need.  If you want to add additional code that does other things after the install, though, then you could go ahead and write your custom command, and place a $command_specific['install-mysite'] entry in your drushrc.php file to provide the default values for your command's options.

If you only want to make minor changes to the way the site-install command works, you might want to also consider providing a "policy file" that provides a hook that runs after the install command finishes.  See policy.drush.inc for details.


I use $_GET variables as needed in my clean-url installs without issue. Views uses $_GET variables, too. Drupal uses $_GET['q'] so you don't want to use that ID, but you should be able to do something like:

function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_redirect_redirect() {
  return $_GET['query'];
}

This is working for me locally. The 2nd item you present in hook_menu only matches for /site_search/foo?query=bar so you only want the first. Be sure to set the 'type' property as well.


In investigating this issue further, I resided to installing the Views Litepager module as it's an increase in performance and it resolved my issue as well with the 2 pagers.


Show sharethis twice on a page with different layouts

You can do it in node.tpl file, by using the sharethis custom code(get it from sharethis.com) and choose your horizontal style

below is the code to display only in teaser(paste this code in node.tpl)

<?php if ($teaser): ?>

<?php endif;?>

for block again choose your style from sharethis.com and paste it in the block

hope you can get ideas from the above!


How do I populate an exposed filter with titles of user's content?

Views Reference Filter can be helpful. I you have to create a ER view of node title and then you can use this ER view in your main view exposed filter of type reference.


I wound up using the Computed Field module to create a custom SQL query.


How can I set the default value for a Media form element?

After some digging in the media module, this is the working notation:

'#default_value' => 12345,

Plain and simple...


How to set URL alias automatically for a content type WITHOUT using Pathauto? Which hook to implement?

/**
 * Implements hook_node_insert()
 */
 function mymodule_node_insert($node) {
   if ($node->type == 'mytype') {
     $node->path['alias'] = 'mytype/' . $node->nid;
   }
 }

Additionally, you may add this code to hook_node_update()


Downside of not rendering a region in twig template?

Drupal won’t care and it won’t have any side effects other than the contents of a region not being rendered to a page whose template doesn’t render it

It's not quite that simple.

The problem with dynamically not rendering a region is that Drupal doesn't know about that. It will still load, check and prepare those blocks on every page, which means it is unecessary overhead compared to defining visibility rules to only have it shown on the frontpage. You can also do an empty check of the region in the template and as a result, only have it printed if there are blocks inside (this doesn't work reliably with blocks that might be shown but might be empty but it should work if they are configured to not be shown).

You could also implement a hook_block_access() implementation and deny view access for all blocks in a certain region, then you don't need to manually configure them all, but it does need to be in a module.


There are quite a few possibilities to deal with this.

To get an overview:

The advantage of custom entities is that they don't come with all the overhead that nodes have. They're especially well suited for storing and managing completely custom data that you might not even want to display and you have full control over them (their data structure, workflows, UI). The commerce project for example defines own entities for orders, products, line items and so on.
Nodes are still the main content pieces. They provide various features that you don't yet get for free with custom entities, like revisioning and comments. Various additional modules focus on nodes. In short, you get a ton of features, but have to live with the overhead that comes with them. Every additional data structure you need is a field, living in it's own table, and so on.
Entity API provides a lot of features for custom entities, for example CRUD and allows you to easily integrate with various important tools like Views and Rules. It's definitely worth to rely on it, see http://www.trellon.com/content/blog/creating-own-entities-entity-api for a nice introduction.
To connect entities (Hint: nodes are entities as well), you can for example use  Entity reference (simple, directed relationship) or Relation (flexible, unidirectional relation between entities which is an fieldable entity on it's own).

Some specific tips based on that:

Article sounds like a perfect use case to use nodes/a content type to me. People need an UI to create them, you might need revisions, maybe comments, they need to be displayed, probably want nice aliases (Pathauto) for them and so on.
Author; Here you have a bunch of options. Nodes have an author by default, the user that created them. Users can have fields as well and can have a public profile, so your authors could actually be users. Especially if your authors are going to be the uses which will create the articles on your site themself. If not, then this might not be a perfect match because changing the author of a node requires administrative permissions. If not, you could either use another content type if you think that makes sense or create a custom entity.
Location: The traditional answer are certainly taxonomies. They're still a good match to categorize content, provide a number of possibly useful features out of the box, like hierarchy (so you could do do Country > State > City), auto-create new locations from a autocomplete widget and a list of nodes attached to them. And, they're fieldable entities too (surprise!), so you can store additional information for them as well.

So, to me it sounds like the default entities provided by Drupal core are a pretty good match for your data.


Different front page for anonymous users

If the pages are not too different, you could edit the page--front.html.twig and make it something like:

{% if not logged_in  %}
  // add your markup for non-registered users here
{% else %}
  {{ page.content }}
{% endif %}


You can render your image with a render array like this:

$a = array('#theme' => 'image',
        '#uri' => 'http://www.url.com/'.FIELD_CONTENT.'.jpg',
        '#alt' => 'Whatever',
    );

If you want that to be the content of an A tag (the link to press), render the link like this:

Link::createFromRoute($a, routename)->toString()

Is this what you need?


Why I'm having fatal error when adding PHP code to my text format?

I just tracked this down.

What happens is that previewing a node will invoke both the teaser display and full node display, and both of those invoke the PHP code.

My solution was to set the teaser to hidden for the content type (at Structure > Content Types > [your node type] > Manage Fields > Teaser). However, I didn't want to do this for default types like Basic Page, so I created a new type "PHP Tests" and only made the change there.

So I think this shows how PHP in nodes can get ugly, but for people like me who basically want to eval code in the Drupal environment without making a module sometimes, the above is an okay solution.


How to make custom login URL accessible in maintenance mode

A viable solution for making the path/URL/page available while in maintenance mode is the use of hook_menu_site_status_alter().

This hook is called after checking whether the site is offline (in maintenance mode) but before the current router item is retrieved and executed.

Code below should be used in a custom module:

function CUSTOMMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  // Allow access to my_module/authentication even if site is in offline mode.
  if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'custom-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}


How to get the entity that field belongs to in the case of an entity reference field

You can get that with an entity query:

// Get IDs of all film nodes that reference this entity
$nids = Drupal::entityQuery('node')
  ->condition('type', 'film')
  ->condition('field_foo.target_id', $entity->id())
  ->execute();

// Load the nodes
$nodes = Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($nids);


How do I pass an additional variable to function theme_item_list

Implement hook_theme_registry_alter() to let Drupal know about the new var:

function MYTHEME_theme_registry_alter(&$registry) {
  $registry['item_list']['variables']['MY_VAR'] = NULL;
}

Then override the theme function:

function MYTHEME_item_list($vars) {
  // Copy/change original theme_item_list as required.
  // $vars['MY_VAR'] is available as long as it has been passed in.
}

And just make sure you pass the var in your render array:

$node->content['list'] = array(
  '#theme' => 'item_list',
  '#items' => $items,
  '#weight' => 2,
  '#prefix' => '
',
  '#suffix' => '
',
  '#MY_VAR' => 'foo',
);


This is a known bug with the media module. See Issue #1351890: Wrong upload destination folder "null" and Issue #1364676: Upload path. The latter of the two contains a patch to fix this.


Print Media CKeditor images correctly custom code

Problem solved.

$black_box_with_image_description = isset($content['settings']['black_box_with_image_description']['value']) ? $content['settings']['black_box_with_image_description']['value'] : '';
if (isset($content['settings']['black_box_with_image_description']['format'])) {
    $black_box_with_image_description = check_markup($black_box_with_image_description, $content['settings']['black_box_with_image_description']['format']);
}


Can I force users to join a group when registering?

I am not sure, but if Organic Groups has rules integration; you might be able to create a Rule which automatically adds the user to the desired group.


The controller base class provides the method entityTypeManager() which gets the service with the same name from the container the first time you use it. You can use this service to get the node storage:

  $node_storage = $this->entityTypeManager()->getStorage('node');

and then load the node:

  $node = $node_storage->load($nid);


Create node fields with values that change every week but old values are being stored

Check the module field_collection

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

add field collection to your tanks content type
in collection add fields for stats like date, amount etc
after that you can store latest amount and display them in views, charts etc


Restore with backup & migrate module does not work with Acquia Dev Desktop

There could be many reasons for this not working for you but as long as you've got the database backup and a copy of your existing codebase, you should be fine. Fixing DevDesktop database issues is a little tricky but the easiest way is to just create a new instance with the correct settings. Quick steps to do this:

We're going to be deleting the whole site instance using DevDesktop so you should make a backup of the folder and your database backup or at least move it outside of the DevDesktop folder.
Now from the DevDesktop application, delete your site and then create another one with the same name, etc. This will create a new database and a new settings.php file that is connected to it.
Finally, you'll want to copy your codebase back into this directory
(making sure not to overwrite the settings.php or sites.php files
that DevDesktop created) and then try the restore again using backup
& migrate.


Right, so I tried all sorts of illogical things, one of which was deactivating and uninstalling Forum Access module (http://drupal.org/project/forum_access).

I did not have to - because the form was accessible - but I did anyway, out of desperation.

Then I enabled it again. Set all permissions again.

And things work!

BUT this is not a proper solution. Something in Forum Access was screwed up badly and ideally this issue should've been solved at its root, not by a workaround like mine.


As an alternative configuration using Field Collections. Instead of using two content types and a field reference...

{% for item in content.field_slide %}

{{ item.getFieldCollectionItem().field_h2.0.value }}

{{ item.getFieldCollectionItem().field_p.0.value }}

{% endfor %}

This is off the top of my head so double check the code.

Then you just create a field collection field on the home page content type called slide. Go to field collections, select "slide" and add the fields: link, slide_image, h2, and p.


How to show a node but return HTTP 404 response

Drupal's built in mechanisms

for delivering 404 pages are useless to you. We can read:

  Page callback functions wanting to report a "page not found" message should return MENU_NOT_FOUND instead of calling drupal_not_found(). However, functions that are invoked in contexts where that return value might not bubble up to menu_execute_active_handler() should call drupal_not_found().

Of course if page callback will return MENU_NOT_FOUND, it will not return any meaningful data. And while calling drupal_not_found() does not always prevent data delivery, comments under function clearly shows that it causes double display of error message more often than any other result - not what you want, either.

Drupal generic header functions

may help you. Especially drupal_add_http_header(). Let me emphasize one thing in it's description:

  $value: The HTTP header value; if equal to FALSE, the specified header is unset. If $name is 'Status', this is expected to be a status code followed by a reason phrase, e.g. "404 Not Found".

So you want to set status to 404:

drupal_add_http_header('Status', '404 Not Found');

It should be enough, after all that's what drupal_deliver_html_page() is doing when you use higher-level 404 calls from previous part of my answer.

Also, you might be interested in logging it like other 404 errors:

 watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);

Where to place it?

It depends on what you need to decide if page should be 404 or not. If all you need is the actual data in page, you can go for hook_page_delivery_callback_alter():

  This hook is intended for altering the delivery callback based on information unrelated to the path of the page accessed. For example, it can be used to set the delivery callback based on a HTTP request header (as shown in the code sample). To specify a delivery callback based on path information, use hook_menu() or hook_menu_alter().

emphasis mine.

Let's assume that you need it for nodes

and this means you need a node id. NID is part of the path, so, following suggestion quoted above, you want to use hook_menu_alter().

Let's take a look on how node's menu looks like. The part we want to alter is:

  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),

    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );

What you need to do is to alter it to provide your own callback. In that callback:

Perform any logic needed
Set header as you need
Log to watchdog if you want to
Call original callback and return it's result. Render cascade does not explicitly set HTTP 200 later, so your status header should be delivered unaltered. Unless some modules will alter it, of course, but that's something we cannot know.

Last notes

thanks to Ayesh K and MPD:

Sending header might now work in any of the preprocess hooks or just about any tpl.php file. The fact that you could does not mean you should, especially not in tpl files, as it may interfere with caching, but it's worth to remember you are not limited to the ways I described above. For example hook_page_alter() can be a safe choice, too.
Make sure the page size is more than 512 bytes, otherwise some browsers (Howdy, IE) will ignore it.
Keep in mind that by RFC 2616

  User agents SHOULD display any included entity to the user.

As you may notice, this RFC uses MUST in some cases and this is not one of them, so if browser will refuse to display your page after you send 404, it's not exactly an error. Browsers are not forbidden to ignore your HTML when you send 404.


How to create a page without any theme via custom module?

If you want to show content in clean page you can use theme_hook_suggestions in THEME_preprocess_html and THEME_preprocess_page with passing some GET variable.
For example for clean pages you can add $_GET['embed'] = 1 and in preprocess functions write the following code:

function THEME_preprocess_html(&$vars) {
  if (isset($_GET['embed'])) {
    $vars['theme_hook_suggestions'][] = 'html__embed';
  }
}

function THEME_preprocess_page(&$vars) {
  if (isset($_GET['embed'])) {
    $vars['theme_hook_suggestions'][] = 'page__embed';
  }
}

Then copy paste html.tpl.php and page.tpl.php and rename to html--embed.tpl.php and page--embed.tpl.php. Ultimately remove unnecessary code from template files.


I had a similar issue in Drupal 8. I had one form with multiple entities (not drupal entities) that had an identical subset of fields and each had their own button. My $form_state->getTriggeringElement() would always show the last of these buttons, no matter which I clicked. My issue was that I was not setting #name on the buttons and they were both defaulting to op (they had the same #name value). Explicitly setting a unique #name for each button resolved my issue.


Drush package handler - recommendations?

Using the git_drupalorg package handler is best if you want to track the latest HEAD of the dev release.  If you just want to download stable releases, the wget package handler is preferable.


What path should I give so that contextual filter works

Instead of creating a node view create a taxonomy view

In that provide two relationships

Taxonomy term: Content with term
Taxonomy term: Content using {Name of the taxonomy field in the content type}*
Add a contextual filter of the type Content : Title Use the first relationship for the contextual filter, Make necessary changes in the more option such as change to lover case turn space to dashes etc
Add the required fields from the content with the relationship set to 2)

You are good to go.

EDIT : As per the discussion There was another need to also show the nodes under a term and its sub terms.

Create a view of the type content.

Add the required fields

Add a contextual filter of the type Content: Has taxonomy term ID (with depth) and select the depth a value as deep as the hierarchy you have in the taxonomy.

Now when you pass the term id as the input it would show all the nodes under that taxonomy term including the child nodes

If you wish to change the url to have the term name instead of the term ID Do the following.

In view give the path as taxonomy/term/% this will override the default taxonomy path.

Install Pathauto Module this depends on Tokens module so have to install that as well.

In Configuration -> URL aliases you have a tab called Patters

Set the pattern of the "TAXONOMY TERM PATHS" to what you would like it to be. Make sure that the last value is [term:name] so if you want the path to be category/carrot you should give it as category/[term:name]

If you have already added the taxonomy terms then you would need to do the "BULK UPDATE" which is again a tab on the URL Alias page.

Now when you visit the page category/termname you will see all the nodes under the term including the child terms


The token needs to be available in the email? I've not created custom tokens in D8 yet but in d7 We'd make a custom token and the value would be set in the token definition based on condition.


A RelationQuery is just an EntityFieldQuery under the hood, and since relation_type is the bundle key of the relation entity type, both

$query = relation_query('node',1234,1);
$results = $query->entityCondition('bundle', 'is_member_of')->execute();

and

$query = relation_query('node',1234,1);
$results = $query->propertyCondition('relation_type', 'is_member_of')->execute();

should work.


Separate permissions for form access and form submit

It's an odd use-case where certain roles can view the form itself, but not submit it. Perhaps better to allow non-privileged users to view the rendered form output instead of the input form.

That way, you can put the access check on the menu callback for the form itself.

Anyway, have you considered putting the access check into the form validate function?

e.g

function members_edit_form_validate($form, &$form_state)
{
  if (!user_access('low admin tasks'))
  {
    form_set_error('submit', t('Sorry, you do not have access to update this form'));
  }
}


How to preload a css/js library programmatically after module installation? is there api for changing *.library.yml file?

Drupal allows modules to add dynamic library definitions by implementing hook_library_info_build(). Drupal core doesn't implement this hook, except in a test module.

function common_test_library_info_build() {
  $libraries = [];
  if (\Drupal::state()->get('common_test.library_info_build_test')) {
    $libraries['dynamic_library'] = [
      'version' => '1.0',
      'css' => [
        'base' => [
          'common_test.css' => [],
        ],
      ],
    ];
  }
  return $libraries;
}

If you instead need to alter the library definitions given from another module, hook_library_info_alter() is the correct hook to use.

function locale_library_info_alter(array &$libraries, $module) {
  if ($module === 'core' && isset($libraries['jquery.ui.datepicker'])) {
    $libraries['jquery.ui.datepicker']['dependencies'][] = 'locale/drupal.locale.datepicker';
    $libraries['jquery.ui.datepicker']['drupalSettings']['jquery']['ui']['datepicker'] = [
      'isRTL' => NULL,
      'firstDay' => NULL,
    ];
  }

  // When the locale module is enabled, we update the core/drupal library to
  // have a dependency on the locale/translations library, which provides
  // window.drupalTranslations, containing the translations for all strings in
  // JavaScript assets in the current language.
  // @see locale_js_alter()
  if ($module === 'core' && isset($libraries['drupal'])) {
    $libraries['drupal']['dependencies'][] = 'locale/translations';
  }
}


To upload a PDF or another arbitrary file, go through the generic Link dialog:

Then use the upload form:


Is it possible to have language specific content?

We managed to find a solution and it involved using view filters.

In case it is useful for anyone else, you can do this by selecting Edit View in the top right hand corner of the view. Click on the Add button next to Filter Criteria and then choose "Content translation: Language".

Alan


Set pager none in a view programmatically

I believe you can do something like:

$view->display_handler->options['pager']['type'] = 'none';

in your function. This calls the view's display handler to set the pager type option to 'none'.


How to change the theme programmatically?

You can install drush on your system and then from drush command you can change the theme using

drush vset theme_default <theme_name>

You can do the changes from database also. Either on the commandline, or via an administration interface (eg PHPMyAdmin) enter the following query

UPDATE system SET status=1 WHERE name = '<theme_name>';

Then either:

UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';
TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

Source: https://drupal.org/node/200774


Webform email component created programmatically

$email = array(
  'nid' => $node->nid,
  'email' => 'name@example.ch',
  'subject' => 'default',
  'from_name' => 'default',
  'from_address' => 'default',
  'template' => 'default',
  'excluded_components' => array(),
);
webform_email_insert($email);

Check this post for more info.


AutoSKU and Commerce Kickstart 2.0 or Commerce backoffice

The AutoSKU that works with product variations is part of Commerce Kickstart 2.0.  You will have to enable the module of AutoSKU once you have installed Commerce Kickstart 2.0.


Do you want to set the value before submission or after?

Before submission:
Use $form and set the default value for the select list using the key.

After submission:
Use $form_state['values']


How can I set a custom CKEditor on only one field?

I believe the module you want to add is Better Formats. This will let you specify format options for a field, if you only want to show one (even if the role has access to multiple).

Edit, because it is not clear from the project page:

composer require drupal/better_formats:1.x-dev


Blog monthly archive block - list of posts grouped by year then month

It's normally done using Views and a good tutorial on the process has been explained by Chris Shattuck on his blog - see How to create a monthly archive block for a Drupal blog with Views

A little sleuthing on how the blog you mention was generated leads me to believe that the author wrote the wp_blog module on Drupal.org which provides a view that ultimately generates the year -> month -> post hierarchy.  You can see an exported view for the blog archive block here: http://cgit.drupalcode.org/wp_blog/tree/views/wp_blog.view?id=47246da29d176c028a749632807d207dfe0461e1


In the Drupal 7 field settings for that location field, make sure you have enabled the longitude and latitude fields.

I believe there is also an option to "allow user to choose co-ordinates".


Simplify Menu sounds like what you'd want.

  The simplify_menu module uses a TwigExtension to gain access to
  Drupal's main menu's (or any other menu for that matter), render array
  so it can be accessed from a twig template. Among the many advantages
  of having full control of the menu's render array in a twig template
  is the ability to customize the markup for your menus to ensure they
  are accessible and comply with standards.

// Get menu items
{% set items = simplify_menu('main') %}

// Iterate menu tree

  {% for menu_item in items.menu_tree %}

      {{ menu_item.text }}

  {% endfor %}

Otherwise, there are a handful of menu-* twig templates to use when rendering a menu from a block. Turn on your Twig debugging settings in Drupal to see what the suggestions are.

However, you need to have pretty good knowledge of menu theming to get it exactly right (like handling child items and not flat menu structure as the example above displays) - that said, I would stick to letting a block render out the menu in a given region. Then, inspect menu.html.twig from your base theme (either classy or stable) to get an idea of what your options are if you want to modify markup.

Be sure to use a decent twig template suggestion and not just menu.html.twig - as that will affect every menu that gets rendered by Drupal... it is the default template.

I would also suggest to install Menu Block as that will grant extra flexibility in theming and twig file suggestions. It also makes rendering trees of a menu (like section based navigation in a sidebar) a breeze.


Where are logs created by drush_log() stored?

It's not. It's printed.

However, notices are by default not visible unless you increase the verbosity of drush using the -v option.

To display internal messages you'll need to enable debug option -d. This will display even more information.

Alternatively, you can change the message type parameter from 'notice' to 'ok' to print out to the console.

drush_log('xhprof link: ' . devel_xhprof_link($devel_run_id, 'url'), 'ok');


drupal 7: How to create a pop-up window with close button, that shows automatically while loading front page

You can use Lightbox2 module. This might help you or else you can also try Node pop-up module.


Works as designed imho.

The markup of the first is generated by the form element/Drupal. By default Drupal has a space between the field title and the asterisk. That's just how it was designed.

The second time you tell the form what to add - exactly what to add. Drupal wont add a space for you, as you may not always want a space between your custom wrapper and the title. (In most cases you probably don't.)

If it is important to remove the space you can overwrite theme_form_element() in your theme. Check the mid to late replies (starting with kkatusic) in this thread: How to remove asterisks from required fields?

Is there a reason why you would want to mark a field required if it isn't a required field?


To skip the cart part of the checkout flow, I have been using the patch here. This is the leading patch for decoupling the cart from Commerce (it's a bit hard-wired at present).
If you want to customize the checkout flow with more steps, you can write a custom checkout flow plugin.
To add a custom confirmation message, you can write a checkout pane.


How do I hide an empty field if my custom field formatter removes all items?

Drupal adds the field wrapper only if the result returned by viewElements() contains at least one renderable child.

FormatterBase::view():

  public function view(FieldItemListInterface $items, $langcode = NULL) {
    ...
    $elements = $this->viewElements($items, $langcode);

    // If there are actual renderable children, use #theme => field, otherwise,
    // let access cacheability metadata pass through for correct bubbling.
    if (Element::children($elements)) {
      $entity = $items->getEntity();
      $entity_type = $entity->getEntityTypeId();
      $field_name = $this->fieldDefinition->getName();
      $info = [
        '#theme' => 'field',
        '#title' => $this->fieldDefinition->getLabel(),
        '#label_display' => $this->label,
        '#view_mode' => $this->viewMode,
        '#language' => $items->getLangcode(),
        '#field_name' => $field_name,
        '#field_type' => $this->fieldDefinition->getType(),
        '#field_translatable' => $this->fieldDefinition->isTranslatable(),
        '#entity_type' => $entity_type,
        '#bundle' => $entity->bundle(),
        '#object' => $entity,
        '#items' => $items,
        '#formatter' => $this->getPluginId(),
        '#is_multiple' => $this->fieldDefinition->getFieldStorageDefinition()->isMultiple(),
      ];

      $elements = array_merge($info, $elements);
    }

    return $elements;
  }

This means for the question if the field formatter removes all items the field is hidden.

However, field formatter and field preprocessing handle empty fields differently. If you only remove the first field item it is possible that the condition for an empty field has different results. See How to print all values of a multi-value field, except the first?


How to get selected Value in the listbox by using form api

1) Try form_test_custom_form_submit($form, &$form_state) {}

2) Try to print all values. print_r($form_state['values']);

  // $form_state['values']['city']; you may get values here.

You can write $form['city_element_wrapper']['city'] array inside the form_test_form itself, instead of writing inside ajax callback.


Why does drush en node_clone end up in a circle

Seems this has been well answered in drupal.org

Commands need to be

drush dl node_clone

but

drush en clone

Discussions about the 'naming standards' are here


Use libraries-override in your theme's info.yml file

Step 1: Find the library name in core that the JS or CSS file to override belongs to.

For example, it is clear that core\modules\file\file.js  belongs to the file module. Review at core/modules/file/file.libraries.yml to find the library name .  In the yaml file, the library name is the top-level item in the yaml structure where file.js is defined.  In this case drupal.file.

#core/modules/file/file.libraries.yml
drupal.file:
  version: VERSION
  js:
    file.js: {}  #### Drupal 8+ defines the js/css to override in libraries.yml
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Step 2: Find the fully-qualified library name.

The fully-qualified library name is generally prefixed by the module name, in the format <modulename>/<libraryname>. However, some core system libraries don't follow this format, so if unsure of the fully qualified library name, search for instances of the <libraryname> in the core codebase, which may turn up a string with the fully-qualified library name like drupal/<libraryname>.

In this case the fully qualified name is file/drupal.file.

Step 3: Override the file in your theme

In your custom theme's info.yml file add the following lines:

libraries-override:
  file/drupal.file:
    js:
      file.js: js/file.js

If you want to override a core or contrib CSS file, the syntax is similar:

libraries-override:
  filter/caption:
    css:
      theme: # <-- this line must match the definition in libraries.yml
        css/filter.caption.css: css/components/captions.css
#        ^                       ^
#        |                       |
#      File path as defined     File path relative to your
#      in *.libraries.yml       theme's folder.

Step 4: Copy the file into your theme, and modify it to your needs

For the 2 examples given above, you'd place the files.js inside a folder js in your theme, and you'd rename filter.caption.css to captions.css and place it inside the css/components folder of your theme.

Step 5: Clear caches and reload the page.

Use your Web browser's resource inspector to verify the path to the overridden file is coming from your theme folder.


How do I create nodes with comments enabled using drush?

This is more of a workaround;
I can coerce all nodes to enable comments by running a query like this:
drush sql-query "UPDATE node__field_mynode_comment SET field_mynode_comment_status = 2"

I had a look at the database and found the node__field_mynode_comment table, which has a field_mynode_comment_status column. I found that the nodes with that column set to 2 had comments enabled, so I ran the above query to set it for all nodes, and now all nodes have comments enabled.
Incidentally I also tried creating the nodes with that field name ignored (--skip-fields=field_mynode_comment_status) but that didn't seem to have any effect.


You're looking for Pathauto I think. It allows you to define patterns for how the aliases should be created automatically.


You can use field collection it allow you to make a subform inside a form so you can add more than subform and arrange them


Getting author_picture component values in twig

No Sssweat has right. When you want to display an entity field based on the "Manage Display" settings, you should go just {{ content.my_field }}.
If you "kint" content (var dump it) you can see that each content field element has also "theme" key/property, which tells twig how to render that field.


How to revolve TinyIMCE error 'The version of TinyMCE could not be detected'?

You need use the last dev version of Wysiwyg, you can read more about this here.

And you need read the Supported Editors Matrix.

I download the 3.5.11 version of TinyMCE from here and copy the tinymce folder to YOUR_SITE/sites/all/libraries/ so inside this folder you must have this:

So I have installed:

Wysiwyg 7.x-2.x-dev
TinyMCE 3.5.11

And it works ;-)


Associating a timer on flag click on individual nodes for individual users

Create tpl file for field field--field-name.tpl.php. place it to your

  if Field nameis: field_page_photos then File name will: field--field-page-photos.tpl.php

clear cache.

paste below code to your tpl field file.

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>

START FLAG

  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>


The full story can be found at Altering existing services, providing dynamic services, but essentially you need to add a service provider to your module, e.g. (mostly copied from the d.o page above):

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the date formatter service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides date.formatter class for custom interval formatting.
    $definition = $container->getDefinition('date.formatter');
    $definition->setClass(DateFormatter::class);
  }
}

(assuming your replacement class is \Drupal\my_module\DateFormatter)


Possible to have variables in migration configuration?

Yes you can! However, depending on the plugin you are using, it might be picky about what you put in the variable. Here are two examples of variables being used in a migration config:

A file import

source:

  plugin: csv
  track_changes: true
  path: 'public://migration/csv/image_download.csv'
  header_row_count: 1
  keys:
    - image

  fields:
    image: 'Image'
    media_name: 'Media name'

  constants:
    uri_file: 'public://photos'

process:
  uri_file:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/uri_file
        - media_name

  uid:
    plugin: default_value
    default_value: 1

  filename: display_name

  uri:
    plugin: download
    source:
      - image
      - '@uri_file'

In the above, both constants/uri_file established in the "source" step of the migration, and uri_file passed as @uri_file to the download plugin in "process" step are variables.

The documentation for the migrate_plus process plugin "merge" has another good example:

source:
     plugin: d7_node
   process:
     temp_body:
       plugin: iterator
       source: field_section
       process:
         target_id:
           plugin: migration
           migration: field_collection_field_section_to_paragraph
           source: value
     temp_images:
       plugin: iterator
       source: field_image
       process
         target_id:
           plugin: migration
           migration: image_entities_to_paragraph
           source: fid
     paragraphs_field:
       plugin: merge
       source:
         - @temp_body
         - @temp_images
   destination:
     plugin: 'entity:node'

In both these example, the vars are used in arrays. That's just what the plugin expects, not something inherent to using variables.


There are no ctools plugins anymore in Drupal 8. There's just the Drupal 8 plugin API.

Page Manager, Panels and so on use standard block plugins now in 8.x, so you basically have to port this to a block an then it should work fine.

Also, the "code" you posted only defines that you have such a plugin in your module, nothing else. If you need more specific support, you will need to post your actual code, and ask specific questions (which are probably better as a follow-up question).


How to set page variable from custom module

As far as I can tell, this should be handled in the custom theme, not in the custom module.  This is because the module really has no idea how a custom theme wants to render stuff.

In any case, in the custom theme, the only way I can figure out how to make the data available is to register a hook_preprocess() function in the theme, check the hook that's called, and declare a static variable that sticks around until it can be injected later on.

The custom module's "promt_program" hook will be called earlier than the theme's "page" hook. I'm pretty sure that will always be true.  So, we grab the location_id and then inject it later on.

This preprocess function will get called many, many times, so it seems important to make it thin.

function cob_preprocess(&$vars, $hook)
{
    static $location_id = null;

    switch ($hook) {
        case 'promt_program':
            if (!empty($vars['program']['location_id'])) { $location_id = $vars['program']['location_id']; }
        break;

        case 'page':
            if ($location_id) {
                $query = \Drupal::entityQuery('node')
                    ->condition('status', 1)
                    ->condition('type', 'location')
                    ->condition('field_promt_id', $location_id);
                $nids  = $query->execute();
                if ($nids) {
                    $vars['node'] = \Drupal::entityTypeManager()->getStorage('node')->load(current($nids));
                }
            }
        break;
    }
}


SQL queries in theme functions - is it a bad practise?

Any theming function only format variables passed inside them to specified format.
If you want to get some additional variables from database you should use hook_preprocess_HOOK https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess_HOOK/7.

So, in your case you should implement:

hook_theme() in module to register new theme-function;
hook_form_alter() in module to modify form theme (as showed in your example);
template_preprocess_HOOK() in module, to get aditional info from database;
[theme]_hook() in template.php of theme to format variables as you wish.

There is no any performance issues, it is "must do" practice.
If you have version control system, and you need to change some output, it's no required to change module files.


How to add a prefix - suffix to a view title

The variables title_prefix and title_suffix will be rendered using Twig, and therefore filtered from markup and potentially harmful code.

If you like to use HTML within Twig variables, you need to use an instance of the Markup class:

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK() for page_title.
 */
function mytheme_preprocess_page_title(array &$variables) {
  $variables['title_prefix']['#markup'] = Markup::create('

');
  $variables['title_suffix']['#markup'] = Markup::create('

');
}

PS.: The above hook would add the markup to all titles. If this really is your intention, consider altering the page-title.html.twig template instead.


Show all user profiles and geolocated content on a map

Alternative,

Create your 2 views. Let's say they're called, user_points and node_points and both have a display called map.

You could then create a simple module that does,

use \Drupal\views\ViewExecutable;
use \Drupal\views\Views;

function hook_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'node_points' && $view->current_display == 'map') {

    $args = []; //these are contextual filters on the view
    foreach ($view->argument as $argument_key => $argument_value) {
      if(is_string($argument_value->argument)) {
        $args[] = $argument_value->argument;
      }
      else {
        $args[] = $argument_value->argument[0];
      }
    }

    // Get user view
    $user_view = Views::getView('user_points');
    if (is_object($user_view)) {
      $user_view->setArguments($args);
      $user_view->setDisplay('map');
      $user_view->preExecute();
      $user_view->execute();
    }

    if (!empty($user_view->result)) {
      $view->result = array_merge($user_view->result, $view->result);
    }
  }
}

On your node_points view, you'll now have the results from user_points.


How to put up a notification about scheduled maintenance?

Drupal Core has in built option to put site on maintenance but out of the box it does not have option to show maintenance message prior to scheduled date. In order to do that you can Scheduled Maintenance module.

  Scheduled maintenance allows users to schedule an upcoming maintenance
  and show site visitors a warning message in advance.


There are a few ways you can do this, but this is probably the most straightforward:

$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}

// Return this if you want to use "or" logic
return implode('+', $tids);

// Return this if you want to use "and" logic
return implode(',', $tids);


Which parameter do I need to pass for user registration?

$user_data["field_name_first"]["en"][0]["value"]='testranjeet8';
$user_data["field_name_last"]["und"][0]["value"]='testgholave8';
$user_data["mail"]="testranjeet12@example.com";
$user_data["pass"]["pass1"]="test123458";
$user_data["pass"]["pass2"]="test123458";
$user_data["field_gender"]["en"]="Male";

Just pass the parameter you will get the result .I had problem with android side that they are not passing value correctly
finally i got answer


How do you create a CCK field that presents a node creator with a list of the website's users?

You can setup a view for those users and then install Views Field View module. With this module you can add a new field to your node which is a link to that view.

That view will be able to get arguments coming from the node where it's linked from.


Photo Gallery attached to Story - How to Create

I ended up add the images directly to the story with new fields so they could be shown as a gallery of thumbnails with a block.  I used a view with a grid and followed directions to create a contextual filter from this helpful post:
http://www.drupalwoo.com/content/blog/easy-gallery-image-option-your-content-editors-drupal-7


How can I use the Date tools without requiring an end date?

It is an option to choose end date or only start date
try to make a new date field and in option before saving there is a check box if you want an end date or not


How do I convert a string like node/1 into a RouteMatch or Url object?

One way is to use the path validator service:

$url = \Drupal::service('path.validator')->getUrlIfValid($path)

I don't think that can handle URL's prefixed with the langcode if that's what you mean. That's usually handled/stored separately.


template_preprocess_field() hook is your friend.

The general flow is:

theme($hook, $var) >> preprocess functions >> process functions >> finally either goto template.php or call theme function >> return output as string

therefore, template.php or theme function call is the final destination, no hook runs after template.php


How to add pager at the bottom which allow shifting between views?

Create 10 different page views. Example:

In Page View1 click on add page

In your view pager, select  Display specified number of items.

Then add an offset of 5 (so your view will start from row 6)

If you're going to make changes to anything make sure you select this page override, otherwise it will make changes to all your page views. (On previous screenshot, see my pager options, I forgot to do that. Should be this page override)

On your footer Add Global text area. (remember this page override)

Then use html to create your own pager. (this is for view 2)

1 2 3 .... Next > Last >>

Then change code accordingly for view 3. (remember this page override)

Now we will need to hide the real pager.

Under Advanced, click on theme info. Then click on Display Output and copy the entire code that's there.

Create a new file and paste the code there.

Now find and delete the <?php print $pager; ?> line.

Now rename the new file to views-view--[view name goes here]--page.tpl (In my case my view is called sadfsafd)

Note: Do not use views-view.tpl.php as your template name, because that will affect all of your views, and we don't want that. By using views-view--sadfsafd--page.tpl I am only affecting the sadfsafd view.

Then upload views-view--[view name goes here]--page.tpl to your sites/all/themes/template folder.

Now clear/flush Drupal cache.


Filter data from two content types with different criteria in view

a1 and b1 will show nothing, because content type == A AND content type == B is always false for 'A != B'

On filter block, you have a drop down with options. You need to group them into groups connected with OR, so you will have:

published and ( (content type == A and category == aa) or (content type == B and tag == bb ) )


How can I change the value of a field in Entity B based on the value of a field in Entity A?

You may need to write a quick custom action for this given your use case but its fairly easy to do. First create a custom module and add this hook to declare that you are creating a new action to be taken when 'someone checks out'.

/**
 * Implements hook_action_info().
 */

function YOURMODULE_action_info() {
  return array(
    'YOURMODULE_room_checkout_action' => array(
      'label' => t('Action to take after someone checks out'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
}

Presumably, you want to attach this action to the trigger you already have, perhaps 'when booking content type is updated'.

Next, all you need to do is write your payload function that gets triggered for the action. The name for this is the same as what we defined in the array above. After that, you just need to set the two values which is a bit more involved but the pseudo code here should get your started.

/**
 * Action function for 'check out of room' action.
 *
 * @see action_example_action_info()
 */
function YOURMODULE_room_checkout_action(&$entity, $context = array()) {

  // find entity id for your room entity and load entity as $room
  // set $room->needs_cleaning field to 1 (or same value as $booking->checked_out
  // note that the $entity passed here is the one from your trigger (ex. the booking node)

}


Change toolbar config to latest CKEditor toolbar groups

If you use the dev version of the wysiwygmodule, you'll be able to use the latest CKEditor library with all the fancy plugins.


An entity add form is built with a new entity. And when you create this entity you can use parameters for this. See this example from the block module.

The new route with the additional parameter:

block.routing.yml

block.admin_add:
  path: '/admin/structure/block/add/{plugin_id}/{theme}'
  defaults:
    _controller: '\Drupal\block\Controller\BlockAddController::blockAddConfigureForm'
    theme: null
    _title: 'Configure block'
  requirements:
    _permission: 'administer blocks'

This adds the parameter theme.

And the controller for this route:

BlockAddController.php

 public function blockAddConfigureForm($plugin_id, $theme) {
    // Create a block entity with prepopulated values.
    $entity = $this->entityManager()->getStorage('block')->create([
      'plugin' => $plugin_id,
      'theme' => $theme,
    ]);

    return $this->entityFormBuilder()->getForm($entity);
  }

Here the additional parameter theme is used when creating the entity.

Using both routes at the same time is no problem, the standard entity route configured in the entity annotations will still be in place.

Another way to use parameters in entity forms is in the third parameter $form_state_additions:

$form_state_additions['langcode'] = $langcode;
$form = \Drupal::service('entity.form_builder')->getForm($entity, 'default', $form_state_additions);

This example is from the source of the entity formbuilder:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityFormBuilderInterface.php/8.2.x


Field collection with condition node tpl

Did you try field_collection_item in entity_metadata_wrapper? I mean this

$wrapper  = entity_metadata_wrapper('node', $node);
$raw_collection = $wrapper->field_window_shade->value();
$fwrapper = entity_metadata_wrapper('field_collection_item', $raw_collection);

Now use $fwrapper to extract the items (This code is not completely accurate a few modification may be needed)

Visit Extracting a specific data part of a Field Collection Item for more details. Also Programmatically create and update field collection with Entity API and Understanding Field Collection Values can be helpful.


Where does Drupal render the content of the  tag?

template_preprocess_html() gets the tags for the <head>, and adds them to the html.tpl.php template file as $head.

The template file looks like this:

..
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
..


How to add a user-friendly option to link to nodes from body text or text-field?

Sounds like you're looking for the LinkIt module.

  Linkit provides an easy interface for internal and external linking.
  Linkit links to nodes, users, managed files, terms and have basic
  support for all entities by default, using an autocomplete field. In
  7.x-2.4 there is also support for fields (text, textarea, and link).

If you have pretty paths I'd also suggest combining it with Pathologic, that way your links will have their path aliases applied rather than their direct links (i.e. node/123 will become about-us)