How can I override a node's post date theme?

I'm using Display Suite, which takes over the node's created timestamp and turns it into a field named post_date.  Therefore, I overrode the field.tpl.php file and named it field--post-date.tpl.php, and added the time element to the markup:

<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; ?>
  <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]; ?>><time datetime="<?php print $datetime; ?>"><?php print render($item); ?></time>

    <?php endforeach; ?>

To get the $datetime variable, I added the following code to theme_preprocess_field():

function mytheme_preprocess_field(&$vars) {
    // check for Display Suite fields.
    if ($vars['element']['#field_type'] != 'ds') {
        return;
    }
    switch ($vars['element']['#field_name']) {
        case 'post_date':
            if ($vars['element']['#entity_type'] != 'node') {
                break;
            }
            $node = $vars['element']['#object'];
            $vars['datetime'] = date_iso8601($node->created);
        break;
    }
}

I'm just handling nodes, and a node always has one created time.  The loop in the tpl file can probably be removed, since there will always be one value.


How to create a suggested articles block that uses taxonomy?

Have a look at the Similar by Terms module. Here are some more details about it (from its project page):

This Drupal module attempts to provide context for content items by displaying a view block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Views are available based on similarity within each of the defined vocabularies for a site as well as similarity within all vocabularies.
What does this really mean? How should you use this module?

Create a freetagging vocabulary called "Tags" assigned to the content types on which you'd like to display the "Similar" view block.
Enable the view block called "Similar entries from the Tags vocabulary".
Add keyword tags to the content.

You can also create own views and add similar by term Nid argument, sort handler and similarity as field. Now when you go to the page for a tagged content item, a block will show up displaying other content in descending order of common tags (terms).

Note: a stable version of this module is available for both D7 and D8!


webform select options validation unique

You can use a select list with a pre-loaded option list. In that "preload" callback you can alter available options.

Define a custom option list:

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

  $items['exclusive'] = array(
    'title' => t('Exclusive options'),
    'options callback' => 'mymodule_webform_options_exclusive',
  );

  return $items;
}

This callback is called every time the form is displayed, we can alter options here based on previous submissions:

function mymodule_webform_options_exclusive() {
  $default_options = array("One" => 1, "Two" => 2, "Three" => 3);
  $available_values = mymodule_webform_available_values(5); // nid of the webform

  return array_diff($default_options, $available_values);
}

function mymodule_webform_available_values($nid) {
  $submissions = webform_get_submissions(array("nid" => $nid));

  // get all the options values that were already submitted
  $values = array_values(array_map(function($submission) {
    return $submission->data[1][0]; // 1 == index of the field in the form
  }, $submissions));

  return $values;
}

Two things are hard-coded here: nid of the webform (5 here) and the index of the select widget (1 here). It might be possible to avoid hard-coding stuff, good luck!


Allow a role to assign user roles but not to manage user permissions

Use the role delegation module

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.


Hide the "view exposed filter" form or reload the page after submit the form?

Try this:

function custom_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-YOURVIEWNAME') {
    if($_GET['xxx'] == 0){
      hide($form);
    }
  }
}


Multiple Views on a page - How to exclude already shown nodes?

You could load and display each view in your template.
For each view you will have to get a list of nid values that you then will pass on as argument to the next view in line.

For this to work you should setup a Contextual Filter of type Content: nid and configure it to allow multiple values and exclude supplied nids.

In your template your could then do something like this:

// load and display view A
$viewA = views_get_view('VIEW_A');
$viewA->execute();
// get all nids from the result
foreach ($viewA->result as $result):
   $nids[] = $result->nid;
endforeach;
// render first view
print $viewA->render();

// now load view B
$viewB = views_get_view('VIEW_B');
// set arguments for view
$viewB->set_arguments(array(implode(",", $nids)));
// execute view
$viewB->execute();
// render
print $viewB->render();

If you would like to use just one view with multiple displays, you could use set_display() to select the display that should be used:

$view = views_get_view('VIEW');
$view->set_display('VIEW_DISPLAY_ID');
$view->execute();


How to use more than 2 versions on jquery?

Since you need to run multiple versions of jQuery for different contrib modules I would say the jQuery multi module would be the easiest solution (although I don't know the specifics of your requirements).

The 7.x-2.x branch of jQuery update is supported with jQuery multi.

For example, you could use Drupal default jQuery for admin pages, jQuery 1.7 for non-admin pages and jQuery 1.9 for the specific plugins/modules that require it.
Or alternatively you can use 1.9 as the main version and 1.7 for specific plugins/modules.
Whichever works best for your site.

Usage instructions for the jQuery multi module can be found in its README.txt file when you download it.


Using entity reference field as filter in view

Follow the following steps.

1) First create an entity reference field in your content type (player) and in the Entity Selection Mode
select (Simple(with optional filter by bundle) and then check Tournement checkbox, And in Additional Behaviors check (Render Views filters as select list) and save your content type.

2) Create view of type Players

3) Add new filter and choose your reference field and apply

4) Check (Expose this filter to visitors , to allow them to change it) checkbox.

6) Select Operator (Is one of) and in options check (Select all) checkbox

7) Click on Apply button and save your view.

That's all, now you are ready to filter the view using your reference field.


Problem using entity reference to show links to content types associated with a content type

First thing I'd do would be to check the display settings for your module content type. The field may be hidden or otherwise not configured as you want.


Inject SQL_CALC_FOUND_ROWS into db_select()?

As made evident in Compare db_query() and db_select() performance, db_query() is faster than db_select(), which should then be used when you need to make the query you are executing alterable from other module via hook_query_alter(), for example when you need to get a list of nodes for which a user has access.

If that is not your case, then you can use db_query() and using the query you are showing is quite straight as db_query("SELECT SQL_CALC_FOUND_ROWS field1, field2 FROM ...").


That is no problem. user_save an hook_menu will be you're friends.

The file with the random is a good id for security. You could also have a look into the IP Login module.


You can't.

Different entities use the same ID.

E.g. you can have a user with ID 42, and a node with ID 42, and a taxonomy term with ID 42. So just knowing the ID is 42 is not enough to know what type of entity the ID belongs to.

This is why entity_load takes both the entity type and the ID as arguments.

To list all entities use entity_get_info().


I just want to add a radio buttons to my content type

You can choose the list field type - this will display radio buttons.  List core module will need to be enabled.


How to disable cron from running while another time consuming process takes place?

You can use Elysia Cron. This module is a enhanced Cron that has, apart of many other improvements, a global disable option. As they say in a bug report this variable may help you:

  It disables ALL cron tasks. (No cron will be executed).

Also Elysia Cron allows you to set complex schedules so you may fix your problem just with the right schedule.


When using database with in {} you don't need to add the prefix of the table it is automatically added by drupal in your case since you have placed it between {} it is adding another dot_ so the table name is becoming dot_dot_node instead of dot_node.

Note the relevant section from Drupal Database API documentation

  Prefixing

  In static queries, all table names must be wrapped in {}. That flags
  them so that the database system can attach a prefix string to them if
  appropriate. Prefixing allows for running multiple sites from the same
  database or, in limited cases, for sharing selected tables between
  sites.


Attempting to merge in an array of items into Twig classes

Twig's merge filter expects an array as an argument, not a string.
Updating your for loop should resolve:
{% for item in content.field_category | children(true) %}
  {# Merge classes array with an array with one item, item #}
  {% set classes = classes|merge([item]) %}
{% endfor %}


Drupal 8 Equivalent of Drupal 7's disabling a module without Uninstalling it

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

The long and the short of it is that you cant. This option is no longer available in Drupal and it was a conscious decision to remove the ability to disable a module because:

  Because upgrades of some contrib module don't actually work (and can't be made to work) if upgrading when they are disabled.
  Because data left behind by a disabled module that is later re-enabled causes integrity issues and cruft.
  Some upgrades left behind data loss due to things like unexpected dependencies, plugins or hooks being unavailable at key times - when
  things were disabled. .. that issue (https://drupal.org/node/1199946) is several hundred arguments long,
  so It's unfair to over-summarize.


You can use hook_node_update().

In Drupal 6, you can easily get the last node ID by calling db_last_insert_id().


How to make a contextual filter optional

You can use Exceptions setting in views like below

And point your menu link to www.example.com/tech/all instead of www.example.com/tech


I could be wrong here but am going to assume that the fetching of the embedded view and HTML refresh on the client-side has been done using custom Javascript code.

Once new HTML has been added to the DOM in a custom way, then to attach all Drupal behaviors defined by active modules, from within the success callback of your XHR client (say jQuery.ajax()) you might have to manually call:

// $wrapper here is the jQuery object identifying the wrapper element to
// which your new HTML has been injected to. Eg. $wrapper = $('.my-view-wrapper')
Drupal.attachBehaviors($wrapper, Drupal.settings);

My recommendation would be to try and possibly switch to the Drupal AJAX API (Documentation) as it lets you keep this refresh logic on the server-side (one place). The other, obvious benefit is that Drupal.attachBehaviors() is called for you automatically.


How to check user by user name is exist in ldap server?

The LDAP module can handle that for you.


It is not clear in your question if you are placing your template in sites/all/custom/modules, or in sites/all/custom/modules/the_name_of_mymodule. It needs to be the later.

However, if you:

Have your template in the proper place.
Visited the admin/appearance path to force a theme registry refresh.
Cleared all the caches aftewards.

...but still no dice, you can always specify in your hook_theme() implementation the theme_path key:

<?php
function apps_theme($existing, $type, $theme, $path) {
    $items = array(
        'node_app' => array(
            // Don't specify the path in the template name.
            // Unless you have your template inside a directory within this module.
            'template' =>  'node--app',
            'variables' => array('node' => (object)array()),
            // If you want to put the tpl in another location, you can use this key.
            'theme path' => drupal_get_path('module', 'another_module'),
        ),
    );
    return $items;
}


Sounds like your hosting provider does not support InnoDB. There are a few others like you, here is a discussion thread with some ideas on how to fix it http://drupal.org/node/1089724


If you're comfortable with modifying a little your theme, you can use a plugin like Reflection.js for jQuery.


Are the data stored with the tempstore.private and tempstore.shared services expected to be removed when the user account is deleted?

The user's temp storage deletion isn't attached to the user deletion process.

If you look at the class, PrivateTempStoreFactory, instantiated for tempstore.private & tempstore.shared, you can see that the class has an expire property that determines the storage's TTL (in seconds).

These services are instantiated with an expire value of defined by parameters:tempstore.expire in core.services.yml, with a default of 604800 seconds (1 week), so the temp storage will expire 1 week after its creation.


what i personally usually do with local databases is overriding the admin password:

drush uinf 1

will help you to get the user 1 name (just to be sure it is 'admin')
in that case :

drush upwd admin --password=MY_LOCAL_PASSWORD

then go to /user and try it :)


You can do it by node reference. Add those kind of field to your content type. You can always set default value for automatic add webform to node, but it doesn't add you form automatically to node edit form.

I test it by using node reference and views, but it doesn't display a webform on node edit page (in the same form).

You can try to use hook_from_alter, which means to add programatically fields from reference webform. IMO is the only solution or maybe there are some modules for this, but I didn't look for them.

You need add your submit function to this form too, because you need to filter and save webform fields programatically too. Check WebForm API for this. A lot of work, maybe you should think about better solution without programming and using webform at all?


How to apply a patch file in composer to a submodule of a module?

Use admin_toolbar.

"drupal/admin_toolbar": {
  "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
}

Then run composer update or composer update --lock if you want to apply your new patch and do not want to update any packages.


How to display second level menu on another node page

Try the Taxonomy Menu Module. It creates you a menu item for each term which you then can place in your menu.


With drupal_add_js() you can set the scope to either header or footer, specify the group the script is loaded into, and give the script a weight relative to that group. Scripts are loaded by scope > group > weight, where a lower weight will be loaded before a higher weight.

If you have aggregation turned on in /admin/config/development/performance, the script will be combined with others with the same scope & group, and ordered by weight.


How to show users Online and with Photos filter on views

You can achieve that by using the User Stats module

  Provides commonly requested user statistics for themers, IP address tracking and Views integration.

  Statistics are:

  days registered; join date; days since
  last login; days since last post; post count;
  login count; user online/offline; IP
  address;


Select list set default value does not work

To set the default value of field change the default value inside the widget like the following :

 $form['field_my_name']['widget']['#default_value'] = 1;


How do I retrieve the user ID of the latest editor of a node?

$node->getOwnerID() returns the user ID for the user who created the node. If you need the user who created the revision, you need to use $node->getRevisionUser(), or $node->getRevisionUserId() for the user ID.


Form added to content in hook_page_build lacks of AJAX

The problem is the element's name: submit. In the rendered page there's another form that have the same button name (submit), so the AJAX layer just ofund one of the buttons but not the two.

To fix this just rename the element's name:

 $form['myform-submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );


Solr Search - Adding taxonomy to Search results

I rebuilt the view and this time it worked fine.


Adding a custom subject field to the Revision Information Drupal 7

No - because revisions are not Drupal entities themselves but metadata associated with entities. You can expose an entity to the revisioning system but not the other way around, its a core part of Drupal.

Best way I could think of to come close to this functionality is to have a special fieldset / field collection of fields that allow for what you want (ex. log message, subject) and then use field permissions to hide that from the end user. You would then have your team use these fields for recording their updates rather than the log field.


Is there a way to downsize images on upload to save server space?

I answered my own question and I feel a little silly. I realized resizing images programmatically is unnecessary. In the UI you can set maximum dimensions for an image that will be uploaded. I knew that but I'd never read the text underneath that mentions the image gets resized if it violates the limits. That's all I needed, no need to for me to do it in code.


How do I get translated strings into Drupal.locale.strings?

Drupal handles populating the needing strings into the javascript object. Much like the entire collection of strings isn't loaded on every page, only the needed strings are added to the JavaScript.

I believe this is done by traversing the script files before they are actually added to the page.

So if you add Drupal.t('Some string'); to your JavaScript code, you should be able to translate that in the translate interface.


Displaying content type as a field in a page

Create a custom block type "Testimonial slideshow" or so (Accessible through local tasks on the block overview page), add a reference field and allow nodes of your given type. Set the cardinality to exactly 3.

Then you can create a block of that type and select 3 testimonials (with select or autocomplete, depending on what you configure on manage display).

That's it, now you just have to implement the necessary templates to show it as a slideshow.


You have to return $queues in your hook_cron_queue_info..

function timesdb_cron_queue_info() {
  watchdog("timesdb","timesdb_cron_queue_info called");
  $queues['alltimesynch'] = array (
    'worker callback' => 'timesdb_import_alltime_start',
  );
  return $queues;
}


The standard way to do this in Drupal is with drupal_add_js, using the "setting" type:

drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.


Display all tokens programmatically? Trying to debug token

There's a function in the token module called token_get_list() which is:

A helper function that retrieves all currently exposed tokens, and merges them recursively.

It invokes hook_token_list() for all modules so should give you every single token defined in the site.


What causes the error in my custom module for OpenLayers 3?

Looks like a mismatch between your annotation (the @ in the comment above your class) and your class declaration.

But you should post your code for more details.


Access fields in views-view Twig template

In your case you should be using views-view-fields.html.twig instead of views-view-unformatted.html.twig file.

Views fields template will iterate on all rows of result. Your views-view-fields.html.twig should contain below code -

{{ fields.title.content

You can check the fields array by using kint function like - {{ kint(fields) }}

Check for image path and anchor path variable from output of kint function.

If you want to do this in views-view-unformatted.html.twig, then you can access the field values like below -

{% for row in rows %}
  {% set photo = file_url(row['content']['#row']._entity.field_page_photo.entity.fileuri) %}

{% endfor %}


By configuring the Access: section on the Page settings, we can manage Page: Access restrictions.

Choose the Roles  and assign the required user role.


Location's Distance/Proximity exposed filter without Node Location Submodule but with Location CCK Submodule instead

I was faced with the same problem and "solved" with a little workaround:

I use both node and cck location. The one is hidden from the user, he only sees one, and if it is changed then I copy it into the other one.

That way I have both a cck field for flexibility's sake AND the node location for the views. :)


Syntax for using getValue to get value in an array

Put the keys in an array, for example:

$this->configuration['header']['margin-top-submit'] = $form_state->getValue(['header','margin-top']);


All of my pages have class "page--node-" on the body element. This doesn't seem right

Classes beginning with page generally come from drupal core in template_preprocess_html(), which calls theme_get_suggestions() to do the heavy lifting.

That function makes a bunch of suggestions for the classes or template suggestions based on the path of the current page. The % is used as a wildcard for numeric arguments (in this case the node id).

Then back in template_preprocess_html() it passes the suggestions through drupal_html_class(), which in turn runs them though drupal_clean_css_identifier(), which strips out characters not allowed in a class, including the %, so you get a class of page-node- (this seems like a bug but there is a use for it I will explain below).

This theme_get_suggestions() code is the same reason you have the template suggestion with the percent symbol.

This means you can affect all node pages by using the template name page--node--%.tpl.php.

That might not seem necessary because you also have page--node.tpl.php, however if you want a different template for the path /node than you do for individual node pages you need to use both page--node.tpl.php and page--node--%.tpl.php.

This same reason is why the unusual class is useful.
If you want to style the /node page differently from individual node pages you can style page--node differently from page--node-

I agree it is a silly looking class though with pretty limited (or maybe none) documentation.

Also, something I found after writing this that is useful is How Drupal determines page theme hook suggestions based on path, from the "Drupal 7 Template (Theme Hook) Suggestions" documentation page.


Views Output field as a link - Two tokens, use only one of them

Modules You Need:

Views
Views PHP

Assuming your content type is having these fields:

The VIEWS Code:
Simply go to admin/structure/views/import and then Import the below mentioned code:
$view = new view();
$view->name = 'pdf';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'PDF';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'PDF';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: PDF */
$handler->display->display_options['fields']['field_pdf']['id'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['table'] = 'field_data_field_pdf';
$handler->display->display_options['fields']['field_pdf']['field'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['label'] = '';
$handler->display->display_options['fields']['field_pdf']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['path'] = '[field_pdf][path]';
$handler->display->display_options['fields']['field_pdf']['element_label_colon'] = FALSE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
if (isset($data->field_field_pdf[0][\'rendered\'][\'#markup\'])) {
    $pdf_url = $data->field_field_pdf[0][\'rendered\'][\'#markup\'];
    print $pdf_url;
} else {
    global $base_url;
    $node_url = $base_url . \'/node/\' . $data->nid;
    print $node_url;
}
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'pdf' => 'pdf',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'pdf';

I'm sure you might be having some dummy content for that content-type, if not then do create couple of ones. Some with values in field_php and some with not!
and Voila! Here is your required output:

Updated Code:
$view = new view();
$view->name = 'pdf';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'PDF';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'PDF';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: PDF */
$handler->display->display_options['fields']['field_pdf']['id'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['table'] = 'field_data_field_pdf';
$handler->display->display_options['fields']['field_pdf']['field'] = 'field_pdf';
$handler->display->display_options['fields']['field_pdf']['label'] = '';
$handler->display->display_options['fields']['field_pdf']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['field_pdf']['alter']['path'] = '[field_pdf][path]';
$handler->display->display_options['fields']['field_pdf']['element_label_colon'] = FALSE;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = '';
$handler->display->display_options['fields']['php']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['php']['alter']['path'] = '[php]';
$handler->display->display_options['fields']['php']['alter']['absolute'] = TRUE;
$handler->display->display_options['fields']['php']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = '<?php
if (isset($data->field_field_pdf[0][\'rendered\'][\'#markup\'])) {
    $pdf_url = $data->field_field_pdf[0][\'rendered\'][\'#markup\'];
    print $pdf_url;
} else {
    global $base_url;
    $node_url = $base_url . \'/node/\' . $data->nid;
    print $node_url;
}
?>';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'pdf' => 'pdf',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'pdf';

Let me know if you need anything else from this.
Cheers!


Load CSS and JS using absolute paths on select pages

I had a look at how the web_widgets module was making CSS/JS paths absolute and it looks like a valid solution is just to alter $GLOBALS['base_path'] to add the URL of my site. An easy way to do this is with url():

  $GLOBALS['base_path'] = url('', array(
    'absolute' => TRUE,
  ));


where to find default view code in user relationships module in drupal 7?

Under User Relationship module there will be a folder called user_relationship_views inside that you can find the default view user_relationship_views.views-default.inc file


Registration module, Rules, how to add the node-title of the registrated entity to notification mail

Figured it out. I had to add another action before the mail-action: "Fetch entity by id". Set the type to "Node" and the data selector to "registration:entity-id". After this all the node-specific fields were available for the mail-action.


Is there a way to list permissions for a given module?

You could use drush cim and create a yml for your role like for example

langcode: en
status: true
dependencies: {  }
id: myrole
label: 'My super Role'
weight: 1
is_admin: false
permissions:
  - 'whatever 1'
  - 'whatever 2'

And if you don't know what perms your module brings, you could use that simple eval code with drush:

drush php-eval '$p = Drupal::service("user.permissions")->getPermissions(); foreach ($p as $k => $x) print $k." : ".$x["provider"]."\n";'


Drupal 8 update via drush removes files from vendor folder

This is normal, because an update with Drush overwrites vendor and composer.json. So if you've installed a module via composer you need to reinstall it the same way (but you should be able to avoid a reinstall in the backoffice if you manage to get the code base right before running update.php or drush updatedb).

Updating core with Drush is depracetated and this function is removed from Drush 9.0. So you might consider switching core to a composer based install.

Edit to answer this comment:

  Well I'm a bit lost here on how to manage this, so more info is
  required I guess? Today I tried to install a module with composer
  (fieldblock) but could not find it? So I had to install it with drush
  ... For me it is not really clear right now what the best practice is
  and how to avoid problems in the future when having a core update ..

It's still OK to manage core and module updates with Drush as long as you use only modules which can be installed by Drush and don't mix it with Composer. However, when you start to use composer only modules you should really think about switching over to a composer based Drupal install. It's possible to start a new composer based project and keep the existing database, see this great answer from @greg_1_anderson Updating core with Composer doesn't work


Is there a table listing contributed modules that have been ported to Drupal 7?

There is the D6 Upgrade Status Module that will list what modules installed on your system have modules in the D7+ versions of Drupal.


How do I import a database through a Drush(PHP) script?

Basically, you want to run some php code to import an SQL database dump from a file.  There is code that does this in the implementation of drush sql-sync.  It looks like this:

  $options = $global_options + $target_options + array(
    'file' => $destination_dump_path,
    'file-delete' => TRUE,
  );
  $return = drush_invoke_process($destination, 'sql-query', array(), $options, $backend_options);
  if ($return['error_status']) {
    // An error was already logged.
    return FALSE;
  }

You could also call drush sql-sync with appropriate options for a more full-featured solution (e.g. if you want to import a local database to a remote site).  For an import to a local site, though, it is more straightforward to simply use the snippet above, which essentially runs drush sql-query --file=/path/to/dump.sql.

n.b. You may simply remove (or make empty) $global_options, $target_options and $backend_options. You should also take of the file-delete flag, unless you really would like Drush to delete your sql dump for you after it has imported it (e.g. for temporary files).


You can create own field formatter in code. Or use field preprocess function.

But I would suggest you to render this references as view. Than you can do with field anything you want


Is there a way to conditional sort criteria in views

You could achieve this using Views PHP.

Excerpt from the page:

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.


db_select() ignores condition() when used with join

HearthbeatStream::$query is an object of the class PagerActivity which extend the class SelectQuery; this is evident from the code for HeartbeatStream::createQuery(), where the value of the property is initialized with the following line.

$this->query = db_select('heartbeat_activity', 'ha')->extend('PagerActivity');

The fact PagerActivity is an extender of SelectQuery means that every method implemented by SelectQuery is also implemented from PagerActivity.

SelectQuery::conditions() is a getter method, not a setter method. The only method to set the condition associated with a SelectQuery object is SelectQuery::condition().

The code should be re-written as:

  protected function queryAlter() {
    if (isset($this->ctype)) {
      $this->query->leftJoin('node', 'n', 'n.nid = ha.nid');
      $this->query->condition(('ha.access', 0, '>=')
        ->condition('n.type', $this->ctype));
    }
    else {
        $this->query->condition('ha.access', 0, '>=');
    }
  }

To make a comparison, this is the code executed from blog_page_user():

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('uid', $account->uid)
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

There are some similarities with your code:

in both the cases, the value returned from db_select() is passed to the extend() method
in both the cases, more than one condition is applied

Using the value returned from db_and() with SelectQuery::condition() is not necessary, as the constructor of SelectQuery initializes the value of SelectQuery::$where (used by SelectQuery::condition()) with the following code:

  $this->where = new DatabaseCondition('AND');

The returned value is the same returned by db_and().

function db_and() {
  return new DatabaseCondition('AND');
}


modifying option text in ubercart attributes

Go to this URL in your Drupal site:

admin/store/settings/products
You will find a list of menu in that click Attribute settings
You will option for price format in that select the first radio button do not display


You can try this  under your hook_validate

Here i added new function name mymodule_soft_block_validate

 function mymodule_validators() {
        return array('user_login_name_validate', 'user_login_authenticate_validate', 'mymodule_soft_block_validate','user_login_final_validate','mymodule_validate');
    }

function  mymodule_soft_block_validate($form, &$form_state) {
        $pass=$form_state['values']['pass'];
        if(empty($pass) || $pass=='') {
            form_set_error('name', t('dummy message'));
            return $form;
        }

}


How do I associate a field value with another value of a multi-value field?

I've found what may be a possible solution using the Field Collection module.


Entity Translation - create a translation for all existing nodes

A possible solution could be to use a custom module that uses hook_node_view, as in this example:

function yourmodule_node_view($node, $view_mode, $langcode){
   global $language;
   if (!empty($node->language) && $node->language != $language->language) {
      drupal_goto('path/to/some/temporary/version');
   }
}

What the content of such path/to/some/temporary/version node should be is up to you. E.g. you could point to some custom 404 page.


Rules: Data comparison between saved and unchanged node doesn't work with radio buttons

1st attempt (do some debugging ...)

You clearly have a combination of Rules Conditions and/or Actions which don't seem to react as you expect/want them to do. If I was to get this to work, the first thing I'd do is Rules debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect.

There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick (if you want, you could consider/call it "adding breakpoints to a rule you want to debug"). A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Obviously, if you have more then 1 Rules Action (you seem to have (about) 4, following the "Display message test"), you may want to  make it like Bingo1, Bingo2, Bingo3, etc. Depending on the order they are shown, you also know the order of execution. Stupid, but simple and efficient (I think). Here is an edited version of your rule containing those BingoX-messages (try to import it in your site, note I gave it another machine name):

{ "rules_cessazione_with_breakpoints" : {
    "LABEL" : "Cessazione with breakpoints",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "interval", "rules_conditional" ],
    "ON" : { "node_update--rapporto_di_lavoro" : { "bundle" : "rapporto_di_lavoro" } },
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-data-cessazione" ],
          "value" : [ "node:field-data-cessazione" ]
        }
      },
      { "OR" : [] },
      { "NOT data_is" : {
          "data" : [ "node:field-dimissioni-licenziamento" ],
          "value" : [ "node-unchanged:field-dimissioni-licenziamento" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Bingo1" } },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "node:field-giorni-di-preavviso" ],
            "op" : "*",
            "input_2" : "-1"
          },
          "PROVIDE" : { "result" : { "giorni_neg" : "Giorni neg" } }
        }
      },
      { "drupal_message" : { "message" : "Bingo2" } },
      { "interval_apply" : {
          "USING" : {
            "interval" : [ "giorni-neg" ],
            "period" : "day",
            "date" : [ "node:field-data-cessazione" ]
          },
          "PROVIDE" : { "date" : { "data_preavviso" : "Data Preavviso" } }
        }
      },
      { "drupal_message" : { "message" : "Bingo2" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "text_matches" : {
                "text" : [ "node:field-dimissioni-licenziamento" ],
                "match" : "L",
                "operation" : "starts"
              }
            },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo3a" } },
              { "data_set" : {
                  "data" : [ "node:field-data-licenziamento" ],
                  "value" : [ "data-preavviso" ]
                }
              },
              { "drupal_message" : { "message" : "Bingo3b" } },
              { "data_set" : { "data" : [ "node:field-data-dimissioni" ] } },
              { "drupal_message" : { "message" : "Bingo3c" } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "Bingo4a" } },
              { "data_set" : {
                  "data" : [ "node:field-data-dimissioni" ],
                  "value" : [ "data-preavviso" ]
                }
              },
              { "drupal_message" : { "message" : "Bingo4b" } },
              { "data_set" : { "data" : [ "node:field-data-licenziamento" ] } },
              { "drupal_message" : { "message" : "Bingo4c" } }
            ]
          }
        ]
      },
      { "drupal_message" : { "message" : "Bingo5" } },
      { "redirect" : { "url" : "[node:url]" } },
      { "drupal_message" : { "message" : "Bingo6" } }
    ]
  }
}

I'd be interesting to hear which of those "BingoX" messages will get shown while debugging your rule ... Based on that you should come closer to finding the real reason for your rule which doesn't seem to do what you expect/want.

For more suggestions about Rules debugging, and more advanced facilities, refer to "How can I display the value of a variable inside a condition?"

Note: for those who think "this is not an answer", here is my reply to that already: do you know the story about giving somebody a fish, versus giving a fishline (or whatever that is called)?

2nd attempt (why no "entity has field"?)

About your "but the rule doesn't trigger". It may mean that you NOT (repeat: NOT) get that "test" message (as in your very first rules action). If that's the case, I'd wonder (if I was debugging) what results you get if you (temporary) remove the first rules condition? And what if you (temporary) remove the 2nd rules condition?

Hang on: you don't seem to have the typical "entity has field" condition (as your very first Rules Condtion). Imagine Rules thinks all those field values are blank (because of the missing  "entity has field" ...), then neither condition is true (because of the NOT ...), so the rule works as implemented. Therefor, add such "entity has field" Rules Condition, 1 for each of the fields you are already doing those data comparisons. Then let us know the result (the bets are open ...).


Bringing modules into project as git submodules - .info file doesn't have version info

Check out the Git deploy project.

It exposes the version information by looking at the git information. I am not 100% if it supports git submodules, but it's worth a try.


A page provides a certain context.

For node_view, it happens to be a node.

There's no benefit to creating a custom page just to provide the same context.

You'd want to add a new page however, if you, for example, wanted both a node and a taxonomy term as context.


How to resolve the Composer related error shown using the Drush DL command?

using composer is rather for Drupal 8 than Drupal 7
You could remove your version:

composer global remove drush/drush

and install an older one

composer global require drush/drush:8.*


Instead of using drupal_get_form as the page callback, you can specify a custom callback and build the forms there.  An implementation in Drupal 6 would look similar to the following:

function tudakozo_menu() {

  $items['tudakozo'] = array(
    'title' => t('Tudakozo'),
    'page callback' => 'tudakozo_page_callback',
    'access callback' => TRUE,
  );

  return $items;
}

function tudakozo_page_callback() {
  $output = '';

  // Render your two forms here.
  $output .= drupal_get_form('tudakozo_nevszerint_form');
  $output .= drupal_get_form('tudakozo_second_form');

  return $output;
}

The only difference in Drupal 7 would be working with a render array as opposed to a string in the custom page callback similar to the code below:

function tudakozo_page_callback() {
  $build = array();

  // Render your two forms here.
  $build['form_one'] = drupal_get_form('tudakozo_nevszerint_form');
  $build['form_two'] = drupal_get_form('tudakozo_second_form');

  return $build;
}


This is a bug. I created Issue #3029964: Datelist element in webform not working in the Webform's issue queue.  Please try the provided patch.


I complete the previous answer about Drupal 8.

In Drupal 8 with Views (include in core) it's exactly the same way.

Add a 'Promote to block' checkbox field on your News content type.

Then in Views you can create a new View or you can go in the "Content" View. Then create a new "Block". Describing all Views functionalities would take a long time, but in this block you can filter all your content, particularly in the Filter Criteria sections where you can filter in order to take only News content type with only the 'Promote to block' option checked.

If needed, search for some Views tutorials. It's quite easy and very powerful.

Then call this new block instead the old one.


How to add newsletter functionality (just stable modules if possible)?

Simplenews is really your only way of going. I have personally been holding off on it's implementation in 7 because of its state as well. More specifically, emails were not being sent (test ones were) and it's lack of mimemail support.


Can I create a node, assign a language and provide it a menu link with Drush?

Not out of the box. See this prior related question, all of these examples are created through the Devel 'generate content' library but they assume generic (ex. lipsum) content. For a custom build like you are asking with a specific title, you're best bet is going to be to create a custom Drush plugin using node_save to programmatically create a node with the values you want.


How to change the format that shows the autocompletion of reference entities?

You can filter for the entity type & bundle in the getMatches() method.

It is also possible to add specific handlers to your forms: https://www.qed42.com/blog/autocomplete-drupal-8


Can I use 'drupal_add_library' inside an ajax call?

drupal_add_library() under the hood ends up putting things into the same array as drupal_add_js() and drupal_add_css().

These get called by ajax_render(), so your function should work (so long as you are using ajax_render).

However this will add the library load to every ajax request. This will slow them down some what, and most of the item you are using ajax for speed so that may not be such a good idea. Your html JS should be cached and it should only include the ui.dialog on pages where you need it. So I think you may be better off using the standard JS caching.

In simple cases you may be able to use ajax_command_alert() in stead.


How to clear or update only anonymous cache from module?

cache_clear_all() is what you need.

If you need to clear cache of only one node page:

cache_clear_all('http://yoursite.com/node/' . $node->nid, 'cache_page')

(first parameter - cache id, it case of cache_page it is page url).

If you want to clear all pages cache:

cache_clear_all('*', 'cache_page', TRUE);


How do I show Device Geolocation share location prompt only on specific pages?

In the smart ip setting pages there is a setting to limit asking on specific pages.

Ask user's geolocation on specific Drupal native pages

Specify pages by using their paths (not the aliased path). Enter one path per line. The '' character is a wildcard. Example paths are blog for the blog page and blog/ for every personal blog.  is the front page. Leave blank if all pages.


Easy noob custom PHP question in views... Editing recent news stories view

It's probably easier to add the field to the field list (field_successdate). Then use Views rewrite display option to write the node: title link to include the date from field_successdate.

The rewrite will require the Token module to be enabled. rewrite the title as: [node:title] [node:field_successdate]

Be sure you hide field_successdate if you dont want it literally shown in the view by itself somewhere. You may or may not need to move field_successdate to the top of the field list so its gets made into a Token to be used in the title properly.

I'd make a pic of this .... but that'd take like minutes....


Queue Implementation for third party api

I think this is what you want:

'If any failure occurs, you can revert the item back to queue to process that again'

The queue API of Drupal 8 which is known as Queue Worker

http://www.tothenew.com/blog/how-to-implement-queue-workerapi-in-drupal-8/


Create a custom form in Drupal CMS for editors

Maybe just use a regular content type, add whatever fields you'd need, and let your Drupal editors edit regular nodes.

As a variation, use the ECK module so that you have custom entities (instead of nodes). And then let Drupal take care of storing the data in an appropriate table in the database. With such approach you get all sorts of extra facilities (integrations with other modules), out-of-the-Drupal-box ... Views, Rules, Group, Flag, you name it.

Another approach could be like I described in my answer to "How to implement a multi step approval with webforms/entityforms based on form components?".


OG group content notification for group administrators

Your task cannot be done in an obvious way. A piece of content can be content of several groups. If a user is admin in the first group, but not in the second group, should he receive the email or not? If a user is an admin in both groups, should he receive the email twice?
You'll have to think about that first before one can give a precise answer.

Either way, my guess is that one should create either a rule component "Send email if group admin" that receives a user and a group as variables, or one should create a view of group admins that the rule loops over. Do ask me for details if you still need the advice.


How to create a responsive theme with Omega?

So, there's plenty of good documentation on both Omega 3 and Omega 4. Depending on what your background is and what your experience level is there are a number of ways to approach responsive design. I suggest defining your needs for a responsive website, and then seeing how Omega can help you. If not Omega, than the Zen and Adaptive themes are also well documented. There are free tutorials and videos on youtube, your question here is too generic to answer.


Bootstrap external login from subfolder isn't working

I think this is related to how you're defining the DRUPAL_ROOT constant.

Several times I've had to make scripts interact with Drupal from sub folders, and I've found the simplest way to make sure things work correctly is to preface my code with the following:

<?php
chdir('../');
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

The key thing here is the chdir() call.

Also, when creating a path and you want to go up one folder, its usually ../ not /.., because directory paths should usually end with a /.


First thing you should do is contact your web hosting provider and see if you can go back to working copy of your website. After you have a working copy of your website download that into a local environment. I would recommend to this either a Mac or Linux machine (ubuntu os what I user).

Once you have your local environment you can start trying migrating from D6 to D7. You should never try an migration a production site.

From here you can use drush sup to upgrade your website. After your website is been successful upgrade from D6 to D7. You should consider uploading that to your web hosting provider.


Newbie Question - How do I add content to this page?

Am not clear about your requirement, right now you are trying to display it using a panels. If your requirement is just to show a custom page with custom text.. then just add a basic page as a content and place the text in body field. Then call the page using the given path.


You should add the field from the Block Type interface. Either add to the block type that comes with core or create a new one and add your fields.

Also, no, Drupal Fields and Form API elements are two different constructs. That is why 'link' does nothing. It would simply be:

$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'url',
];

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Url.php/class/Url/8.2.x

But you're creating more work that necessary.

In this context (a form) link pertains to a RenderElement and not a FormElement like url is.


WYSIWYG edit view of text is below image in content but node view isnt.

It is quite possible that the text format with which your field is being displayed is restrictive i.e. it only allows a subset of HTML tags.

I'm going to assume that you are talking about the Body field or more generally a text field attached to a Content type.

Ensure the field_ui module is enabled and go to the Manage display page for your content type. For the field in question, check if the formatter says Default.
Now, go to Administration > Configuration > Content Authoring > Text formats and inspect the first text format in the list.

If you are going to view as a different user, remember that Text formats are linked to permissions and an user's default text format is the first from the list in 2. that he has access to use.


Add custom html to a facet api facet block

You can create your own facet widget. Just extends from one of existing widgets. You can found examples in module facetapi.


Dynamic Content Type? (field appears based on previous taxonomy choice)

Try out the Conditional Fields module.

Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.
Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


User login through JSON request returning HTML instead of JSON

It turned out that the Redirect after login module was redirecting to the given URL, which resulted in HTML being output. I have disabled that and now I am getting the proper JSON response.


How to alter each article's comment setting by PHPMyAdmin

Comment settings for each post are stored in the node table. You can run the following, or similar, query:

UPDATE node set comment = 2 WHERE type = 'foo';


According to https://drupal.org/node/1848184#comment-6801690

  Check if you have the code for the main content on the homepage .tpl file:

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


Need help configuring new user signup email notification

The workflow for registering users can be configured at index.php?q=admin/user/settings. If this does not suit your needs, let us know how your workflow differs from what can be configured on that page.

I suspect you want to check the option Visitors can create accounts and no administrator approval is required. and uncheck the option Require e-mail verification when a visitor creates an account. The e-mail that are sent can be configured in the fieldset User e-mail settings and for some e-mails, you can configure whether to send them at all.


The Better Formats module provides this type of functionality.

See Better Formats Module.

  Better formats is a module to add more flexibility to Drupal's core
  input format system.
  Features
  Set allowed text formats per field. Set default order of text
  formats per field. Hide format tips per role. Hide more format
  tips link per role. Hide format selection per role per entity.


Returning HTML through an ajax-call in Drupal 8

Since we are fairly new in the Drupal 8 jungle I'll give some feedback how I fixed this. Be aware this is probably not the best solution.

Using a controller I included this function:

    /**
     * Inspiration page action
     */
    function inspiration(){
        $twig = \Drupal::service('twig');
        $template = $twig->loadTemplate(drupal_get_path('module', 'experimental') . '/templates/inspiration.html.twig');
        echo $template->render([]);
        die;
    }

This works fine, allthough it is not very beautiful.


with Drupal you should never have to deal directly with tables and add/edit/delete forms again - Drupal does it all for you.
In your case you could either extend the user profile and add a "resume" field or you could add a "resume" content type and use the reference module to reference it to the user.


How do I programatically generate multiple "add to cart" forms on product display?

I implemented this through patching Commerce Add to Cart Extras. My patch can be found here: https://www.drupal.org/node/1836200

In brief, the line item type contains a reference to an entity, a field collection item, actually.

I used views to generate a list of products with an add to cart form using Commerce Add to Cart Extras, joining (by a views relationship) on my field tables that provide the reference which must be attached to the line item.

Next, I had to alter Commerce Add to Cart extras so that the views result containing my entity id which must be added to the line item will copy that id over to the line item when the line item is created.

In the end, I have a list of multiple instances of the same product with a quantity field and a single add to cart button. Each product has the entity which must be added to the line item. When one of those products is added to the cart, the entity id gets copied over to the line item.


How can I recognize when the user is editing or inserting something?

Field nid is unset if node is created. Optionally, you can check if arg(1) === 'add'


Is there a standard way to control which node or entity links appear in which view modes?

If you are adding fields in hook_node_view then the most polite thing you can do is add them to the 'manage display' tabs for that content type. Do this using hook_field_extra_fields(). This way people can: hide or show them per content type, per view mode and also position them amongst other fields, just like any field API field.

Here is a code example where I have added the print links to the node using hook_node_view().

/**
 * Implements hook_node_view().
 */
function zest_general_node_view($node, $view_mode, $langcode) {

    // Add print and email links as pseudo field.
    $node->content['print_links'] = array(
      '#markup'=> print_insert_link() . print_mail_insert_link(),
      '#view_mode' => $view_mode,
      '#prefix' => '
',
      '#suffix' => '
',
      '#weight' => 20,
    );

}

Then I add them as a 'pseudo field' using hook_field_extra_fields().

/**
 * Implements hook_field_extra_fields().
 *
 * Adds the print and email links as a pseudo field.
 */
function zest_general_field_extra_fields() {
  $extra = array();

  $extra['node']['product'] = array(
    'display' => array(
      'print_links' => array(
        'label' => t('Print Links'),
        'description' => t('Links provided by the print module.'),
        'weight' => 20,
      ),
    ),
  );

  return $extra;
}

hook_field_extra_fields()


You can to use hook_prorocess_page for this.

In the theme's template.php file, add the following function (make sure it doesn't exist. if so, append the function content to the existing file)

function THEMENAME_preprocess_page(&$vars) {
  $image = ... // Generate your image's img tag here, optionally wrap with some DIVs.
  $vars['my_image'] = $image;
}

Now, you can access this variable as $my_image.


Save checkboxes value into another checkbox field

Yes, it's solved.

I don't need to add the permission to the product. I just check the permission that are check on the field_permission related to this node and then I display the Add to cart button only if the user meet the required permission.

Thanks


In code alter user registration and override approval to no approval required

I suggest you to code this directly in your module :

use _user_mail_notify()


Varnish has no SSL support; then what to use?

Content delivery platforms like CloudFlare and Fastly offer a wide range of SSL/TLS options. The question is, what are you trying to accomplish? Note that Varnish really won't do you any good for high transaction-volume sites because you're dealing with authenticated traffic. However, services like the ones listed above can be useful for delivering assets or for serving anonymous traffic.


Uploading an image from a form in my custom module

You shoud use Drupal file managing system. When Drupal is aware of a file, its data is stored in the file related tables. If you need to do something with a file you only need its identifier, called fid.

So, in your form upload the file using Drupal Form API, and store the fid in your table. Whenever you need to do something with the file use the fid to get all the file information.

This question may be very interesing for you:
Managed file: the file used in the field may not be referenced

Check also the file_managed Form API element:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file


If I understand you correctly, what you want to do is override the field template field.tpl.php.

To target specific fields you can rename your version of the file as per the template suggestion options for the field template.


Render a drupal form retrieved by drupal_get_form

The correct answer is to use drupal_render, which is used for render arrays like the form is. I tested this with a different form, and got the desired result so what you're doing should be right. Most likely you have a different error some where in your code causing this.

$html = drupal_render(drupal_get_form('form_id', $args)));


embedding a block inside a views template file

A Computed Field on the node itself can also pass the NID to a view, regardless of the page it's displayed on.

Add a Computed Field to the node type.

in Computed Code:

$node_field[0]['value'] = $node->nid;

in Display Format:

$display = views_embed_view('VIEWNAME','DISPLAY', $node_field_item['value']);

If you store it in the database, then the field can be called in via Views.


Drupal configuration on non root url (how to change $base_url)?

If your drupal installation resides on the webserver in a subfolder of the webroot for www.mymachine.fr, you can set the base path in the drupal site's .htaccess file.

Find the line that reads # RewriteBase /drupal
Uncomment it by deleting the "#" RewriteBase /drupal
Edit it to reflect your subpath/subfolder # RewriteBase /mydrupal

That block should look like this after the edits.

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /mydrupal

Then, reset your .conf (vhost entry) to reflect just the top level website (code sample below resets to default .conf setup):

<VirtualHost *:80>
  ServerName mymachine.fr.mydrupal
  DocumentRoot /var/www

  ServerAdmin webmaster@localhost

  # Log configuration
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory "/var/www">
      Options FollowSymLinks
      AllowOverride All
      Require all granted
  </Directory>
</VirtualHost>

This setup presumes that your top level domain does not have any redirection rules that forward/process all requests (such as the rules in an out-of-the-box Drupal or Wordpress .htaccess for processing requests with index.php)  If your top level domain has such a redirect rule in place, you may need to add another rule to exclude your mydrupal subdirectory.


Add field to an entity_view for dispaly in a tapir table in ubercart

So this is the ugly hack I used to resolve the issue:

  if (!empty($order->products)) {
    $build = entity_view('uc_order_product', $order->products);
    foreach($build['uc_order_product'] as $line_item) {
      $node = node_load($line_item['#entity']->nid);
      $vendor['#markup'] = 'uid) . '>' . $node->uid . '';
      $vendor['#cell_attributes']['class'][] = 'vendor';
      $line_item_id = $line_item['#entity']->order_product_id;
      $build['uc_order_product'][$line_item_id]['vendor'] = $vendor;
    }
    $table['#rows'] = $build['uc_order_product'];
  }


How to use ConfirmFormBase to confirm the action of another form?

As you've already discovered, ConfigFormBase just provides some buttons, handling for messages, and submit/cancel logic. On its own, it's not designed to be used as the sort of multistep form you're looking for.

Getting that functionality is pretty easy though; you could use the logic in Drupal\config\Form\ConfigSingleImportForm as a rough example. Basically you just handle the multistep part of it yourself. For example:

protected $step = 1;

public function buildForm(array $form, FormStateInterface $form_state) {
  // When this is the confirmation step fall through to the confirmation form.
  if ($this->step === 2) {
    return parent::buildForm($form, $form_state);
  }

  // Build and return your upload form as normal, but don't call the parent method.
}

public function validateForm(array &$form, FormStateInterface $form_state) {
  // The confirmation step needs no additional validation.
  if ($this->step === 2) {
    return;
  }

  // Perform any additional validation
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  if ($this->step === 1) {
    $form_state->setRebuild();
    $this->step = 2;
    return;
  }

  // Extract rows from CSV and set batch to import here
}


Turn off revisions for content types that contain certain types of fields (e.g. Field Collection)

You could use hook_form_FORM_ID_alter to alter your node forms of the content type (s) you need.

function my_module_form_node_form_alter(&$form, $form_state) {
  if ($form['#node']->type == 'my_content_type') {
    // Your code goes here.
  }
}

Now you need to know whether or not it has a field collection field on it. You can use one of the field api functions for this, for example, this will give you the field collections in your site:

$collection_fields = field_read_fields(array('type' => 'field_collection'));

Then you can check if your node has one of these to see if you disable the revision feature or not.

You can disable the checkbox appearance by adding an #access FALSE:

$form['revision_information']['#access'] = FALSE;

It's probably safer to repeat this operation and checks in hook_node_presave if that makes sense for your workflow.

Additionally, there are a couple of modules relevant to this issue, Jammer allows you to hide some specifics from the node creation form and so on, but nothing condition based. There's also Field SQL no revisions that will skip saving information for revisions, be careful because there's no come back from this one so you need to be very sure you're not using revisions for your fields in any other content type.


Check if the PHP Filter module (Core, optional) is enabled.


How to transfer multiple databases by sql-sync?

Drush sql-sync will only copy one database per run; if you have multiple databases to copy, you must run sql-sync multiple times.  Use --source-database=other and --target-database=other to specify some other database.  Use --source-target=mirror and --target-target=mirror if you want to copy a secondary mirror of your Drupal database (not your use-case).

Rename 'other' and 'mirror' to match the appropriate key of your database record.  See figure below.

Array
(
    [default] => Array
        (
            [default] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => drupaldb
                )
            [mirror] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => mirrordrupaldb
                )

        )
    [other] => Array
        (
            [default] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => otherdb
                )

        )

)

Update from NenadP:

It seems that you need to add --strict=0 when using Drush 5 to work around a bug in the sql-sync command definition.  This has been fixed in Drush 8.6-6.x.


minifying css in drupal and getting the original source css

Yes that looks like Drupal's built in CSS aggregation.

The easiest solution would be to turn aggregation off temporarily. Then you'll see the original sources in the markup.

You can turn it off at the admin/config/development/performance page.


Generate match list from two different content type on price basis

it could probably be done using Views

  You need Views if

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

and Views PHP

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

Creating a View limited to those content types, and including the relevant fields - it would allow you to create a Global:PHP sort field, in which you could use your formula to determine the sort order. It would be tricky though, since it appears you want to include duplicates and group them together.


Is Search API module 'English-speaking' only?

You;d need to use the Search API Entity Translation module to have this work as expected.

Going further if you wanted more control of the system and were using Database based indexes you would also want to install Search API Entity Translation Database Search


Views fields settings style settings no options avaible

I had the same problem and found that it is caused by using jQuery 1.8, so with an older jQuery versions it should works just fine.


You could write a small one-off DB copy function to accomplish the task. There a couple of modules around but they appear to be quite old, so it would depend on what version you run. Here's a tutorial for MySql (if that's what you use) DB access: http://www.w3schools.com/php/php_mysql_intro.asp


Rule on Saving New Comment not triggered

I cannot reproduce this problem. Attached is an export of a rule which fires when a comment is added to an Article or when a comment on an Article is updated. The Rule simply prints a system message containing the CID so that you can see the Rule was able to access the CID. I have tested this and I always get the message, with the CID, when adding or updating a comment.

{ "rules_comment_added_or_updated" : {
    "LABEL" : "Comment added or updated",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_i18n", "rules", "comment" ],
    "ON" : {
      "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" },
      "comment_update--comment_node_article" : { "bundle" : "comment_node_article" }
    },
    "DO" : [
      { "drupal_message" : { "message" : "Comment id = \u0022[comment:cid]\u0022" } }
    ]
  }
}

Note that in general you should not be using PHP code except as a last resort. It would be much better to use a custom action or condition instead. Both ways require writing PHP, but a custom action or condition is secure. In any case, neither is needed here.


Simple way to add dropdown arrows to a dropdown containing menu?

I would recommend that you use the settings of the Drupal Superfish menu itself. There is an option to use "Auto-arrows".

They can be further themed via CSS.

Superfish settings (in configure superfish block)

This is your site html source. That auto arrow element is there, but because it uses a white background-image you will not see it, so style it like you need it.


How to display records in table programmatically?

In order to achieve this you need to do the following

Inject the database service as db_query is not working in Drupal 8 anymore
Use of theme() was discouraged in Drupal 7 as well, instead you need to use render array #theme key
Use Drupal 8 Database API db_select and chaining stuff and extend a special class Drupal\Core\Database\Query\TableSortExtender for rendering the data in tabular form
Finally form a render array with #theme key, #header, #rows.

The following example from my custom module display the data in table along with pager

      // Prepare _sortable_ table header
      $header = array(
        array('data' => t('ID'), 'field' => 'id'),
        array('data' => t('Name'), 'field' => 'name'),
        array('data' => t('Email'), 'field' => 'field1'),
        array('data' => t('Age'), 'field' => 'field2', 'sort' => 'desc'),
        array('data' => t('Gender'), 'field' => 'field3'),
        array('data' => t('Operations'), 'field' => 'field4'),
      );

      $query = $this->database->select('location','loc');
      $query->fields('loc', array('id', 'name', 'field1','field2','field3','field4'));
      $query->addField('loc','name','name_alias');
      $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
      $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
      $result = $pager->execute();

      foreach($result as $row) {
          $rows[] = array('data' => (array) $row);
      }

      $build = array(
          '#markup' => t('List of All locations')
      );

      $build['location_table'] = array(
        '#theme' => 'table', '#header' => $header,
          '#rows' => $rows
      );
     $build['pager'] = array(
       '#type' => 'pager'
     );


Aggregating CSS breaks with Internet Explorer

The Advanced CSS/JS Aggregation Module might make it work correctly. If not, the advagg validator sub module might help identify the CSS that is breaking in IE.


It sounds like you wrote most of this yourself, or with some heavy work in Views maybe -- either way Good job! :)

You can solve your problem by saving the pager value into the users $_SESSION data. Every time they the pager page adds a key the querystring http://www.yoursite.com/page&page=2 you can check the querystring for the page key and save its value to the users session. Eg,

if (isset($_GET['page']) && intval($_GET['page'], 10)) {
  $_SESSION['your_custom_pager_index'] = $_GET['page'];
} else {
  $_SESSION['your_custom_pager_index'] = 1;
}

Then you can check for $_SESSION['your_custom_pager_index'] in your list form pager code to offset by whatever amount based on your index value.


PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column

Quick fix would be adding the missing single quotes around your variable. Forgetting the quotes can throw odd errors from this function, such as mixing a string for a column, like in your case.

There are less error prone ways to make short queries like this. See also Molot's answer.


You could use Display Suite to create custom layouts of your forms and content displays.

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

A combination of Display Suite and css will allow you to really tweak the standard layout of your theme.

Otherwise Panels is another module that allows you to customize the layout, among many other features.


How do we set required for new & optional for existing fields - when adding basic field to content type?

You can use hook_form_alter or hook_form_FORM_ID_alter to set require for that field.

function my_module_form_alter(&$form, $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  if ($entity->isNew()) {
    $form['my_field']['#required'] = TRUE;
  }
}

And, not set the field 'my_field' as required field.
Not tested, but it is a way to go.


Why does a header set via drupal_set_header() revert to text/html?

I think you are too late in the template_preprocess hook. The views display will have set it's header already before your hook gets called.

To test my thought have a look at the return value of the function drupal_set_header. It shows you all headers sent before.

If I'm right: Try implementing a hook which is is called earlier (maybe even before execution of the view query). Then your header will have precedence.


views entity reference to point email instead of uid in contextual filter?

Yes. If you're look to contextually filter a view based on an Entity reference's (user) email, you can add a Relationship with the value of Entity Reference: User. This allows your view rows to be join with the rows in the entity that is referenced.

With the relationship added, you can add a new User: E-mail contextual filter for the view.


Have you read the Open App Standard http://groups.drupal.org/open-app-standard/oas ? Here's an excerpt that might help:

  What is an app? Before we say what an App is it’s helpful to know who
  it’s for: An App is for the end user, typically a non-technical user
  of a Drupal site such as the site administrator....

  ...Technically, an App is a collection of new or existing Drupal
  functionality, including Modules, Features, and Themes along with some
  simple additional code that publishes the existence of the App to the
  rest of the App infrastructure.

  What distinguishes an App from a Module or Feature is that the App
  includes all of the additional polish, end-user UI, configuration UI,
  sample content, and documentation that are needed to fully meet a
  specific need. Whereas Modules and Features are more developer-centric
  and provide building blocks for larger functionality, Apps are larger
  blocks of completed functionality.


Deleting users who have created content can lead to access bypass?

Indeed the page at https://drupal.org/node/1732920 has an example scenario of how this can happen. I don't remember verifying that myself, but believe it came out of some research on an issue reported to the security team. I think Greg_1_anderson's comment about "edit own page content" is probably an important element to that scenario.

I've also seen this happen with node access modules. In discussing it with people, the theory that seems most likely:

User 42 exists and has been granted access to view and/or edit some nodes on a site using a node access module.
User 42 gets deleted, this invokes hooks including in the node access module which may take some action like updating the records it previously stored about user 42 to now point to uid 0 instead of 42
OR...perhaps it forgets update those records and instead they just exist with user 42 on them
When node access records are rebuilt, the code of this node access module either sets faulty records with uid 0 (based on step 2) or it fails to properly load a user and php/mysql will behave in their usual loosely typed ways and take the need for a record with a missing uid value and just insert a zero for the uid.

It's definitely a bug that has occurred more than once. If it can be prevented in code then it should be submitted to that module's issue queue to fix it.


Contextual links don't display in a floated custom region

Try to add an "overflow:hidden;" to the wrapper of both the content and the contextual links to force it to fill the dimensions of its children. Either that or add a clear as a sibling of the elements. What's probably happening is the wrapper is being rendered to 0 height.


the difference between the drupal login "block" and mysite/user/login

There is no such difference. Both forms provide the same input fields and use the same validation and submit handlers. The one is generated by user_login(), the other is generated by user_login_block().


Programmatically add node translation drupal 7 ( Entity translation )

Found the answer ! Thanks to my co worker.

In order to add translation to a node you need to add every translatable field like this in your creation node code :

 $node->field_trailer['fr'][0]['value'] = $movie['link'];
 $node->field_trailer['de'][0]['value'] = $movie['link'];
 $node->field_trailer['en'][0]['value'] = $movie['link'];

And after node_save($node); add

  node->translations->data['de']['entity_type'] = 'node';
  $node->translations->data['de']['entity_id'] = $node->nid;
  $node->translations->data['de']['language'] = 'de';
  $node->translations->data['de']['source'] = 'fr';
  $node->translations->data['de']['uid'] = $node->uid;
  $node->translations->data['de']['status'] = $node->status;
  $node->translations->data['de']['translate'] = 0;
  $node->translations->data['de']['created'] = $node->created;
  $node->translations->data['de']['changed'] = $node->changed;

For each language and the node_save($node) again.


How to automatically add new users to a OG Group (MyCommunity) using Rules?

One of the elements you can use under actions is "Fetch entity by id". Say the node id of your MyCommunity group is 10, then the Entity type value will be Node, and the Identifier value is 10. In the Provided variables section, you give your fetched entity a label and variable name. Let's give it a label of MyCommunity, and name it my_community. Save the action element. The next action element to add is "Add entity to group". The Entity data selector is the new user so give it the value of "account". Then under group, the data selector is the variable name we created in the previous step, which is "my_community". I tested this out locally and it worked. Here's an export of the rule.

{ "rules_115407" : {
    "LABEL" : "115407",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "stackexchange" ],
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "user_insert" : [] },
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : "10" },
          "PROVIDE" : { "entity_fetched" : { "my_community" : "MyCommunity" } }
        }
      },
      { "og_group_content_add" : { "entity" : [ "account" ], "group" : [ "my_community" ] } }
    ]
  }
}


How to upload a static copy of a pages HTML to S3

If you want to speed up the transfer process you could use HTTPRL to send the data to S3 in a non blocking request. You can also use it to do threading.


How Can I display values of variables in a "PHP contextual filter code" to debug my code?

Install the Devel module with the Search Krumo module and you will be able to use the dpm() function.

  Devel

  Helper functions for Drupal developers and inquisitive admins.
  Enable the included Kint submodule as for pretty print of variables. kint($array) function is provided, which pretty prints arrays. Useful
  during development. Similarly, a ddebug_backtrace() is offerred.

You can read how to use the Devel module at: Debugging Drupal (a page which gives a brief overview of some of the tools you can use to make Drupal development and debugging easier).


Why drush fails to rsync between my two local instances?

You cannot change the file timestamps or change permissions by being a member of a group, you have to be the file owner, or root. If you cannot be the other of that file, you might need to avoid trying to set permissions at all.

So you may try to modify your drushrc file (e.g. sites/default/drushrc.php) and add the following arguments for rsync command:

$command_specific['rsync'] = array('mode' => 'rlptzO', 'verbose' => TRUE, 'no-perms' => TRUE);

If running rsync on remotes, edit your aliases.drushrc file (e.g. sites/default/aliases.drushrc.php) and add something like:

$aliases['mysite.dev'] = array(
    // here are your settings such as uri, root, remote-host, etc.

    'command-specific' => array (
      'rsync' => array('mode' => 'rlptzO', 'verbose' => TRUE, 'no-perms' => TRUE),
    ),
);


Features local permission issue Warning: mkdir(): Permission denied in features_export_build_form_submit()

The point is that your folder needs to runs under the _www group (www-data is the group and user for linux machine). You can do it within a terminal or with the finder too.
So find the webserver root folder (~/Sites/MYDRUPALSITES, for example) and pull up the Finder Get Info window.

Then on the bottom left corner, click the group icon (The picture with 2 people) and then hold Option then click the “+” button. This will allow you to select system users and groups. Find the World Wide Web group, select that and change the group priviledge to “Read & Write” and then use the cog-wheel to “Apply to enclosed items…”

Or just run the following chgrp (change group) command via Terminal : easiest way (y) !

cd ~/Sites

sudo chgrp -R _www MYDRUPALSITES/

That's the most revelant answer I can answer with your question. But it can also be the owner or a bad installation permissions set. Simple google : permission issue mamp/xammp. Or you could also run

sudo chmod 777 -R MYDRUPALSITES/

But I clearly do not recommend it on a online production (in local it's "acceptable").


How can I add a new value to a multi-value field programmatically?

Using this:

$account->get('field_useragent')->appendItem($_SERVER['HTTP_USER_AGENT']);

However, that doesn't seem like a good idea to me. Over time, that list will grow big, multi-value fields don't scale that well. All values are always loaded, on save, all values are inserted again into the database.

Maybe you want a list of unique user agents, but even that is hard to control with versions and so on. If you want a log, then save it somewhere else in your own table.

http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf doesn't have this yet, would probably make sense to add it.


I found it-- the Date field can store dates or datetimes, and you have to change your code for each case.
When you add a Date field to an entity, you can choose Date (date) or Date and time (datetime) as the Date type.
More information in this blog post, but the basic idea is:
$node->set('field_date', date('Y-m-d', time()));
$node->set('field_datetime', date('Y-m-d\TH:i:s', time()));


How might I have Webforms save files to private file system or as a database blob?

Did a little digging into Webform. There is a setting for this in webform I believe. There was an issue posted in the webform issues but it has been resolved. Saving file submission to private directory

OP already solved but for future onlookers: There are instructions I believe on how to accomplish this in the comments of the issue referenced above, also make sure Webform is up-to-date.


What is the difference between 'Groups audience' and 'Groups content visibility' in Organic Groups Access?

Group audience = which group(s) content was posted to.

Group content visibility = who can see the posted content, only group members or all site users.

Do contact the author directly to ask them and/or let them know that the tutorial could be improved.


Whats the difference between "Content Type" and "Content Types" on a block configuration form?

"Content type" comes from CTools and "Content types" comes from core.

Simplified summary

"Content types" comes from core and is the preferred condition to use. The "negate" option is also present in core, but it is suppressed by the block module (source). In contrast to core CTools provides this condition not just for nodes but for any entity type (taxonomy terms, custom entities etc.). That's the reason why in case of nodes there is a duplicate set of entity bundle conditions.

Issues on drupal.org

Now there's this core issue Duplicate node type setting in block visibility which was closed as "works as designed". The problem shall be fixed by CTools (as in remove the duplicate entry).

This leads us to this CTools issue Duplicate node type visibility condition in block settings which was put on hold until core itself replaces CTools functionality to provide block visibility settings for any entity type (not just for nodes) including the "negate" option.

Which finally brings us to this core issue Add entity bundles condition plugin for entities with bundles where the progress to move CTools functionality to core to replace the current node type core condition is being tracked.


How to properly compare values of two identical entities?

Assuming you have two entities $a and $b.

You can convert them to arrays and compare the two arrays.

// if the position matters
$is_equal = ($a->toArray() === $b->toArray())

// if the position doesn't matter
$is_equal = ($a->toArray() == $b->toArray())

Edit: I thought the OP was about discovering if two entities have identical data.
After reading the question again it seems that OP wants a way to mark what is the difference in data.


How to properly call drush command from another drush command?

If you use drush_invoke, you should first use drush_set_option('strict', FALSE); to turn off strict option checking for the subcommand.  drush_invoke runs a subcommand in the same process, which can be more efficient; however, there are a number of ways that this can go wrong, so it is often better to use drush_invoke_process instead, to run the subcommand in its own process.  If you do this, there is no need to disable strict option handling.

drush_invoke_process('@self', 'twig-compile', $args, $options);.


How to limit number of files uploaded with plupload integrtion module?

The way I limited it to single file, was to create js file and attach it to the form. In that file, I bound a function to QueueChanged, to remove excess files and hide "Add file" button:

(function($) {

Drupal.plupload = Drupal.plupload || {};

/**
 * Attaches the Plupload behavior to each Plupload form element.
 */
Drupal.behaviors.download_plupload = {
  attach: function (context, settings) {
    $(".plupload-element", context).once('download-plupload-init', function () {
      var add_button = $(this).find('.plupload_button.plupload_add');
      var uploader = $(this).pluploadQueue();
      uploader.bind('QueueChanged', function() {
        var local_uploader_element = this;
        // Remove files exceeding the cardinality setting.
        if (local_uploader_element.files.length >= 1) {
          var i = 0;
          for (i=0;i<local_uploader_element.files.length;i++) {
            if (i >= 1) {
              $(this).removeFile(uploader.files[i]);
            }
          }
          add_button.hide();
        }
        else {
          add_button.show();
        }
      });
    });
  }
};

})(jQuery);

This is a simplified version of js found in FileField Sources Plupload, trimmed, without Field API specific parts, and made to work on all plupload elements.


Execute Drupal Feeds Import Programatically - Where to put code

I think you have found the code from this link. In this case you can mention this code in a custom function or hook_cron or in a separate page. Totally depends upon you.

Follow
Triggering the Feed Import module
and
Programmatically execute FEED import


How to add advertisement node at the end of Slideshow

slides are usually images or maybe node bodies (html). It doesnt really matter that advertisments have different fields. I had some code in Drupal 6 you could adapt to D7 or your needs, look into hook_views_pre_render() ...

You simply want to load your advertisement node(s) before the view is rendered and add them to the end of the slideshow ... see below.

//d6 example
function MYMODULE_views_pre_render(&$view) {

  if ($view->name == 'your_view' &&
    $view->current_display == 'slideshow_xyz') {
    // Insert something to the end of the view results.
    // For example another "node" or advertisement.
    $some_node = node_load(array('nid' => 456));
    // make a fake view row item with your advertisement.
    // you should create all fields used in "slides" from your
    // advertisement node data.
    $advertisement_item = new stdClass();
    // add your advertisement fields as fields being used by the Slide view.
    $advertisement_item->a_field_views_is_using = $some_node->advertisement_field_1;
    //  ... add all other view row items you are using ....
    // make this advertisement "row" in the results appending to the view results for slides.
    array_push($view->result, $advertisement_item);
  }
}


How do I configure the recurring node checkout payment?

I got it working.  I've read the file "README.txt" and found that any product type can be a recurring product.

Now I configured my existing product type to add the fields, required by recurring payment.  So, now when I checkout, it does create a recurring entities for this order.  Hope it will help someone.


The Media Module (2.x) uses the File Entity module. Files become 1st class citizens in your Drupal installation just like a Node or Entity or a variable. A FileEntity can be queried using Views for instance.

IMCE (to my knowledge) is simply a file browser (bridge) for your server compatible  with TinyMCE and I suppose CKeditor now. Files are just files on the system and drupal isn't 100% aware of them and their meta-data.

If you only need to browse files then IMCE has its usages. If you want something more meaningful and integrated with Drupal as a whole look at Media, and maybe like Media Browser Plus.


add custom markup on a specific element/filter in a exposed filter (views)

You can override the twig template responsible for that particular HTML output. You already see debug hints so you can see which template to check out.

Then copy that template to your subtheme and edit it there. Don't edit the core Drupal theme to avoid messing up your project maintainability.

Working With Twig Templates

You might be after select.html.twig and function template_preprocess_select.


Is there a printed map / tree / graphic of a sample array(s) during each phase?

Devel is a good place to start. That will make the function dpm() available to you. This will allow you to print out arrays in an extremely user friendly visible way. If you're doing any sort of development you should really look into this module. I know when I'm trying to figure out what's being called for a given area I often use the combination of dpm and debug_backtrace.

There's also a theme developer that relies on Devel that you can you to see a back trace of functions.


You can create a View that shows the users who haven't authored any nodes, and then use VBO https://www.drupal.org/project/views_bulk_operations  to delete those users.