Where is the service container compiled to?

As @mradcliffe described in a commment, the normal Symfony way to compile and cache the service container is a single php file. Drupal used this until Sep. 2015. If you have an older installation, you still find the compiled container in php/**/, because it was never deleted by newer versions.

For better performance Drupal has changed this and stores it now in database in the table cache_container. The change record and how to take a look inside the container to debug it:

Change record: The service container definition is now stored in the database by default


When does hook_field_storage_details_alter() fire?

The function that invokes both hook_field_storage_details() and hook_field_storage_details_alter() is _field_info_prepare_field(), which is indirectly called from the following functions:

field_info_cache_clear()
field_info_extra_fields()
field_info_field()
field_info_fields()
field_info_field_by_id()
field_info_field_by_ids()
field_info_instance()
field_info_instances()

In other words, all times information about a field is required, that hook is used.
As Clive points out, _field_info_collate_fields(), the function that directly calls  _field_info_prepare_field(), caches the information returned by those hooks, which means they are not always invoked; they are invoked when the cached data don't exist, or have been removed. This makes hook_field_storage_details_alter() used in a similar way to hook_menu_alter(), which is called only when the menu definitions need to be rebuild, and not all times Drupal is retrieving the menu definitions given by all the enabled modules.


How to add a send email action link in views using the same VBO send email action

In order to do this with VBO you'll need modify the system_send_email_action_form form (to default its recipient) and add some custom JS (to create click events that automatically submit the VBO form).

An easier alternative here is to use the Views Send module which does nearly the same thing with a slight UI difference; there's a Send Email button at the bottom of the view as opposed to a send email link for each row.


How can I create a Drupal/IFTTT trigger or action?

There is a module for that.
Rules and/or Gigya

probably more around.


How to access all of the properties related to Commerce Line Item entity in a rule?

Below is a possible approach you can use to solve your question. It provides the details about how I was able to have a set of Drupal messages being shown at checkout time, which look similar to this testcase I used (for a cart with 3 line items):

Current line item has label 'USB-BLU-08' and id '17'
Current line item has label 'TSH4-BLK-MD' and id '18'
Current line item has label 'MES1-BLU-OS' and id '19'

To get this to work, I created a custom rule, which looks like so (use the Rules UI to import it in your own site):

{ "rules_access_line_items_at_checkout" : {
    "LABEL" : "Access line items at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } }
          ]
        }
      }
    ]
  }
}

Some details about it:

Rules Event: After completing the checkout process.
Rules Condition: none.
Rules Action: Create a loop, to iterate over each line item. And for each line item, show a Drupal message, starting with "Current line item has ...". Obviously, at this point you could display any of the properties related to a line item.

Easy, no?

PS: I'm assuming this question is about D7 ...


How to add multiple images to a node using node.save service?

[{ "fid": 1 }, { "fid": 2 }];

have you tried this?


How do I display multilingual logos in D7?

For D7, this is very painless.

In i18n, enable 'Variable Translation' module. To do so, be sure to have at least variable 7.x.2.x, else this module is not available. Here is the text from the module page:

Multilingual variables that switch language depending on page language.
Requires: Internationalization (enabled), Locale (enabled), Variable
(enabled), Variable store (7.x-2.x) (incompatible with version 7.x-1.2),
Variable realm (7.x-2.x) (incompatible with version 7.x-1.2)

After that, go to:

configuration->Multilingual settings->variables (tab)->Theme settings. check the boxes. Then go to your theme and set a logo for each language.

That's it!


Find the custom module responsible for a URL

You can use "hook_menu_alter" to list all routes and you can see the module via the module key.

function HOOK_menu_alter(&$items) {
    if(isset($items['yoururlpattern'])){
        drupal_set_message($items['yoururlpattern']['module']);
    }
}


How do you set a node reference field's default value when creating a node programatically?

This should work :

$values = [
  'type' => 'competition',
  'title' => 'my title goes here',
  'field_competition_node_reference' => [['target_id' => 1]],
];
Node::create($values);


Granular role access on a per Entity basis

but that doesn't seem like a very good solution.

Yes, it is.

What you're saying makes perfect sense, just do it :)

access() (or checkAccess()) is called for each entity separately, you can implement any imaginable logic in there, that's completely up to you.


If your language is not already added, you can do it in this interface admin/config/regional/language/add
You have to check that your new language is activated in the languages manager admin/config/regional/language
Check that this modules are activated : Local, i18n
In your content type manager, check that multilingual settings tab exist
In this tab, choose the elements suitable for your case
In Publishing options tab, check that multilingual support is activated


You can do it in function phptemplate_preprocess_page exists in template.php

The below is code to remove unwanted js

function phptemplate_preprocess_page(&$vars) {

  $scripts = drupal_add_js();
  //PRINT THIS ARRAY AND UNSET THE UNWANTED ARRAY
  // unset($scripts['module']['sites/default/files/js/jquery-min.js']);
  unset($scripts['module']['YOUR_PATH_TO_JS']);
  $vars['scripts'] = drupal_get_js('header', $scripts);

}


Ajax callback on Views exposed form filter

Sounds like there is an ongoing core issue queue -
https://www.drupal.org/project/drupal/issues/2842525
After applying the patch -
https://www.drupal.org/files/issues/2020-03-27/2842525-83.patch this seems to work.


How to delete a node/nodes created by a user with rules?

Add an action for "Fetch by Property" > Node
Property > Author
Value > The user
Add a Loop
Add an action for "Delete an entity > List Item" inside the Loop (on the right)


Any particular vacuum policy to increase performance using Drupal with PostgreSQL?

In theory you can run your database optimization commands any time you want, but I think at least bi-weekly helps. However, if by running database optimization commands you intend to improve the performance of your site by more than 5%-10%, I'm afraid no vacuum optimization policy will do. You will need to utilize traditional performance troubleshooting procedures such as checking all your server's error logs, access logs, database slow query logs, as well as taking in consideration your peak and average load versus your current architecture.


How to build a custom block with a image field

You could create (anyway) a content type and use the module Node Blocks. Every content you create with this content type are automatically available as block. Maybe a bit overhead if you just need to create one.

Another solution may be the BEAN Module. But just dropping the module name, never worked with it.


How can I get my RSS feed to be Auto Discovered?

Attach the Feed display to a valid Page display. The "Master" display may not be a valid page display.

An example of this can be seen in the default "Front Page" view. In this view, the feed display is attached to page_1, which is the page at the URL /node.

See the YAML export snippet from views.view.frontpage.yml below:

  feed_1:
    display_plugin: feed
    id: feed_1
    display_title: Feed
    position: 2
    display_options:
      sitename_title: true
      path: rss.xml
      displays:
        page_1: page_1
        default: ''


Drush pm-updatestatus No JSON output on success

Did you check to see if $? is correctly set? It should be 0 for success, and 1 if there was an error. Please open an issue in the Drush queue if this is not the case.


Form submit with radio in table has data in form_state['input'] and not in form_state['values']

At last I managed to find the answer (after a lot of experimentation). The following code works fine for me. I am not sure if everything is needed, but I won't touch it as long as it works.

Pay attetion that I use an associative array for the #rows array, in order to be able to find the correct row without keeping track of indexes.
The most bizzare part is that I had to add $form[$key]['#type'] = 'value'; to hold the selected value.
The '#name' => $key, is obviously used to group the radios
together per row.
The '#id' => drupal_html_id($key . '[' . $item . ']'), was also
added, but I'm not sure if it's needed.

Obviously one does not need to use a seperate column for the label, but I display it this way because in my code I use drop downs and other controls instead of the labels shown here.

Here is the code:

function game_test_form($form, &$form_state) {
  dpm($form_state, 'form_state');
  $test_data = array(
    'alfa' => array(1, 2, 3),
    'beta' => array(1, 2, 3),
  );
  $header = array(
      t('Name'),
      array('data' => t('First'), 'colspan' => 2),
      array('data' => t('Second'), 'colspan' => 2),
      array('data' => t('Third'), 'colspan' => 2),
  );
  $form['undefined'] = array(
    '#tree' => TRUE,
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array(
      // The keys here are used later on for the correct #row insertion
      'alfa' => array('title' => t('Alfa')),
      'beta' => array('title' => t('Beta')),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $table = &$form['undefined'];
  foreach ($test_data as $key => $data) {
    // This stores the value in the $form_state['values']. It must be outside the table.
    $form[$key]['#type'] = 'value';
    foreach($data as $item) {
      $element = array(
        '#type' => 'radio',
        // this value will be assigned to the $form_state['values'][$key]
        '#return_value' => $item,
        '#default_value' => isset($form_state['values'][$key]) ? $form_state['values'][$key] : 0,
        // Radio group stored in input[#name] with the selected radio's #return_value as value
        '#name' => $key,
        '#id' => drupal_html_id($key . '[' . $item . ']'),
      );
      // Attach the radio to the logical tree, so as to be included in $form_state['values']
      $table[$key][$item] = &$element;
      // Attach the radio to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => &$element);
      unset($element);
      // Attach its label to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => array('#markup' => 'Label ' . $item));
    }
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}
function game_test_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
  $form_state['rebuild'] = TRUE;
}


Pass custom variable from template.php to *.tpl.php

Every element key in the root of the $variables array will be available in the template file as an actual variable. The mechanics behind this is in theme_render_template(), which uses PHP's extract() function on the theme's variables.

So when you look at $content in the template file, that corresponds to $variables['content'] in the preprocess function.

Similarly, if you add $variables['newVariableName'] in the preprocess function, it will be available at $newVariableName in the template file.

If you want to add it to the content array, you need to do so explicitly in the preprocess function, e.g. $variables['content']['newVariableName'] = ...

Bear in mind that the content array is supposed to be a render array, so that's probably not the best place for it. The way you have it currently is fine, just use if (isset($newVariableName)): in place of your current array_key_exists condition.

Your current method is considered best practice for passing variables from preprocess functions (whether in template.php or a module file) to template files, you don't need to change anything in your thinking there.


How do I give the following responsive information in the .info file?

Your D7 declarations have the effect of placing the media query in the markup, and I think you want to replicate that method. You can do this in the library declarations, e.g.

stylesheets[all and (max-width: 760px)][] = css/mobile.css

Becomes:

mobile:
  version: 8.x-1.0
  css:
    layout:
      css/mobile.css: { media: all and (max-width: 760px) }

Note I am assuming this is for layout, hence my use of the "layout" SMACCS category for this library.

Personally I don't really bother with such things and write the media queries in the CSS, if you have many media queries you're going to have a lot of extra http requests if you're always splitting files based solely on breakpoint.


The template file you have to create should be

block--menu--menu-top-menu-navigation.tpl.php

Hope that helps.


How to allow special character in username?

You have to override the defualt user_validate_name($name) :

Verify the syntax of the given name.

To do that, define your username validation code in your custom module

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form['#validate'] = array();
    $form['#validate'][] = 'registration_username_validate';

  }
}

And inside registration_username_validate function do your logic to allow your special characters.

Care about security issues caused by allowing special chars in username and about display issues not sanitized usernames may cause in themes.


What is the purpose of Master Display in Views module of Drupal 7? Why is it not present in every Drupal 7 installation?

To always see the Master Display you need to set the 'Always show the master display' setting at

admin/structure/views/settings

The Master Display is a convenience and time saver when you have a set of related displays (block, page, feed etc.). You create the master view and then all of the other displays are 'clones' of the master that you then customize individually. Also, when you revert a setting in an overridden display it will revert to that of the master. I also think that the master display is fully saved in the database, and for all the other displays on the same view only the overridden parts are saved, hence less storage.

The Master Display has no associated menu and is therefore good when you need a view but do not want to unnecessarily create a menu entry (ie page) or block or other views resource. It is typically used in this fashion when embedding a view in code, or by other modules that take a view as a parameter, ie Answers, and Views Field View.


What database backend are you using? Sounds like a case problem, that a cache entry with a different upper/lower case version exists and then it can't map that back. I'd suggest using only lowercase but this shouldn't happen IMHO and it doesn't for me:

>>> $cache = \Drupal::cache();
=> Drupal\Core\Cache\DatabaseBackend {#48
     +"_serviceId": "cache.default",
   }
>>> $cache->get('foo');
=> false
>>> $cache->set('foo', 'bar');
=> null
>>> $cache->get('foo');
=> {#9809
     +"cid": "foo",
     +"data": "bar",
     +"created": "1505412278.945",
     +"expire": "-1",
     +"serialized": "0",
     +"tags": [],
     +"checksum": "0",
     +"valid": true,
   }
>>> $cache->get('Foo');
=> false


Generate js variable before javascript loaded

It is also hard to say if this will work without seeing exactly what you need to do, but you may want to play with the scope, group, and weight options for drupal_add_js().  These may help you get the order that you need.  From the docs

  The exact ordering of JavaScript is as follows:

  First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by
  the theme.
  Then by group.
  Then by the 'every_page' flag, with TRUE coming before FALSE.
  Then by weight.
  Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js()
  that happened later in the page request gets added to the page after
  one for which drupal_add_js() happened earlier in the page request.

When I have been in similar situations, I implement a template_preprocess_html(), create some markup, stuff it into $variables, and then output this before the print $scripts in html.tpl.php  I have to use this in some very specific situations where I need to output JS very early in the <head> before CSS and JS is loaded.


You have to add the cache tag of the menu, in this case the main menu:

  '#cache' => [
    'tags' => [
      'config:system.menu.main',
      ...


Form textfield AJAX validation "deletes" injected services to form

For anyone running into this problem or AJAX call that fails on the second call intermittently, check the properties used on your AJAX form class for the right access. It seems a trivial thing but change the properties of DInjected services to protected. Refrain from using private as the dependency serialization from Drupal won't be able to get those for caching purposes.
Check this link for more information.


Drupal Commerce "add to cart" form with complicated attributes

The biggest problem is that the Drupal Commerce module adds to cart
  products with different attributes as a single product.

Have you tried unchecking the option to: "Attempt to combine like products on the same line item in the cart."

It's on the "Add to cart" product reference field formatter settings on the product display content type

e.g: admin/structure/types/manage/product-display/display


As far as I can see, there isn't a module that allows to the users listed in a user reference field to edit the user account where the field is contained.
You should write your own module.

The easier step is to alter the access callback for the user edit form, and use a function that checks the value of that field, comparing it with the value of the user currently logged in.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/edit'])) {
      $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
  }
}

function mymodule_user_edit_access($account) {
  // The argument is the user object for the user profile being edited.
}

The default access callback is user_edit_access() which should be always called to verify that the currently logged in user has still the permission to edit the user profile, even if the user is not listed in the user reference field; users with the permission to administer users should always be allowed to edit a user account.


Can't moderate content from "View Draft" page using Workbench Moderation

Figured this out.  Was so easy it was hard...

Had to configure the "Workbench information" block and set it to "Content" region.  It then would show up above the content.  I also had to add the tags in the "Page elements" panel settings.

Hopefully this will help someone else out.


Manipulate texts before rendering to frontend

Since version 5, Drupal provides filters, a mechanism to manipulate the value of a text filter before rendering. In Drupal 8, filters are implemented as plugins.

So, in order to have two (text) fields which can can manipulate the value before display, you would need to

Create a custom filter (in a custom module)
Define a text format specific for your two fields, configured to use your custom filter (and any other filter you still want to apply)
On your content type, configure the two fields to use that text format
?
Profit

You filter code would look like

namespace Drupal\celebrate\Plugin\Filter;

use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * @Filter(
 *   id = "filter_ninjafart",
 *   title = @Translation("NinjaFart Filter"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class NinjaFartFilter extends FilterBase {
  public function process($text, $langcode) {
    $text = doSomethingWith($text);
    return new FilterProcessResult($text);
  }
}


One quirk that I have run into is that everything that happens during a node_load and node_view happens during indexing.  Take a look at _node_index_node start tracing backwards to see the process.

This means that any expensive operations that happen when a page gets viewed also happen when a page gets indexed.

For example, I had a site a while ago that queried an external webservice during node_load and I also noticed that search indexing was slow.  In my instance, the external webservice calls were adding up and not needed during indexing.  I solved it by doing something like

function foo_node_load ($nodes, $types)
{
  if (arg(0) != "node") return;

  // rest of hook
}

So, I would take a look at what else could be going on in your hooks and preprocess/process functions that could be slowing the process.


Print primary and secondary tabs separately

Finally I ended up like this:

<?php
  $primary = menu_primary_local_tasks();
?>

<?php print render($primary); ?>

The above code will return the primary links:

To print the secondary links

 if ($secondary = menu_secondary_local_tasks()) {
    $output .= "
\n". $secondary ."
\n";
  }

Above code will return the secondary links for the theme.


Display 2 contents types fields in 1 view

If there is a 'venue' content type linked through a node reference field, you can do it using a relation in a view.


Display/hide CCk field with custom PHP and rules or

Two quick ways come to mind.

Off the cuff...

You could use the preprocess_node() hook, something along the lines of:

MYMODULE_preprocess_node(&$variables) {

  if ($variables['node']->type=='THISKINDOFNODE') {

    if (empty($_SESSION['VARIABLE')) {
      unset($variables['node']->field_B;
    } else {
      unset($variables['node']->field_A;
    }

  }

  // other preprocessing here

}

You also could create a node--TYPE.tpl.php file and inside it, do something like this:

if (empty($_SESSION['VARIABLE'])) {
  hide($content['field_B');
} else {
  hide($content['field_A');
}


$items['admin/sponsorship'] = array(

    'title' => 'Sponsorship',
    'page callback' => 'system_admin_menu_block_page',
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
);

Seems to have done the trick.


EDIT

You can try the below code its working fine for me.

$views->items_per_page($item_num); instead of
$views->set_items_per_page($item_num);

Related questios

May be this can help you


Page Manager on a variant of the node url

I don't know if this is the only way to do it but I just add custom pages at /admin/structure/pages like:

/node/%node/admin

I guess there are some benefits to doing it separately instead of as a variant of the main /node/%node because now your selection rules etc. are easy to manage for different content types, for example.

Your arguments page should look like this:


How can I stop a specific page in the Omega Responsive theme from being responsive

You can use the Context and Delta modules. Delta was developed by the Omega developers and Context+Delta is part of the Omega philosophy.

Use Delta to create a variation on the original theme that does not respond to theme width.  Uncheck "Enable the responsive grid" setting in the theme, for instance. Then use Context to enable your Delta'd theme variation to trigger only on a certain path, in your case the page with the iframe.


You want to be looking at the permission "vote on polls" that is the one you want to enable for that user.


Remove contributor role when user deletes all of his content

Checkout the rules bonus pack

  Conditions

  Check number of results from a view: This condition loads a view and checks   the number of results – condition is passed if it is at least
  as many results   as you set. You can pass on arguments to the view.


How to distinguish between custom modules and contrib modules?

If you want know which module has been upgraded or not and what things upgrade in module then you can use hacked module of drupal.

Go to hacked module configuration and click on "list project" Let it do the work.It will process the modules and will check for the changes.

Once it completes the process you will get a list of module along with the number of changes done in the modules.

Now open the directory sites/all/modules/ and check the modules which are displayed in the list you got after hacked process.The listed modules in the result are the contrib modules and rest of the modules should be custom.


Views CSV export, not exporting complete data

As an alternative to the 2 modules you're using, you could also try to use the Forena module (Disclosure: I'm a co-maintainer of it). Here is a quote from that page:

  ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

And here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

  Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

These are the steps for creating such CSV files are:

Create a custom SQL query, in which you have the full power of SQL at your fingertips (and various extra features related to it provided by Forena).

Here is a (basic) SQL I'd use for answering this question:

  SELECT nid, title, type, uid

  FROM node

Create a custom report, either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor.

Using the WYSIWIG editor, in about 10 secs (= a few mouse clicks later on) you'd have a report for which the layout (in XHTML) would look like this:

List of all nodes in this site

Report caption

      nid
      title
      type
      uid

      {nid}
      {title}
      {type}
      {uid}

As part of "designing" this report, you should enable (within what is called "Document types") the option to export to CSV files (possible other options like XLS, DOC, PDF, etc also if appropriate).

At then end just "Save" the design of such report. This will be used later on, to retrieve all the specs of your report, when you want to browse (run, execute) your report.
Browse the report (= enter its relative path, or click some menu link if your design included such link) and then use the CSV link in it to actually save (= export) the report in (eg) CSV format.
Note: These steps do not require any PHP coding.

Bonus: instead of CSV format, you also have an option to format it as either XML or JSON. For more details on that, refer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

Example

Here is an example of (part of) a CSV file I created using the above approach:

  nid,title,type,uid

  33,Demo title,article,19

  39,"Demo, with some commas in the title, just a test",article,1

  72,Yet some other Article,article,8

  73,Article with some field collection data,article

The above CSV file contains:

the typical CSV header in record 1 of it, whereas the values in this record correspond with what was requested in the report design, as specified with the ...	 tags in the report layout.
1 record for each result that was selected.
1 specific record with a node title containing commas (shown with surrounding "...").

More info

For more info (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module.


How to find the name of changed file in Forms API

I have just verified it... Form submit handler does store old values and new values..

In $form you see old fid in #node property , In $form_state['values'] you see new fid that was uploaded...

By comparing above two in your submit handler you can take action..

function my_custom_submit_file_alter_detector($form, &$form_state) {
  dpm($form);
  dpm($form_state);
}


Webservice args types automatic validation

Although it appears Services doesn't validate the incoming data based on the type, you can use an access callback to build your own validation.

Add something like this to your Service Resource definition:

// ...
'access callback' => '_example_resource_access',
'access callback file' => array(
  'type' => 'inc',
  'module' => 'example',
  'name' => 'example.resource-access',
),
'access arguments' => array('foo bar'),
'access arguments append' => TRUE,
// ...

Then create a file called example.resource-access.inc with a function like this:

function _example_resource_access($op, $args = array()) {
  if ($op == 'foo bar' && !is_numeric($args[0])) {
    return services_error(t('That is not an integer.'), 406);
  }
  return TRUE;
}

Note, $args[0] will likely come in as a string representing an integer, so using is_numeric() should be accurate, unless you specifically use (int) to cast $args[0] beforehand, then you can run it through is_int() for validation instead.


How do I modify the output of iframes generated by Media oEmbed module?

The HTML is being generated by the YouTube oEmbed API.

If you inspect the themes/media-oembed.tpl.php template & the theme preprocess include themes/media_oembed.theme.inc, you can see that  media_oembed_get_data() looks up the plugin which pulls the data from the API. In the returned data, the html element is used to fill the $content variable in the template.

The module provides a few different means to hook into retrieval/process/display of the data:

hook_media_oembed_request_alter($parameters, $plugin, $url) can be evoked to alter data before plugin retrieval.
hook_media_oembed_response_alter($embed) can be evoked to alter data after plugin retrieval.
hook_preprocess_media_oembed(&$variables) can be evoked before processing the template for display.

Whatever means you use, it looks like you'll need to manipulate the HTML string directly to add the title element to your output.


Simple answer - don't :)

You shouldn't change anything in the core files, it'll just make things difficult when you try to update.

Drupal's way of extending functionality is through Modules; it's easy to write your own.

When a module is enabled, all the functions defined in the 'MODULENAME.module' file are available during the page build. So if you define a function

function MYMODULE_say_hello() {
  return 'Hi!';
}

That will be available for use in code in the same module, other modules and themes.

As Drupal doesn't currently use namespaces, it's important to prefix your 'global' function names with the name of the module. This just helps to make sure you avoid collisions with other functions of the same name (imagine another module also wanted to say_hello()), which would otherwise result in a fatal error.

There's also a convention in Drupal programming to prefix 'private' function names (those that should only be used internally by your module), with an underscore, e.g.

function _MYMODULE_say_hello_quietly() {
  return '<hush>Hi</hush>';
}

This doesn't technically stop them from being available to other modules (which is actually a good thing in a lot of cases), but it's a good pattern to fall into for Drupal 6/7 development.

For Drupal 8, thankfully, we'll have a much more OO focused core. But that's a topic for another day...


Save Commerce Order and Customer Profile on validation fail

You can can implement hook_form_alter in your custom module and add one more validation handler on top of validation handlers stack, so your is called first.

Inside your validation function follow the way the module Commerce Postal Code Filter is putting the validation, I assume it should be as simple as calling a function. Now if depending on what value it returns you can programmatially update current order status.


How do I attached language specific css in Drupal 8?

You may want to use the "lang" attributes to style the language.

Here is the example:

<!DOCTYPE html>

I live in Italy.

Ciao bella!

Note: For :lang to work in IE8, a DOCTYPE must be declared.


If you updated the modules manually, rather than using the Drupal UI system then you must run example.com/update.php on the URL.  It is likely that one of the modules you updated made changes to the database table system.  If you do not run update.php, then the modules may not have made the necessary table structure changes that match the code.


drupal_goto(request_uri()) replaces my '?', '=' and '&' in url

drupal_goto() accepts an $options parameter to be passed on to the url() function. You can pass a query string like this:

$options = array('query' => array('foo' => 'bar'));
drupal_goto('path', $options);

That example will forward on to /path?foo=bar


Lets try this method

on your form

function form_example_form($form, &$form_state) {
  $name = 'myname';
  $value = 'nikhil';
  variable_set($name, $value);
  // Your form elements goes here ...
}

function form_example_form_submit($form, &$form_state) {
  $name = 'myname';
  $myname = variable_get($name, $default = NULL);
  echo $myname; // will print nikhil
  variable_del($name);

}

As i dont know any Form Unload event i will do

drupal_add_js("jQuery(document).unload(function() {
//make an AJAX call to clear the value });", 'inline');

in javascript

Good luck.


invoking a block and attaching it to a specific html element

You can achieve this by creating a custom module which prints block content as shown below:

<?php
function mymodule_menu(){
    $items = array();

    $items['ajax/replace/block'] = array(
        'title' => t('Ajax Block'),
        'page callback' => 'ajax_callback',
        'access callback' => true,
        'type' => MENU_NORMAL_ITEM
    );

    return $items;
}

function ajax_callback(){
    $block2 = module_invoke("block", "block_view", 1);
    print $block2["content"];
}

Then add following jQuery line in your page to replace the target element with block content:

jQuery("#target-selector").load("/ajax/replace/block");


Clean way to programmatically add attributes to a view field entity label link

Generate the scaffolding of a Views field plugin with Drupal Console

drupal generate:plugin:views:field

and put the link in the render() method generated by the command above:

  public function render(ResultRow $values) {
    if ($entity = $values->_entity) {
      return [
        '#type' => 'link',
        '#title' => $entity->label(),
        '#url' => $entity->toUrl(),
        '#attributes' => [
          'class' => ['foo'],
        ],
      ];
    }
  }

After clearing the cache you'll find the new field plugin when adding a field to the FIELDS list.


Mathematical operations and Twig variables

Yes, it is legal to do mathematical operations in Twig (and in PHP as well). The issue you have is you are trying to calculate render arrays, which doesn't work, no matter which programming language you use. You need to do this on the field values. For example the first value you are looking for:

in PHP:

$value = $node->field_my_customfield->value;

or in Twig:

{% set value = node.field_my_customfield.value %}

This code should work then in Twig:

{% set percentVariable = node.field_my_customfield.value * 100 / node.field_my_second_customfield.value %}


You should have something like

//already loaded
$node = $row->_entity;

Best way to get properties easily is probably to inspect variables with xdebug

If it is some king of header/footer, you can get the rendered array this way :

$view = \Drupal\views\Views::getView('Your view');
$view->execute();
/* @var $area \Drupal\views\Plugin\views\area\Text */
$area = reset($view->header); // $view->header['area'] or something else
$rendered = $area->render(); // rendered array

Ok, then :

$view = \Drupal\views\Views::getView('YOUR VIEW');
$view->execute('YOUR DISPLAY ID OR DEFAULT');
$nothing = $view->getHandler('YOUR DISPLAY ID OR DEFAULT','field', 'nothing');
$text = $nothing['alter']['text'];


How can I pass a long javascript string to PHP hook_menu in Drupal?

I would suggest that you consider some pretty substantial changes to how you're doing things.

I would recommend using an AJAX request, probably with POST rather than GET,  and don't try to do the redirect.   Just update the interface with a "success" message for the user.


Rules has its own set of debugging options. Using Drupal 7? Try /admin/config/workflow/rules/settings and then check your recent log messages at /admin/reports/dblog. As a last resort, it might help to print some manual code just so you know that the rule is being triggered.

More info on debugging Rules: https://drupal.org/node/1593278


How do I use the Video module with Colorbox?

I dont know to use video module but can open a video in colorbox easily with  Video Embed Field. Just create a content type with field as Video Embed Field and in the manage display tab Select the format as 'Preview with Colorbox'.


How to modify a cck field of Node A when Node B (referenced from Node A) is modified

If you are careful you can use hook_node for this. You can check when node type property is saved, and load alter and save the task.

Make sure you put guards in place  otherwise it is easy to end up with recursion.


How to implement some super admin feature to facilitate password retrieval for existing users?

You can't. Drupal passwords are hashed, not encrypted, the key difference being hashes are one-way.

With Drupal 6's non-salted MD5 hashes, a rainbow table might get you there, but with D7's salted SHA512 hashes would be much tougher. The time spent trying to do this would be better spent trying to find an alternative to your need of listing all user/pass.


Where to find all possible keys for BaseFieldDefinition -> setSettings()

The settings are specific to each field type, and each type can provide both storage and field settings (storage settings apply to the field as a whole, per type of entity it's used in, and field settings are the per-bundle settings).

For example, the entity_reference type, backed by the EntityReferenceItem class, provides a target_type storage setting, and several field settings (including handler).

You can use the API to get the default settings, which equate to the available settings that you're looking for, like this:

$field_type_manager = \Drupal::service('plugin.manager.field.field_type');
$storage_settings = $field_type_manager->getDefaultStorageSettings('entity_reference');
$field_settings = $field_type_manager->getDefaultFieldSettings('entity_reference');

That gets you something like this:

If you need to inspect the code to find out what's going on, you can find the class responsible for a particular field type with the same service:

$class = $field_type_manager->getDefinition('entity_reference')['class'];


I can see a couple of ways ahead.

Instead of creating a content type (a Node) just for the header, why not use the taxonomy term (an Entity) itself? Terms are fieldable, so you can add your additional content there, including image, other terms, &c. Then you can grab the term fields using the *replacement patterns from the "first row". You may need to create a Relationship to the term.
If you really want another Node I think you could use the Views Field View module. This way you can create a second View on your "Views Header" type, returning only one result, and pass the term ID from the first View's header to your second View.

Note: Using Views Field View in this manner follows a pattern known as a representative view. IE: A View on a node that is representative of all other nodes using this term. Views 3 does actually support representative views natively though it has some limitations and is generally more difficult to use. I talk about it more over here.


How do I increase the number of characters accepted by MySQL?

Use field type as  Text (formatted, long) or Text (formatted, long, with summary)


Add large number of images to drupal site

I spent some time in understanding how Drupal 6 retrieves images to show on front-end. Since drupal is heavily database intensive, all the files and images are retrieved from the database itself.

If you are using CCK in your site, you must have created image fields for some content types. Now if you open the database and check the table for respective content type, you will find that there are three columns created for each image cck field namely field_name_fid,field_name_list,field_name_data .

The field "field_name_fid" is the key field that maps images to this content type. The fid is the key that is matched to the fid of the table "files". If you open this table, you will find that the primary key of this table i.e fid is used to map images throughout Drupal content.

Here comes the solution

Upload an image from the frontend to test where is your file saved
physically in you drupal directory. For every image uploaded to any
node from front-end there will be an entry in the files table with
its filename, filepath, filemime, file size, status and timestamp.
The fields that you should take care about in the files table are filename, uid, filepath, filemime, and status.
All you have to do is, Place all your files in that physical location.
Run SQL queries to first fill all the fields stated in #2. and match the fid of files table to the field_name_fid of respective content type.

And you are done.


To translate products, you will have to look into Entity translation. Make sure to check the Title module as well which allows to use a field for the product title so that can be translated as well.

For the automation/mass management part, have a look at the the Translation Management Tool* project. The new alpha2 release now integrates into the default Translate tab added by Entity translation and there is also a generic overview for all translatable entity types that allows to mass-translate (by sending a job to translation agencies, machine translation services, export as XLIFF and translate in a desktop tool, ..) entities, which includes products.

Note that the project is in alpha which in this case means that it hasn't been tested on many real sites yet, especially not the new entity translation integration. It has an extensive automated test suite though and is well documented (there is even a introduction video now!).

You can also translate product displays (nodes) using the same tool chain.

*Disclaimer: I am the maintainer of that project.


How to configure a view accessible on user's profile only by that user

If you don't want them to see their own content instead of the user which profile they are currently viewing, you need to add a contextual filter

skip to 8:52 and watch Views Relationships and Contextual Filters

Note: this is for drupal 7, but I imagine the drupal 8 views look the same.


Modifying contextual filters to display user name

It appears that %1 does actually return the title.


an entity_metadata_wrapper for a form_content in form alter hook?

If you've got a complete entity in that form, or some type of structure that the Entity API knows about, because it's been defined in hook_entity_info and/or hook_property_info, you can wrap virtually anything, for example:

$data = array('pears', 'apples', 'oranges');
$wrapper = entity_metadata_wrapper('struct', $data);
dpm($wrapper->value());

But you won't have all the goodies of the wrappers, which are the smart metadata information about the values you're retrieving, you can find how to build your own in the entity module, for example in entity_metadata_site_wrapper:

function entity_metadata_site_wrapper() {
  $site_info = entity_get_property_info('site');
  $info['property info'] = $site_info['properties'];
  return entity_metadata_wrapper('site', FALSE, $info);
}

site is not an entity or field structure at all, but it has been defined by a hook_entity_property_info, in entity_metadata_system_entity_property_info so you can wrap it normally and Entity API will go and fetch the properties you define by using the callbacks you've defined:

function entity_metadata_system_entity_property_info() {
  $info = array();

  // There is no site entity, but still add metadata for global site properties
  // here. That way modules can alter and add further properties at this place.
  // In order to make use of this metadata modules may use the wrapper returned
  // by entity_metadata_site_wrapper().
  $properties = &$info['site']['properties'];
  $properties['name'] = array(
    'label' => t("Name"),
    'description' => t("The name of the site."),
    'getter callback' => 'entity_metadata_system_get_properties',
    'sanitize' => 'check_plain',
  );
  $properties['slogan'] = array(
    'label' => t("Slogan"),
    'description' => t("The slogan of the site."),
    'getter callback' => 'entity_metadata_system_get_properties',
    'sanitize' => 'check_plain',
  );
(...)

So if you've got an entity (saved or not, this only will limit how the data is accessed), you can wrap it normally and access to it, and if you have another type of structure, Entity Metadata Wrappers will still know how to deal with this if you or another module defines so.


Internal Server Error - Downloading attachments

Drupal can put .htaccess files in some folders. It is likely that something in your Apache setup is different and the .htaccess files are no longer valid on your new server.

Removing the .htaccess file from the sub folder could leave you open to hacks, so it may be worth looking to see what it was trying to do and make sure that you are secure.


How to Filter Node Reference Field Values Using Multiple Views?

According to my understanding and the following answer, I believe you can reuse that same field. It will get cloned and then you can go and modify the field settings. This will affect only that field instance, specific to the entity/bundle (node/content-type).

Hope this helps!

Difference between Field and Field Instance?


D6 i18n slow due to huge locales_source table. How can I speed things up?

Yes, 1 million is an extremely high amount. That's not normal.

The amount of nodes should have nothing to do with that table, because content translations happens by creating separate nodes for each language that are linked together.

What is added to that table are all strings which are passed through t(), and everything that is registered through the various i18n modules (menus, terms, ...).

t() must not be used for user generated content but this is often done and I suspect that might be responsible for your amount of rows in that table. The problem with something like t($term->name) is that the identifier is the term name. If you change your original term name, then your translations are lost and the source entry will stay there forever. See below on how to identify problems here.

The interesting column to check where something is coming from is the location, there are 3 different possible types of values in there:

When imported from a .po file (e.g. official translations from localize.drupal.org), the location is filename:line. These are most likely ok and should be much much less than 1 million.
Translations managed by i18n_string have some sort of context/identifier in there, that looks like this: taxonomy:term:1:name. That allows to look up a translation based on a unique identifier of something that won't change. There could be many of these, if you have many taxonomy terms/huge menus but again, not 1 million (except you have 1 million or close terms). You can also identify them by the text group, case 1 and 3 is both textgroup default, while this has a textgroup for each source type (taxonomy, menus, ...).
Every string passed to t() that is not yet in that table is automatically added. In that case, the location is the URL of the page where this string first occured. Those will probably be the most interesting ones for you.

What you need to find out is which pages are adding these dynamic translations and then track down the exact module/call and fix it. There two ways to start. First, look at the most recent additions to that table to see what URL's you have in there (last page on the translate overview, or you can look directly in the database). The second option is group by location and then sort by count(), which might forever on a table of that size. But it's likely that a large amount of sources have been added on the same page. Once you know the page, it's time to do some profiling there and track down who exactly is calling t() often.

Two contrib module examples that I recently identified while doing a performance review on a site:

The site had two hierarchy/relation select boxes using hierarchical select, which currently falls back to t($term->name) if i18n_taxonomy is not installed. That was a free tagging vocabulary with 10k terms and this resulted in 40k calls to t(), which obviously also makes it extremely slow. This issue is still there, I need to find the time to provide a patch.
The other case was the print module, which "translated" the node title on the print page.  I think this was recently fixed, but the already added sources will stay in that table.

Once you identified the problem, you need to fix it and then remove the existing strings from that table, e.g with a like 'taxonomy/term/edit/%' condition for the term edit pages. Just removing the strings can be useful to quickly check how it affects the site load time but they will get re-added as soon as the problematic code is executed again.

For the record, the site that I looked into had "only" 40k entries in that table but even that resulted in cache entry of the short translations of 10MB (in PHP, not serialized).


It's possible to create constants or similar and use them inside a node description or title in Drupal 7

I'm not sure I fully understand your need. But I would try to set a token called current_software_version as 1.1.0. Node titles and descriptions support the use of Tokens.

Tokens may also be supported within links, when using contributed modules or the redirect module I think.

You typically make custom tokens within a custom module you create. If you want an easier way to make the token value and name, I would look at the Variable module to build a UI and Admin Edit page for your current_software_version value. The Variable module will provide a token of the value for use throughout the site for you.


How to add addition settings in node edit page on rightside bar

The key is to implement hook_form_node_form_alter function to add settings to node edit page. I did this by applying patch specified in https://www.drupal.org/project/redirect/issues/2702353.

I specified a wrong module in my question (There were confusion, because both the modules showing same text), actual module that was showing settings in admin pane was redirect module not url_redirect.

I keep this answer here that may help someone who come across the same question I had.


Dealing with such a limited number of nodes, my first reaction would be to clone the content type, say 'basic_extra', and add the field to the clone. Just make sure to change the scope of any views including 'basic' to include both. It would eliminate a lot of work for only one node.


Argument 1 passed to EntityViewBuilder must implement interface, null given

Try this patch

diff --git a/src/Plugin/Field/FieldType/FieldCollection.php b/src/Plugin/Field/FieldType/FieldCollection.php
index 8721220..c5335be 100644
--- a/src/Plugin/Field/FieldType/FieldCollection.php
+++ b/src/Plugin/Field/FieldType/FieldCollection.php
@@ -183,19 +183,15 @@ class FieldCollection extends EntityReferenceItem {
   public function preSave() {

     if ($field_collection_item = $this->getFieldCollectionItem()) {
-      // TODO: Handle node cloning
-      /*
-      if (!empty($host_entity->is_new) && empty($entity->is_new)) {
+      $host = $this->getEntity();
+
+      // Handle node cloning
+      if($host->isNew() && !$field_collection_item->isNew()) {
         // If the host entity is new but we have a field_collection that is not
         // new, it means that its host is being cloned. Thus we need to clone
         // the field collection entity as well.
-        $new_entity = clone $entity;
-        $new_entity->target_id = NULL;
-        $new_entity->revision_id = NULL;
-        $new_entity->is_new = TRUE;
-        $entity = $new_entity;
+        $field_collection_item = $field_collection_item->createDuplicate();
       }
-      */

       // TODO: Handle deleted items
       /*
@@ -231,11 +227,10 @@ class FieldCollection extends EntityReferenceItem {
       }
       */

-      $this->newHostRevision = $this->getEntity()->isNewRevision();
+      $this->newHostRevision = $host->isNewRevision();

       // If the host entity is saved as new revision, do the same for the item.
       if ($this->newHostRevision) {
-        $host = $this->getEntity();

         $field_collection_item->setNewRevision();

diff --git a/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php b/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
index 4d6ae09..800383f 100644
--- a/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
+++ b/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
@@ -104,9 +104,8 @@ class FieldCollectionEmbedWidget extends WidgetBase {
   protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
     // We don't want to render empty items on field collection fields
     // unless a) the field collection is empty ; b) the form is rebuilding,
-    // which means that the user clicked on "Add another item"; or
-    // c) we are creating a new entity.
-    if ((count($items) > 0) && !$form_state->isRebuilding() && !$items->getEntity()->isNew()) {
+    // which means that the user clicked on "Add another item"
+    if ((count($items) > 0) && !$form_state->isRebuilding()) {
       $field_name = $this->fieldDefinition->getName();
       $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
       $parents = $form['#parents'];

mentioned here.


Taxonomy not working with the ECK module

Someone answer my question on Drupal.org forums.

  Taxonomy only works with nodes. It's been hard-coded that way.

https://www.drupal.org/node/2339147#comment-9151769


Imported blogs not showing up under proper tab

Well, that query list above was the key. So I just threw it into a module cron. When feeds are imported on each cron run, this query runs and corrects the null value in the table.

function hook_cron() {
      db_query("update content_field_group_sticky set field_group_sticky_value='Not Sticky' where field_group_sticky_value is null");
}


You don't post the code performing the actual AJAX request, so I have to assume it's directly calling an URL returning just the rendered version of the textfield wrapper with id "panorama_titulo_div".

Since this is sort of side-stepping Drupal's own AJAX functionality (which operates on a per-form basis, initiated by the "#ajax" key being present on certain elements), you'll need to perform some steps manually.

First you need to tell elements in the form that they are about to be removed using Drupal.detachBehaviors($('#panorama_titulo_div').get(0), Drupal.settings, 'unload');

Then you replace the form like you already do.

Finally, you need to re-attach all the JavaScript behaviors since any script operating on the elements in the replaced form won't have any references to the new elements.

Drupal.attachBehaviors($('#panorama_titulo_div').get(0));
This is where Drupal would normally pass the settings received together with other commands returned from an AJAX operation. We don't have that here, and it's not that important since we're not adding/removing elements or otherwise alter the DOM structure and won't introduce any new scrips.
Just to be sure every behaviors works, Drupal calls Drupal.attachBehaviors() again with the entire form as the context argument. You may want to do that too if you notice some things aren't working. It's a safe operation since all behaviors are required to keep track of whether they're already attached or not (often done using jQuery's .once() method.


Drush modifying variable on settings.php

Drush cannot edit the settings.php file.  You could do the above with sed.  Let me know if you want the regex to do it.


The built-in IP blocking (at /admin/config/people/ip-blocking) works just fine, but if you're looking for some slightly more advanced functionality, like blocking ranges of IPs, I've used IP Ranges with a great deal of success:

  IP Ranges is a module that let's you completely ban both single IP-addresses as well as
  full ranges from your site. The ban is triggered already at the early bootstrap phase, so you
  can get rid of unwanted visitors as early as possible without wasting server resources.

  You can also define whitelists that override blacklists, both single and ranged.
  The UI is similar to core ip-ban, so you will feel like home immediately.


If you have nothing but that, yes, Drupal core migrate and migrate_drupal_ui module will easily do this.


PDOException: SQLSTATE[42000]: Syntax error or access violation

Sounds like a case of InnoDB File Format issues.
SUGGESTION #1
If you are not using innodb_file_per_table, you may need to export all the data with mysqldump, delete ibdata and ib_logilfe0 and ib_logilfe0. Then, reimport that data. I wrote a detailed step-by-step process for this 2 years ago.
SUGGESTION #2
Increase the size of your InnoDB Log Files. Each file (ib_logfile0,ib_logfile1) needs to be more than 10 times as big as the biggest BLOB in your dataset:
Here are several links discussing this scenario

https://serverfault.com/q/293406/69271
https://serverfault.com/a/3979/69271
http://www.mysqlperformanceblog.com/2008/11/21/how-to-calculate-a-good-innodb-log-file-size/
http://bugs.mysql.com/bug.php?id=39168

MySQL's maximum size of innodb_log_file_size for a log group of of 2 files is 2047M. Should you ever need InnoDB Log Files that can exceed the 4GB combined barrier, you must upgrade to Percona Server.
I also wrote a detailed step-by-step process for resizing InnoDB Log Files.
SUGGESTION #3 (OPTIONAL)
You may want to switch the innodb_file_format to Barracuda. Bill Karwin's answer in the DBA StackExchange and links thereof explains why.


You can write the function in any php file that gets loaded.  PHP is not sequential in loading/processing files, it will load them first then process.


The first thing that pops to mind is to create a custom module, with a menu callback to obfuscate the real url. This is the same way the drupal private filesystem (private://) handles this.

Create a menu entry in your custom module's hook_menu() to obfuscate the real url and perform access checks.

function my_module_menu() {
  $items['my-module/download'] = array(
    'title' => 'File download',
    'page callback' => 'my_module_page_callback',
    'access callback' => TRUE, // Let the page callback handle the checks.
    'type' => MENU_CALLBACK,
  );
}

Have the page callback transfer the file and check access. Based on file_download().

function my_module_page_callback() {
  $args = func_get_args(); // Get the path elements after `my-module/download`
  $target = implode('/', $args); // Join them into a string.
  $uri = 'http://some-other-server.com/files/' . $target;

  if (function_to_check_if_file_exists($uri)) { // Define this function yourself.
    $headers = array('Content-Type' => 'file mime-type'); // Set the correct mime-type for the file here.

    if (function_to_check_access()) { // Define this function yourself.
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

Accessing an url like example.com/my-module/download/documents/1.pdf should now serve a file from http://some-other-server.com/files/documents/1.pdf.

In order to register the files you will have to construct a file object, set the uri to my-module/download/[remote-path] and save the file to the file_managed table. Then attach the file to a node. There might be better ways for this, but this is what I can think of now.

$f = (object) array(
  'uid'         => 1,
  'filename'    => '',
  'uri'         => 'my-module/download/[remote-path]',
  'filemime'    => '',
  'filesize'    => 12345,
  'status'      => 1,
);
file_save($f);

$node = node_load(1);
$node->field_file[LANGUAGE_NONE][0] = (array)$f; // Add a file field on a content type and use the name here.
node_save($node);


Set the reply address for the contact form to user's mail address

Isn't there a way to set the reply addresses to the ones of registered users and why isn't it done by default?

When authenticated users send a message using the system contact form, the email address assigned to the sent message is the one set for their user account; I just tested it on my Drupal 7 test site, and I can confirm it works that way.

The issue you are seeing is probably caused by the fact you are relaying the emails through Gmail.
If you need to add any header to the email sent from Drupal to resolve this problem, then you can implement hook_mail_alter() in a custom module.


Problems in recovering the fields with php

In node.tpl.php, the title is available as $title.

http://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

In the case of full-page view of nodes, the title may be printed via page.tpl.php, so you may also need to modify that template to get the desired behavior.

http://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/7


Installing Bootstrap theme using Composer

That is because every Drupal package is at drupal/ - twbs is not in the Drupal packagist. You have to add that to composer to get that to work as Clive said.

It is not in the composer.json file out of the box.

You need to add that, and then do:

composer remove twbs/bootstrap because this is NOT a Drupal ready theme.

After adding the repository to composer.json, then you can do:

composer require drupal/bootstrap

Also, not every module or theme has a composer.json file yet. Bootstrap for Drupal does, and thats where you can determine what the package name is if you are unsure.

http://cgit.drupalcode.org/bootstrap/tree/composer.json

I believe modules/themes have to provide this file in order to work with composer (including the repository addition in Clives answer).

Here is one of my projects composer.json, for example. Note the addition of the repositories and Drupal packages URL.

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/search_api_solr": "1.0.0-beta1",
        "drupal/search_api": "^1.0@beta"
    },
    "replace": {
        "drupal/core": "~8.2"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url":  "https://packages.drupal.org/8"
        }
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "modules/contrib/{$name}": ["type:drupal-module"],
            "themes/contrib/{$name}": ["type:drupal-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    }
}

The lack of the packages repository in composer.json is a small, easily missed and often overlooked thing. Hopefully it will be added in a future release.


Some links are still visible after logging out in drupal8

I would suggest, you check the permission at two places

(1) Views permission, which you can find at views UI, under page setting, so from there you can apply the Role restriction.

(2) Permission of Entire that Navigation block under blocks layout, Which allows the display of entire block.


Bots still register on website even though CAPTCHA is activated

To specifically block bogus registrations, I've found the project MotherMayI to be a great help.

  Mother May I provides a simple to use extra hurdle to reduce the bother of spamming account requests. It's primarily useful to sites with a limited target audience (at least for authenticated accounts) where valid users have some side information about the group. The site administrator can define a site-specific "secret word." Anyone requesting an account must enter the secret word before even a temporary account is created.

As the quoted text says, it is best suited for sites with a limited target audience.  However, the module lets you give a "hint" that is supposed to make it simple for humans to find the secret word, and I've found that even ridiculous easy task where where the hint is "Please type in cartoon character Fred Flint's last name" (and the secret is "Flint") works great.

MotherMayI allow you to have a long "hint" text and use a RegExp for the answer, but only allow one "secret" word.

There is an alternative in the CAPTCHA family called Captcha Riddler that works similarly.   It allow multiple riddles to be defined to separate humans from robots, but only allow short texts for riddles and have no RegExp function.

Since you define the "secret" word (MotherMayI), or "riddle" (Captcha Riddler), these methods are more immune to the "training" feature of Xrumer and other pests.  This means the 'bot need to be trained specifically for your site.  Unless your site is really huge, you'll be able to fly under the radar for a long time. And it is trivial to replace the secret word or riddle if the robot is trained to recognize your site.

Are You A Human playthru (also mentioned by Mołot) is in the same genre as the previous two, but IMHO slightly more cumbersome for humans to "solve".


Organic group module- teacher student layout dashbord

Thats possible out of the box.. see http://nodeone.se/en/permissions-and-roles-for-groups


How to enable inline editing on Views in Drupal 8?

Quick Edit of nodes in Views works. You can see this on the frontpage, which is a View.

However this works only for Views which show content.

If you have a View which shows content and want to choose the fields and customize the layout, you can create a custom viewmode, configure the fields there and put the layout in the twig files of the view mode.

Of course this does not provide all features of a View which shows fields and the module Editablefields. For this you would have to wait until this module is ported to D8.


How to create user profile theme hook suggestion for custom template?

It's hard to tell without seeing your code but off the top of my head your preprocess function should look something like this:

function MYTHEME_preprocess_user_profile(&$vars) {
  if ($vars['view_mode'] == 'mini_teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__mini_teaser';
  }
}

Or a more generic solution:

function MYTHEME_preprocess_user_profile(&$vars) {
  $vars['theme_hook_suggestions'][] = 'user_profile__' . $vars['view_mode'];
}


Drupal 8, include a subtemplate in a form

Most likely you are looking at adding to the "render array" of the page (or form). A render array can refer to a "type" or Render Element, and that type can render into a template.

The scenario of rendering after form submission on the same form can be done within the Form itself by setting the form state to rebuild.

  public function submitForm(array $form, FormStateInterface $form_state) {

    // Set the rebuild state to TRUE to persist $form_state when the form is reloaded.
    $form_state->setRebuild();
    $form_state->set('display_extra', TRUE);
  }

  public function buildForm(array $form, FormStateInterface $form_State) {

    // Conditionally display something from form state.
    if ($form_state->has('display_extra') && $form_state->get('display_extra')) {
      // Structure the render array here including setting up a custom RenderElement ('#type'), which has a custom template defined in hook_theme().
      $form['display_something'] = [];

    }

    // Rest of form...

    return $form;
  }


EntityQuery with a condition on an array

try to use an array instead of the value of $paragraph_type.

that would be like this :

->condition('settings.handler_settings.target_bundles', [$paragraph_type], 'IN')


views filter: problems with the query object

Your add_where syntax doesn't follow the documentation given in Views code. Here is a paste :

/**
   * Add a simple WHERE clause to the query. The caller is responsible for
   * ensuring that all fields are fully qualified (TABLE.FIELD) and that
   * the table already exists in the query.
   *
   * @param $group
   *   The WHERE group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param $field
   *   The name of the field to check.
   * @param $value
   *   The value to test the field against. In most cases, this is a scalar. For more
   *   complex options, it is an array. The meaning of each element in the array is
   *   dependent on the $operator.
   * @param $operator
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
   *   = otherwise. If $field is a string you have to use 'formula' here.
   *
   * @see QueryConditionInterface::condition()
   */
  function add_where($group, $field, $value = NULL, $operator = NULL) {

So basically you cannot inject a complete query like you tried to, but you must use the different methods provided by the objects to carefully construct the different parts.

The less clear part is the group argument : it refers to the groups defined in the filters part of Views UI, the one created when you use Create new groupin the filters contextual menu.


If I were you (and with my poor level), I would proceed in 2 steps:

Get all the users with the role that interests you. Maybe inspire yourself for the query here: Get all users with specific roles using EntityFieldQuery
Browse the query result by loading each user and check if $user->roles has another role than the one you are looking for.
Push the final results in another array.

I don't know if it is a good way to proceed or if there is another way to achieve this, but I think it could do the trick.


View is removing iframe from custom text

This is not the expected behavior of drupal views, Drupal Views usually not doing this.
I have done this before, and global text with iframe is working with no issue.
Maybe you have another issue like some javascript issue to prevent the load iframe form another site, see the console of your webpage maybe you got some error.

You can debug also by putting that iframe into any page Textarea field where you already use the HTML content of your website.


How do I copy the values of one field collection field to another content type with the same field collection?

I have used the "set data value" action in Rules to make one field collection equal another field collection. It just dumps the whole field collection in at once, so you don't have to loop through each item one at a time.


How can I send an HTML email from an Ajax callback?

I recommend the Easy Email module. It combines with Swiftmailer and Mailsystem, allowing for creating and sending HTML emails, using templates you can build with a ckeditor right in the interface. Then you can send mails from your module using the standard Drupal mail service, and it will take care of turning it into an HTML email. The video on the top page of the module page is very informative and explains it all. It's by far the best HTML email solution I've found in Drupal over the years.


Custom module administration page template not working

It is a well known issue of the hook_theme() function.

For successfully loading the template file, you have to follow the naming convention to rename the template name, which must be same as the theme key, with converting _ to -.

/**
 * Implements hook_theme()
 */
function module_custom_theme($existing, $type, $theme, $path) {

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    return array(
        'user_availability' => array(
            'variables' => array('users', NULL),
            'template' => 'user-availability',
            'path' => $template_path
        )
    );

}


Try this
//the values for autcomplete

function search_city_autocomplete($text = NULL) {
$results = array();
  $results['city1'] = 'thefirstcity';
  $results['city2'] = 'thesecondcity';
  print drupal_json_encode($results);
exit();
}


Average value of integer field using views

You could use something like Computed Field to display the average, but I would suggest going to the Voting API and something like the Fivestar module which will handle the voting and the averaging for you.


How can I reference a field from a product display when calculating a price?

I generally recommend any information required for the pricing / fulfillment of a product to be stored on the product itself. I can see where you might need to do so based on information in the display, though (e.g. discounting products in a particular category).

In that case, you can't traverse from the line item / product to its display mode via the standard Rules data selector. Instead you need to use the appropriate action to load the node that references the product in question. Then you'll need to pass the line item and that node to a Rules component where you can use additional conditions to bring field data from the display node into scope (e.g. "Entity has field") and use the line item unit price manipulation actions on the line item to affect the pricing.


Sort the view by created desc.

Then limit the view to only show 1 row.

The remaining item will be the last form submitted.


How do I alter the page title h1 tag from a module?

The page title is now a block, so you can override its template file.


What would cause a duplicate session key?

Check your sites/default/settings.php file, if you have $conf[https] = TRUE; then removing it will fix the error.

Removing it also won't affect any security issues as long as your server/domain is configured properly. You can also check the Enabling HTTP Secure page from Drupal.


Drupal 7 - Trying to get term reference node, from html.tpl

Ok, so you'll want to test for a node, then check for the field and then print it to your template. This should work for you:

<?php

if(arg(0)=='node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));
        if(isset($node->field_test['und'][0]['value'])) {
            print $node->field_test['und'][0]['value'];
        }
}

?>

That's code for Drupal 7


How can I upload a CSV file and expose it in a "views table" for Drupal 7?

As far as I know the short answer here is you can't. Views is pretty much a query building machine.

The next best thing would be to create a script and/or use some views plugin to mass import your nodes from the CSV document and then present them to a view.

And I am proposing a scripted solution in case your nodes are more than 25. Else you might as well do it by hand :)


There are jQuery Mobile module and Mobile jQuery Theme available. Looks like exactly what you wanted.

  The Mobile jQuery Theme is a powerful theme built on the jQuery Mobile platform. The theme adapts some of Drupal's base output to work with the highly themable designs built into the framework.

  This is an enhancement module for the Mobile jQuery Theme. You can also hook into the module with you own theme if desired.

So you have the module to provide functionality you need, and theme you can use by creating subtheme, or as a reference.


Help with the sub-groups for Organic groups module

Read this post, it will help you to figure out how to use the sub-og module

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


Redirect users to different page after a login failure in d7

Please try with the correct form_id for user login.

i.e: if ($form_id == 'user_login') {

The form_id can be found in the HTML source hidden element

<input type="hidden" name="form_id" id="edit-user-login" value="user_login">


Creating a view that uses fields from two content types

Best way is to use entity reference

Below is the youtube link which will provide you step by step explanation of using entity reference module with views.
https://www.youtube.com/watch?v=4Pdii7aFIvc


How to let a role be able to administer part of permissions?

I use Permissions Lock to achieve this.  You can give your role A the 'administer permissions' ability and then lock off all of the ones that you do not wish them to have access to.  It's a bit backwards in that you have to go through and tick all of the checkboxes except the ones you want to provide, but it works.

Also you need to check it each time you install new modules or go through an update that provides new permissions as the new permissions default to 'available'.


Using IN queries or joining to a temporary table inside views for data managers to use with VBO for one-off updates

You could try Feeds as well .... but ...

Use either a CSV file or one of its other Migrate Sources, for instance it can use another database table as your source of change-data. But I recommend the Migrate module.

Your CSV can hold the primary key and whatever fields you need to update. You could use the new hash() functionality in Migrate 2.6 to check for changes in your data so that content is either Updated or Inserted as needed.


How to get the "field" value of config entity, with bundles, that is defined in a bundle while creating content

While creating content, HOOK_entity_presave() is called for the content entity and you can access only content fields. One of these content entity fields is a reference field to the bundle config entity, usually named bundle. Use this field to get the config entity via the magic property entity and get the config field value via the method you have defined in WebsiteTypeInterface:

$url = $entity->bundle->entity->getServiceUrl();

A more generic way when you don't know the bundle field name or the code should work for all entity types:

$bundle_field_name = $entity->getEntityType()->getKey('bundle');
if (!empty($bundle_field_name)) {
  $bundle_config = $entity->get($bundle_field_name)->entity;
  if ($bundle_config instanceof \Drupal\mymodule\Entity\WebsiteTypeInterface) {
    $url = $bundle_config->getServiceUrl();
  }
}


Check out the Restrict IP module.

This module allows administrators to restrict access to the site to an administrator defined set of IP addresses. Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page with the message "Your address is not in the list of allowed IP addresses". No blocks will be rendered, and no JavaScript will be added to the page. This will happen for any and all pages these users try to access. The module also has various configuration options to whitelist or blacklist pages, bypass IP checking by role, and alter the output when the user is blocked.


Notice: Trying to get property of non-object in eval() (line 3 of /home/sltruweb/public_html/modules/php/php.module(74) : eval()'d code).

If we break this down, we get:

Severity: Notice. From PHP's perspective, not a big deal.
Actual problem: "Trying to get property of non-object". You have something like this: $foo->bar, where $foo is not an object, and as such, ->bar does not apply
line 3 of /home/sltruweb/public_html/modules/php/php.module, where the problem is happening.
eval()'d code: Your actual problem.

PHP Supports something called eval(). Eval() has some, but very few legitimate uses, and in most cases should be spelled "Evil", instead. Unfortunately, it's used liberally in the Drupal world because there's a module in Core that makes it easy to use. To support my argument, "Don't use it", I quote from PHP's own documentation:

  The eval() language construct is very dangerous

Now somewhere in your site, you have an eval(). And that's one of the many issues with it, based upon your error message, I can't tell you any thing more meaningful than that. To track this down better, you need to update your question with a stacktrace. This however, is not necessarily easy to produce, and you may need the help of a skilled developer.


Drupal Commerce Shopping Cart Form Alter

Simple mistake, you don't change $form but only $item if you did

foreach($form['edit_delete'] as &$item) {

or

foreach($form['edit_delete'] as $key => $item) {
  ...
  $form['edit_delete'][$key] = $item;
}

it should work.


In views Change the Formatter  of the field from Generic file
to URL to file.
Go to REWRITE RESULTS and check 'Output this field as link' and
use replacement pattern of the file field.
check Use absolute path to get absolute path link of the file

That's it you will get complete path of the file instead of file name at output.


Problem with node revisions and taxonomy terms

I figured it out.  unset() is the answer.  Here is my code:

        $loop = 0;

    $termarr = $form_state['values']['catagories'];
    // drupal_set_message('Termarray '. print_r($termarr,1) .'');
    foreach ($termarr as $term) {
      if ($term > 0) {
        $node->field_catagories['und'][$loop] = array('tid' => $term);
      } else {
        unset($node->field_catagories['und'][$loop]);
      }
      $loop++;
    }

This took way longer than it should have.  I wish Drupal had better documentation although trial and error for days does have some benefits... :-(


See editablefields module.

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).


Content listing to show custom fields of associated terms instead of title

In Views under Contextual Filters select your vocabulary field. Now you can find your required image field under add button in fields. Add that field to your view.


It looks like a cache problem. I will suggest to do this, as usual backup is always a good idea:

See if this happens also if you are login. You might have your node permissions corrupted. If you rebuild and have a lot of node, it might take a little while to do this.
Turning cache off for page and blocks.
is your content generated by a view? if so check the permission


Show English tabs regardless of current site language

In the end I just used the workaround: removed the translations for the strings in the tabs. There weren't too many.


How to check in Rules the value of a field collection field contained in a user account?

I'm about sure that the machine name of your field collection field is site:current-user:field-price-override (your question doesn't state that explicitly), for which you do not have a "Entity has field" Rules Condition yet (you have site:current-user:field-price-override:0 instead).

Try adding a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field. Not sure why you have/need that site:current-user:field-price-override:0 Rules Condition, but you might not need that anymore.

You can then add a Rules Action which is simply a Rules "loop", and which iterates over each of the field collection items. And you will be able to use any of the typical tokens (in the replacement patterns).

For way more details about this, refer to "How to iterate over all field collection items in an eMail body using Rules?" (which also includes a rule in export format you may want to experiment with, if you only adapt some machine names of the used fields).


Even if it's kind of hacky you could do a hook_form_alter, set a submit function before the default one and look at the form input. Then wrap it with "" if it's not there already.

So what you need is

a custom module
hook_form_alter
Register a '#submit' function
Alter the value $form_state['values']


How do I add an access condition to a menu item?

What you need to do is to add your callback via hook_menu_alter(), and then inside your callback you simply do your logic then return the data via the original callback.

To be certain that you don't overwrite any other hook_menu_alter() changes, you should pass the previous callback to your callback via the access argument.

This is all theoretical, but the code should go something like this:

MYMODULE_menu_alter(&$items) {
  $items['menu']['access arguments'] = array_merge(array($items['menu']['access callback']), $item['menu']['access arguments']);
  $items['menu']['access callback'] = 'MYMODULE_access_callback';
}

MYMODULE_access_callback() {
  $args = func_get_args();

  // Do Stuff.
  if ($something == FALSE) {
    return FALSE;
  }

  $function = array_shift($args);
  return call_user_func_array($function, $args);
}


Need a Best Video Player For My Video Hosting Site

check that : jw_player.

For thumnbails you can use that : DailyMotion, Youtube.
its very simple to use it.


There are a couple of modules that might help:

Taxonomy Orphanage (specifically the cron interface)

  This module provides interfaces (drush, cron, admin form) for removing orphaned taxonomy term references from entities.

Field reference delete (sandbox only)

  This module removes references to a deleted entity from fields stored in an SQL database. It exists to prevent stale references to non-existent content from causing unexpected problems (for example, when the referencing content is being displayed).


How can I export my translation changes?

With locale module, you have an export tab here : admin/config/regional/translate/export. Or through the menu : Configuration > Regional and language > Export.

On a fresh installation, active the locale module and go to the import tab : admin/config/regional/translate/import. Or through the menu : Configuration > Regional and language > Import.


How to display a form in modal dialog on page load?

What I did, hide the link in the body and from javascript trigger the click event of the link, will show the dialog.


For normal forms you need bind submit event handler to the form, something like below as Baysaa said,

jQuery('#formid').submit(function() {
  console.log('submit handler');
  return false;
});

However For Drupal AJAX forms this wont work, Because Drupal AJAX forms are submitted by Drupal in a different way when the submit button is clicked, So you need to just bind the click event to the submit button to detect the form submission, Something like below,

jQuery('#submit-form').submit(function() {
  console.log('Form is being submitted');
});

Here the restriction is you cant prevent form being submitted, even if you put return false in you custom click handler.


Insert value into field before and after specific string

Sounds like you should be parsing the field with a regex function that matches the content between the script tags. Then you can rebuild your string and update the row.

http://regexr.com/3du5i for an example


Yes, using content entity types for this seems like a good idea.

In regards to entity types vs. bundles, which one is better for you depends on your exact requirement (I only noticed after already writing most of this that you already mentioned and specifically asked about entity types vs. bundles, so might be too much explanation, but too lazy to rewrite now :)).

Entity types

You create separate content entity types. Whether you use inheritance for sharing the base field definitions or for example a trait is up to you. The inheritance only exists in code, the data itself knows no hierarchy, it is stored in separate tables.

But yes, sharing code there is perfectly valid. Drupal 8.4 for example adds a base class for publishable entity types: EditorialContentEntityBase, see https://www.drupal.org/node/2870643.

The advantage of this is that you can build each entity type with exactly the base fields that you need, which results in an optimized storage (1-4 base field tables, depending on whether you need revisions and/or translation support and separate tables for multi-value fields). However, the main drawback is that there is no API, neither views nor entity query that allows you to list different types of animals in a list. If that's a requirement, then this might be a no-go.

Bundles

You create a single animal entity type and different bundles for the different types of animals. This is like the node entity type and bundles. They share the same base fields and storage, additional type-specific fields can be added as configurable fields or maybe also per-bundle base fields (I honestly have no idea how well that actually work - and I'm supposed to be one of the maintainers of the entity system). This is the opposite of the above, it's easy to create lists with different animals but you might end up with a considerable amount of per-field tables if you have a lot of fields on your dogs/cats etc.

In regards to downsides, content entities are pretty heavy, they have a complex structure based on typed data and are therefore slower than plain custom objects. Their storage, while extensible, is also limited in various ways, you can only load full entities and there is no support for bulk update for example (but you can implement some things in a custom storage handler). But you get a ton of features for that, the mentioned views integration, widgets/formatters, cache handling/invalidation, revision and translation support and so on.


Generate a view with parent - child taxonomy terms

I figured the answer. There is a relationship select box that appears on existing fields. I had to add twice the name field, make one of them use the parent relationship and exclude it from display and then use this as a grouping variable for the grid.


How to set root term in Hirerchical select

As I explained in this link ,this is bug in HS module.

finally i found your mistake
in your code , in hs_taxonomy.module
in function hs_taxonomy_hierarchical_select_root_level($params) you don't consider
$params['root_term'] and in every hs this item bypassed by 0 value

<?php
$terms = _hs_taxonomy_hierarchical_select_get_tree($params['vid'], 0, -1, 1);
?>

must be

<?php
$terms = _hs_taxonomy_hierarchical_select_get_tree($params['vid'], $params['root_term'], -1, 1);
?>

if user not set parent in content_taxonomy settings for term reference it passed 0 by default.

please apply this patch to your module.
just notice for this work correctly you want select (not duplicate second level select option)
Save term lineage
in Hierarchical Select configuration in Save lineage part.
i test it ,working like a 'BENZ'


Need help with how custom fields are displayed by article.html.twig file

If I understand correctly:

The node.createdtime in the screenshot comes from the content type setting "Display author and date information" on the content type edit page. Look at /admin/structure/types/manage/article.

If you need a different date shown, you can uncheck that setting to hide Drupal's author and date info display, then ensure your custom fields are displayed on the node instead. Look at /admin/structure/types/manage/article/display.

If the template node--article.html.twig renders content with just {{ content }}, your fields will show once set to display. If your template file is customized, you may need to add {{ content.field_publicationdate }}.

As @Kevin mentioned, use the field format options at /admin/structure/types/manage/article/display to control the output of your date field.

A more technical approach, and if your content is being imported, could be to map your field_publicationdate value to the node created time value. (But that's another question :)


Clear cache after save orders using draggable views in Drupal 7

Sometimes "#submit" functions of HOOK_form_alter are get changes. SO please try adding $form['#after_build']. Your code will be like.

function phponwebsites_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_test_views') {
    $form['#after_build'][] = 'phponwebsites_draggable_custom_afterbuild';
  }
}
function phponwebsites_draggable_custom_afterbuild($form, $form_state) {
  $form['#submit'][] = 'phponwebsites_draggable_custom_submit';
  return $form;
}
function phponwebsites_draggable_custom_submit(&$form, $form_state) {
  print_r('ss');exit;
  drupal_flush_all_caches();
}


Unsetting a field before hook_form_alter

In case this helps anyone - the hidden node reference fields that I have been using were having their lists of selectable nodes generated by views. I ended up using hook_views_query_alter to stop the view query from being run. Here's the code I put into my custom module:

/**
 * Implements hook_views_query_alter().
 *
 * Disables node reference views. This drammatically
 * speeds up performance.
 */
 function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == "my_view") {
    $view->executed = TRUE;
  }
  if ($view->name == "my_view2") {
    $view->executed = TRUE;
  }
 }


How to perform a query using a specific field of a node entity reference

I believe you want something like below. Note that this isn't really a database query at this level but an Entity Query:

$event_nids = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->sort('field_referenced_node.entity.title', ASC)
  ->execute();


How to create a tabbed view in a panel without a menu entry?

You don't need 3 views, just create one view with 3 pages Votes, Activity and Newest. define your fields and filters. In Page Settings -> Menu Option, Use the Menu tab.

Edit: Exmaple

If Page Path for main view is mylist

Add Pages in View with Paths mylist/votes, mylist/activity,
mylist/newest for all the 3 pages respectively
Select Menu Tab and Provide the Menu for Votes, Activity and Newest respectively

Above was the previous reply, here is answer with some graphics.

For the demo of your use case:

I created a taxonomy vocabulary called DSE with 3 terms Vote, Activity and Newest
I created a new content type called Drupal Stack Exchange, with Title, Questions and Tags field, where Tags field is Term Reference to DSE

In Views, I created a Master Display with Just Title field for demonstration, and I gave the Page path as questions like in this picture

For the Menu for Master display I selected Normal menu entry and selected Main Menu as its menu type:

Then I added the new Page for Activity, and in Path I gave questions/activity

In Menu for Activity, I selected Menu Tab and gave a title called Activity

In Filter for Activity I selected DSE Tag and chosed it to be one of Activity Tag like in the picture below. (Note: While adding filter select only this display)

I repeated the same process for Votes and Newest, as you can see Path settings for Newest is also the Menu Tab like:

Save the view and you'll see the New Menu called Questions in Main Menu, and clicking the Menu will give you 3 tabbed menu inside like:

Note: To make tabbed menu it is required the path to be on the same Path like in above case questions/vote for Vote tab, questions/activity for Activity tab.

Finally the Sneak peak of the View page


Is there any other way to create more secure link in a drupal_set_message?

No, there isn't a more secure way, especially when you are not outputting input coming from the user. Still, you should be using t()-placeholders.

Drupal core uses the following code, when outputting an URL.

// system_requirements()
$requirements ['php'] = array(
  'title' => $t('PHP'),
  'value' => $phpversion,
  'description' => $t('The phpinfo() function has been disabled for security reasons. To see your server\'s phpinfo() information, change your PHP settings or contact your server administrator. For more information, Enabling and disabling phpinfo() handbook page.', array('@phpinfo' => 'http://drupal.org/node/243993')),
  'severity' => REQUIREMENT_INFO,
);

  // action_synchronize()
  $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
  $count = count($actions_in_db);
  $orphans = implode(', ', $orphaned);
  watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);

The only difference is that, in the first case, the code is outputting an external URL while, in the other case, the URL is internal to the website.


Rule to check if a node has a translation?

Out of the box: no.

If you are willing to code, check the rules API. It lets you add your own conditions and actions.

If you don't need any of the rules functionality you can of course just implement hook_node_view.


Add CSS file to certain pages only with theme.info file?

I think it only globally, you should do it the the preprocess page instead.