How can I create a node in a PHPUnit Test without having to create the node type in PHPUnit

When you create a node, you need to reference a bundle that already exists. In your case, you are referencing a bundle (expense) that is created from a custom module, but that module is not installed.

If you look at the tests for the Node module, you will notice they always install the Node module. In the test classes that expand the NodeTestBase class, that is done from that class. In other test classes, for example the NodeFieldAccessTest class (a Kernel test), that is done directly by that test class.

In your case, changing the list of modules to install to the following one would solve the issue.

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node', 'paragraphs', 'my_module'];

From the error messages, I take the machine name of the module creating the content type is my_module. If that is not correct, replace my_module with the correct machine name.


Page Categorisation and Multi-level Paths

If it is a node, you need to use Pathauto and also Replacement Patterns, in the Replacement Patterns select the taxonomy term and put it in the url.

But if you need to list set of contents based on the url you need to use Views and add the terms as contextual filters.


how to create separate contextual filters for pages in views

After setting everything the way you want it on the first page, switch to the other display and change those settings, but for each one make sure you have the This page (override) drop-down selected.


What module might make all my links redirect the current window with target="_blank"?

I had the same problem before and it was because of Google analytics module. This link may help you http://drupal.org/node/1091932


Is Paypal payments pro gateway available for Drupal Commerce

In Commerce Paypal's issue queue, there is a patch that is a start on WPP. http://drupal.org/node/1155768


Create user permission with specific role?

Use the role delegation module

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

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

UPDATE:

Simply create two roles Manager and Editor role. When you create this roles, two permissions will appear on the permissions page. Assign Manager role and Editor role. Give the manager the two roles to assign. And also give the user permission to create new users.

And if you login as that user, that user will only be able to create the roles you have assigned to them.

UPDATE 2:

Use the module administer user by role. To stop the manager role from canceling or editing the adminstrator role or any other role you don't want them touching

  This module allows site builders to set up fine-grained permissions
  for allowing users to edit and delete other users — more specific than
  Drupal Core's all-or-nothing 'administer users' permission. It also
  provides and enforces a 'create users' permission.


D7: Create an administration page for my module

First of all hook_mail_alter() only has 1 parameter, no $form_state. Second of all, the system_settings_form() will save the form values into the variables table in the database. To access that value you should use variable_get().

Now, your code should look like this:

// try to change body to something more specific to your module, like custom_email_body
$form['mail_template']['custom_email_body'] = array(
  '#type' => 'textarea',
  '#title'  => t('Email template'),
  '#default_value' => variable_get('custom_email_body', ''),
  '#rows' => 10,
);

then:

function shop_mail_alter(&$message) {
$client_body = variable_get('custom_email_body', '');
if (is_array($message['body'])) {
    $message['body'][] .= $client_body;
  }
}


How do customize settings.php during installation profile

You may find it easier to use a settings.common.php

Often during team projects, we have local settings.php with db credentials etc.. and a settings.common.php with settings common to the install and deployment environments.

You can add settings.common.php with an include / require line in settings.php

require 'settings.common.php'; // same directory, e.g sites/default/settings.common.php

and then write to it as needed during install.


How to determine if the current page is a search results page?

If you're trying to determine from a module then you can check if the page is the search results page via the path arguments using the arg() function.

if (arg(0) == 'search') {
  TRUE
}
else {
  FALSE
}


Display average "Votes: Value" as stars in Views

It should be easy with a simple theme file.
In the views interface, on the bottom right, you should see "Theme: informtion", click that and you will see relevant theme file names.
Using one like "views-view-field--rating.tpl.php" should work.


Prevent password reset urls from being redirected at login

The simplest way would probably be to just test for the path, which you can get access to via arg(). Something like this would do the trick:

function hook_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'login':
      if (_cns_user($account) && !(arg(0) == 'user' && arg(1) == 'reset')) {
        unset($_GET['destination']);
        unset($_REQUEST['destination']);
        drupal_goto('user/'. $account->uid .'/training', NULL, 'steps');
      }
      break;
  }
}


Create a controller and a empty theme page

Controllers must return a response (you will get an error if you don't). Your options are to return a render array, an HtmlResponse, a JsonResponse, or an AjaxResponse.

Edit: Or as Kevin posted below, a Response.

By the sounds of it, you are wanting to return JSON, so JsonResponse is likely what you are looking for.


Understanding the source of a 'Failed to get available update data' errors

If I get your question right, I would suggest the following on a terminal:

drush pm-updatestatus 2>&1 | grep "No release history" -B1

This should give you all the projects (modules and themes) that you are looking for.

Cheers!


How to get taxonomy image and path by tid in Drupal 7?

I'm guessing you're looking for something like:

$term = taxonomy_term_load($tid);
if ($image_items = field_get_items('taxonomy_term', $term, 'field_name')) {
  $uri = $image_items[0]['uri'];
  $external_url = file_create_url($uri);
}

Where field_name is replaced with the name of your image field.


How do you change the default sort in apachesolr?

You can implement hook_apachesolr_query_alter() and add new sort criteria as below

/**
 * Implements hook_apachesolr_query_alter().
 */
function my_module_apachesolr_query_alter($query) {
  $query->addParam('sort', 'ss_date_field asc');
}


Why go through the hassle of defining an entity URI callback?

To allow other modules to override the entity URI and / or provide a default one.

For instance, I have a student entity defined by the student module. The entity URI is student/%student and is defined from the following hook.

/**
 * Implements hook_entity_info().
 */
function student_entity_info() {
  $return = array(
    'student' => array(
      'label' => t('Student'),
      ...
      'uri callback' => 'student_uri',
      ...
    ),
  );
  return $return;
}

/**
 * Entity uri callback: gives modules a chance to specify a path for a student.
 */
function student_uri($student) {
  return array(
    'path' => 'student/' . $student->student_id,
  );
}

Now, let's say I have another module, student_special, which provides a different URI depending on a property in the student object. I can override the URI by implementing hook_entity_info_alter().

/**
 * Implements hook_entity_info_alter().
 */
function student_special_entity_info_alter(&$entity_info) {
  // Add a URI callback to the student entity.
  $entity_info['student']['uri callback'] = 'student_special_uri';
}

/**
 * Entity uri callback: points to a unique URI if the given student is awesome.
 */
function student_special_uri($student) {
  // First look for a return value in the default entity uri callback.
  $default_uri = student_uri($student);

  if ($student->is_awesome) {
    return array(
      'path' => 'awesome-student/' . $student->student_id,
    );
  }
  return $default_uri;
}

We can then use the student URI for a variety of things like creating links or redirecting users to the student entity's view page. For example, if we want to redirect the user to the newly created student after submitting a form.

/**
 * Submit handler for the student create/edit form.
 */
function student_form_submit($form, &$form_state) {

  ...

  // Save the student entity.
  student_save($student);

  // Redirect the user to the student URI.
  $student_uri = entity_uri('student', $student);
  $form_state['redirect'] = $student_uri['path'];
  drupal_set_message(t('Student %title saved.', array('%title' => entity_label('student', $student))));
}

This ensures that we get the correct URI, especially if there are modules that overrides the default URI.

  Does it bring additional custom, cool functionality to our table that we can exploit?

Alas, there are no lucky charms at the end of the rainbow. Like @googletorp mentions, you still need to define a menu callback for the URI to work, otherwise the URI is just a string that does not map to an existing Drupal menu callback.

There are two ways that you can go about mapping custom Entity URIs to menu callback items: via a standard implementation of hook_menu(), or by overriding the hook_menu() method in your controller, in case you're using Entity API with custom admin ui controllers.


Why do OG Vocabulary terms not list content?

I waited a few days on this to see if anyone posted a solution but no luck..

I've never had any luck with og_vocab and instead use a content type as a group type and use that just like taxonomy. This is possible by using entity reference fields that use entity reference views for values instead of a taxonomy field. But the "taxonomy term" ie. Field value must be set before hand as far as I can tell.

If this solution, and I actually like it a lot, sounds like it could work, I can write up a more detailed guide.


How to create content / entity via ajax on a view?

The most basic version would be to add 'use-ajax' to the "Add new" button link pointing at a controller which returns an ajax command replacing the div. See https://www.drupal.org/docs/drupal-apis/ajax-api/basic-concepts#s-trigger-ajax-request-with-a-link.
Modals use also the 'use-ajax' class but need additional 'data-dialog-*' attributes. Then you can load normal HTML content in a dialog box, you don't need an Ajax controller in this case. See https://www.drupal.org/docs/drupal-apis/ajax-api/ajax-dialog-boxes
In a submit handler of the form you have to make a redirect to a URL you have setup to display the updated view together with the form.


Print a list of checked form options in TWIG

Iterate over the form options, returning the # value of each item:

{% for choice in form.filter['#value'] %}

Then Print out the title value of each one of those options:

{{ form.filter[choice]['#title'] }}

All together it looks like this:

{% for choice in form.filter['#value'] %} {# Find each checked option #}
  {{ form.filter[choice]['#title'] }} {# Print the Title #}
{% endfor %}


Is there a Drush command to check the distribution version?

As far as I know, no.

Since commerce_kickstart is not a module, but a profile, the drush commands for getting info about a module (e.g.):

drush pm-info commerce_kickstart
drush pm-list | grep commerce_kickstart

will not work.


Using Panelizer, how can I add a new menu item properly

Cleared the cache and then it worked.
Found this by doing a $modules = module_implements('get_pane_links_alter');


Use Devel for most of the (There is a dev version for Drupal 8) visual testing and seeing output of most of the render arrays (DPM function will retain the array if there is redirect so it will output in those cases). Plus other variables can be output. You can use the old school tail -f drupal_debug.txt by using dd() or just output in Krumo to the screen with dpm(). You can find out more about Devel by visiting the project page.

Also you can run tests using Drupal SimpleTest and find out more about how to implement SimpleTest in the Drupal Examples which does have tests examples for 7 and 8.


How to query Nodes by a referenced Term Value (via EntityFieldQuery)?

EntityFieldQuery can not, as you have noticed JOIN tables, because it may run queries against a backend where JOIN does not make sense.

You will need bridge this gap in code, which is what your own suggestion is doing, it looks fine to me.

However, if you don't intend to run on MongoDB or some such, my personal preferance is would be to ditch EntityFieldQuery in favor of a SQL-query with db_select instead. This mostly because MySQL provides the ACID, while all the "no-sql" db's needs to break atleast one of those.


How to create custom commerce order states?

Two things there:

A. Define your custom order states with one of the Order info hooks.

hook_commerce_order_state_info
hook_commerce_order_status_info

B. Create a commerce_order based VBO view and add an operation to change the order state. It won't be a button on each row, just a checkbox or radio button, but you can batch update that way.

Alternatively, edit the order and set it's state on the edit form.


Have you gone to Display Manager
/admin/structure/types/manage//display
and played with those settings by the gear?

I normally setup display types like "default", "teaser", "teaser- icon side", etc. Then when I create a view, instead of outputting "fields", I output one of these pre-setup display types. I use Display Suite to help get more control of them.

I'm using this votingapi widget in D8 in this way and had no issues.


How can I get exposed filter for content type from the view programmatically?

It might be easier to get the display settings from the View storage (the configuration of the view):

$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$display = &$storage->getDisplay('page_1');
$display['display_options']['filters']['nid']['value']['value'] = 123;
$storage->save();

Here you should be able to find all options configured in the Views UI.


How can I update all content of a content type with a newly added field?

if I understand correctly you need to update node in range of new date? right? so if this is the case why not use EntityFieldQuery() to list of this nodes then node_save() or field_attach_update() to update the new value.

if this is the case I'd be happy to give you some snippets to help you do this.


How to remain logged in when switching languages via domain?

Try adding this to settings.php

$cookie_domain = '.dev.example.com';


Drupal 6.22 is compatible with PHP 5.3, but some contributed modules may not support 5.3. That said, I have been developing D6 sites on 5.3 for more than a year without any problems.

Usually, the PHP version is not the cause of JS problems, so I would start to look for the solution elsewhere (Firebug?).


Where is the the site name and slogan set?

In your active theme's template.php, check template_preprocess_page() function and add following lines:

$site_name = variable_get('site_name');
$site_slogan = variable_get('site_slogan');
$variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;

Assuming that you have used $variables as argument in template_preprocess_page() function.

Now $site_name_and_slogan can be used in page tpl files.

If you have not implemented template_preprocess_page() function, then replace template word with your theme name and add the function as mentioned below:

function THEMENAME_preprocess_page(&$variables){
  $site_name = variable_get('site_name');
  $site_slogan = variable_get('site_slogan');
  $variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;
}


I solved the problem by creating a custom CKEditor plugin.

This is the JS code, in case anyone find it helpful:

CKEDITOR.plugins.add('tableclass', {
  beforeInit: function (editor) {
    editor.ui.addButton('addtableclass', {
      label: 'Add table class.',
      command: 'addTableClass',
      icon: '/modules/custom/mymodule/icons/add.png'
    });
  },
  init: function (editor) {
    editor.addCommand('addTableClass', {
      canUndo: true,
      exec: function (editor, data) {
        const className = 'custom-class';
        var selection = editor.getSelection();
        var selectedElement = selection.getStartElement().$;

        if (selectedElement.localName === 'table') {
          selectedElement.classList.toggle(className);
        }
        else {
          selectedElement = selectedElement.parentNode;
          while (selectedElement && selectedElement.localName !== 'table') {
            selectedElement = selectedElement.parentNode;
          }
          if (selectedElement.localName === 'table') {
            selectedElement.classList.toggle(className);
          }
        }
      }
    });
  }
});


Drupal Commerce 2 Promote Product to Front Page

"Promoted to front page" is an archaism from the early days of Drupal, so it wasn't transferred into Commerce. Nowadays you can create any number of fields, and filter on them:

1) Go to your product type.
2) Create your own boolean field called "Promoted to front page"
3) Use it from your View.


You're going to want to create your new input format separately (probably in a module), assign it to the fields in your content type, then export the fields again and bundle in your module.

Not knowing how complex your new input format is, best advice is to grab the examples module and check out the filter_example module for a good test case of how to create a new input format.

Once you have the input format created, go back to your content type and under "Structure > Content Types > Manage Fields" set the default input format for these fields to your new input format and export your fields to your module.


How do I make drupal check for similar content?

Use the Unique Field module and select your link field as the unique field.


How can I get links in Views Slideshow to link to different URLs than just one as defined in views?

I found that the answer is that I needed to set the Formatter of the link to be set to the default. You can see in the picture that I was trying different formatting options, but the default is what I needed.


Drupal 7 and views: Get results from two content types and their own individual terms

Your problem is that your query is using INNER JOINs but you need to be using LEFT JOINS.

As you found in the thread I linked to the easiest solution is to edit your filter criteria and check the reduce duplicates checkbox.


For now I have solved this by patching the make file of the commerce kickstart profile:

projects[commerce_kickstart][type] = profile

projects[commerce_kickstart][patch][] = patches/commerce_kickstart.patch

The content of patches/commerce_kickstart.patch is this:

diff --git a/drupal-org.make b/drupal-org.make
index bde036e..787f6ea 100755
--- a/drupal-org.make
+++ b/drupal-org.make
@@ -31,6 +31,7 @@
 projects[taxonomy_menu][subdir] = "contrib"
 projects[libraries][version] = 2.1
 projects[libraries][subdir] = "contrib"
+projects[libraries][patch][] = patches/libraries-from-inherited-profiles.patch
 projects[views_megarow][version] = 1.0
 projects[views_megarow][subdir] = "contrib"

The patch happes to be applied on the commerce kickstart before its own makefile is executed. When it finally get executed it will also applied my libraries module patch within its directory structure.


I just realised I was missing the & in my submit function. It should have looked like this:

function ga_script_script_next_question($form, &$form_state) {
}

It works fine now.


The best and quick way to go with is using EntityForm. The module provides advantage of using field using which you can have Entity/User Reference fields with auto-complete, without writing a single line of code. To notify 3 users on Email, you can use Rules Module. And the other advantage is, it is maintained by Community so all security issues are tracked and fixed before the site can get affected.

Webform module doesn't support auto-complete by default you'll need to use Webform Autocomplete module for that. I've not used this module, so not sure if this provides the option for referencing existing entity.

If you're building it custom, you'll need to build everything by your own using Form API and Mail System. Which will be time consuming as compared to using EntityForm.


How to handle cache metadata in a cacheable response?

You have to add the cacheable metadata from the render array to the response:

use Drupal\Core\Cache\CacheableMetadata;

  $rendered = \Drupal::service('renderer')->renderRoot($build);
  $response = new CacheableResponse($rendered);
  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
  return $response;


How to override a JS function in the Media Module without editing the actual module files?

You can simply do it like that :

Drupal.media.browser.validateButtons = function(){ // Your code ... };

Of corse, this assignment must be after the original one.


how to retrieve the index size of a field array

You mention foreach(), but did you try it? Seems to me that it should work. foreach($node->field_img[LANGUAGE_NONE] as $key => $value)


How do I pass parameters from a form redirect to a controller?

In a route callback like a controller you can pull the request with a typed function parameter:

use Symfony\Component\HttpFoundation\Request;

  public function index(Request $request) {
    $query_parameters = $request->query->all();

  }


A hook with exactly the same name exists for CCK in Drupal 6, it just doesn't seem to be all that well documented.

It's invoked from the content_access() function and has the following signature:

function MYMODULE_field_access($op, $field, $account = NULL, $node = NULL) {

}


Use custom marker when specific checkbox is checked

I would use CSS for this.

Add your featured checkbox field
Add a views-row class, in the format settings, with the replacement pattern of the value for the checkbox

Now I can't remember if GMap will add that class to the marker rows too. If it does not, I would advise you to override the template for the view and in the class section, add $fields['field_featured'], making sure that there is a space before it

Using that class, you can style it however you want using CSS and/or JS

Hope that helps!


If you'd like to customize the user registration form, you're probably looking at a custom module to take care of this; an invocation of hook_form_alter() can step in and alter the behavior of the user registration form. For example, adding the following functions to MYMODULE:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  // Disable the email field
  $form['account']['mail']['#access'] = FALSE;

  // @TODO: Override validation functions in $form['#validate']
  // that check the mail field

  // Replace the user registration form submission with
  // the function MYMODULE_form_user_register_form_submit
  $form['#submit'] = array('MYMODULE_form_user_register_form_submit');
}

// Alter the disabled mail field before
// submitting registration form to user_register_submit()
function MYMODULE_form_user_register_form_submit($form_id, &$form_state) {
  // add '@mydomain.com' to the submitted username field
  $form_state['values']['mail'] = $form_state['values']['name'] .  '@mydomain.com';
  user_register_submit($form_id, $form_state);
}

This only get you partially there, as overriding such key functionality requires many scenarios to validate now that a key assumption is gone (e.g. what happens when someone enters an email for a name, what happens when a user needs to recover password, etc.).

It might be helpful to look at the source code of the Optional mail on register module to see how that is accomplished so you can under how modules can override Drupal's user registration functionality.


Could someone explain the 'hit' and 'miss' status in memcache per page output?

The hit/miss statuses are the result of the cache being touched as the result of the operation. For the given operations:

Get: (for a single key) Hit: data was retrieved from the cache; Miss: data was found not in the cache.
Set: Hit: data was stored in the cache; Miss: data was not stored in the cache.
GetMulti: (for multiple keys) Hit: data was retrieved in the cache; Miss: data was found  not in the cache.
Delete: Hit: data was removed from the cache; Miss: data was not removed (for a missing key) in the cache.


Why is the Commerce product's price hidden in my view for Anonymous User?

A first possible solution is to give the "View any product of any type" permissions to anonymous. Here is a relevant screenprint about it:

Another solution is to disable SQL rewriting within the Advanced > SQL Settings section of the view. This can have security implications if your using contextual or exposed filters. So make sure that your filters or contextual filters (i.e. relationships) are properly limiting access.

For more info, refer to comment nr 5 or comment nr 6 of the issue about "Views results empty for unprivileged user when using Relationship: Content: Referenced Product"


You can use Rules module for it. There is an event "After updating an existing user account", add conditions "User has roles" (both for account-unchanged and account parameters to check roles before and after an update), and as a action you can use "Run custom PHP code" to do whatever you want.


How do I add a CSS class to a form label?

I know this is an old thread, but for anyone Googling.

The clue to this is in template_preprocess_form_element().

$element += [
    '#title_display' => 'before',
    '#wrapper_attributes' => [],
    '#label_attributes' => [],
  ];

#label_attributes is a standard attribute array, so very easy to set a class with ['class' => ['my-class', 'other-class']]

#title_display takes 3 values:

before: The label is output before the element. This is the default.
after: The label is output after the element. For example, this is used for radio and checkbox #type elements.
invisible: Labels are critical for screen readers to enable them to properly navigate through forms but can be visually distracting. This property hides the label for everyone except screen readers.
attribute: Set the title attribute on the element to create a tooltip but output no label element. This is supported only for checkboxes and radios


Update user profile picture using entity_metadata_wrapper

Try this out :

  $wrapper = entity_metadata_wrapper('user', $form_state['entity_id']);
//- Get the user object.
  $user = $wrapper->value();
  if (isset($form_state['values']['user_profile_pic'])) {
    $file = file_load($form_state['values']['user_profile_pic']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $edit = array(
      'picture' => $file,
    );
    user_save($user, $edit);
  }


How to disable adding new terms via the autocomplete deluxe module for taxonomy terms?

You can use the content taxonomy module: https://www.drupal.org/project/content_taxonomy

On the content type fields that are taxonomy reference fields there will now be an extra option that says: Deny any new terms checkbox

It will throw this error when creating a new term:

Client: new terms are not allowed. Please choose from the suggested options.

Apparently there are other solutions I found aswell:

https://www.drupal.org/project/taxonomy_autocomplete_permission -- but it isn't working for autocomplete deluxe.

And there were a few discussions where it involved hacking core to disable it. The content taxonomy module seems to be the only way. It would be better if we didn't have to install another module.


How to display nodes only after certain dates? (An Advent calendar is in progress)

We have a client who uses the Scheduler module for their blog.  They write a backlog of posts, and then post date them for when they want them to appear.  You should be able to use this.  Make nodes for all of the days, and date them for when you want them to appear.  As long as you have cron workng properly, nodes should appear when they should.

Another option is to use the Date module along with Views.  Make a content type with a date field.  Set the date field to the day you want it to appear.  Then make a view over that content type, and add a filter to compare the date field against the current day.

Of the choices, I would go with Scheduler.


Does page.tpl.php get overwritten on updates?

For an drupal core update, you transfert every files/ folder except the sites folder for drupal 7.

Because in this folder, you have the setting.php and all your modules (custom or contrib) and your theme.

For module update, you can use the drupal ui or transfert the module update in the sites/all/modules folder.

So normaly, your theme and your page.tpl.php cannot be overide by an drupal core update.


How to make Adaptivetheme dropdown menu show on start page?

Try editing the relevant menu at /admin/structure/menu/

Edit each (first level) items that is not showing it's submenu items and tick off "show as expanded".

This is a general tip. I don't know exactly how your theme works.


Panels problem with changing the width of columns or regions

I found it. when the current language of the site is rtl such error reported. it must be ltr


In D7 you might want to clear also the variables drupal_js_cache_files and drupal_css_cache_files:

drush vdel drupal_js_cache_files && drush vdel drupal_css_cache_files

Other than that, do you have any other cache on top of drupal (varnish?). Your pages could be cached with the reference to the old JS files. Is your site broken (404 on CSS/JS files) or is it just referencing the old ones? Usually drupal regenerates aggregated files if it can't find it.


Override Taxonomy Pages without entire page override

You can use Panels module to create custom layout.

Or :

You can override taxonomy-term.tpl.php in your theme directory as following :

taxonomy-term--[vocabulary-machine-name|tid].tpl.php

I would suggest panel rather than overriding template files.


Meta tags, title and description not showing up on home page

Try printing

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

in your page.tpl.php or page--front.tpl.php if youre using Meta tags


How to hook theme of the main system menu in drupal 7 to display only some of the elements?

There are different levels to alter the system menu. If you want to add a top level container like drupal commerce does for the admin shop section, you need to add a menu item with hook menu like this:

// Top level "Store" container.
$items['admin/commerce'] = array(
  'title' => 'Store',
  'description' => 'Administer your store.',
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file path' => drupal_get_path('module', 'system'),
  'file' => 'system.admin.inc',
  'weight' => -7,
);

system_admin_menu_block_page is what will do the job, of making it a part of the system menu.

If you want to make the menu appear under one of the sections, like configuration etc, you just need to adjust your path in hook_menu, fx

$items['admin/config/section'] = array(...);

Every time you want to create a section that should hold other menu items, simply add

'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),

When creating a menu item in a section, just create a normal menu item.

Update
Since the menu structure is cached, you can't alter the menu by a per user scenario. But there are still some methods available.

Since menus are only displayed if the user has access, you could create a custom access control function for all the menus and put your logic in there.
You could also try to do this in the theming layer, and alter the output to only display the desired menus. I haven't tried this in Drupal 7, but generally, altering the output of menus this way is hard, as the menu system is quite complex.

If you need to alter the menus, to change the access control, you should use hook_menu_alter.


It's a better idea to use db_select or other DB API functions, rather than trying to use db_query directly. You'd want to try something like:

 $to_user_balance = db_select('ubercart_funds_user_funds', 'ucfuf')
   ->fields('ucfuf')
   ->condition("uid", $value['in_array'], '=')
   ->execute()
   ->fetchAssoc();

For more, see https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_select/7.x

And for overall DB API docs, see: Drupal.org DB API docs


When you log in as admin. just hover your cursor over the words and you can do a quick edit. You might have tried create content. If you just click content, all content created will populate.


Edit custom field using user_presave hook during account creation

Try this out:

/**
 * Implements hook_user_presave().
 */
function mymodule_user_presave(&$edit, $account, $category) {
  $edit['field_custom_xyz'][LANGUAGE_NONE][0]['value'] = 0;
}


Simplenews condition results in double email

@Kristoffer Rom, I've just tested and I've got the same duplication.
So, I suggest you create such notification rule based on:

"After saving new user account" event.
"Send mail" action from "System" actions group.


How to add description like: "Comments for paragraph 1" to comments

I don't think it will really be answerable without the code you wrote.

General answer is:

alter query that gets comments to include paragraph number (hook_query_alter)
alter their rendering, so paragraph number is sent to .tpl files (hook_comment_view_alter)
change tpl file of your theme to display that number.


Setting the form value to an organic group gid from validation hook of custom field widget (Drupal 7)

I'm assuming the validate callback that you have mentioned in your question is the #element_validate callback for the field widget element.

In that case, form_set_value must be set to a list of items because a field is inherently multi-valued. Each item in this list must conform to the schema of the field.

So, in this case:

$items = array();
$delta = 0;
$gid = ...; // From somewhere
$items[$delta] = array(
  'gid' => $gid,
  'state' => OG_STATE_ACTIVE, // optional
  'created' => REQUEST_TIME - 3600 // optional (yesterday)
);
form_set_value($element, $items, $form_state);

To illustrate this better, I have a sandbox project up on drupal.org. It declares a new widget with hierarchical dropdowns just like you have described. You can check the code directly from http://drupalcode.org/sandbox/amarnus/1868742.git/tree/refs/heads/master or clone the project from http://drupal.org/sandbox/amarnus/1868742. Hope this helps!


Correct way for a db_query for nodes between two timestamps

You can try using db_select instead wich is a better way to create query with Drupal (assuming you are using Drupal 7).

$start_time = '1403564400';
$end_time = '1403650800';
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'created', 'title'))
  ->condition('created', array($start_time, $end_time), 'BETWEEN');
$result = $query->execute();
$record = $result->fetchAll();


how do I determine the field type within a field formatter?

Maybe it is better to keep the two formatters separated and just put the shared code into a new formatter. Your two formatters can then extend the new one and just overwride the things specific to them.


What arguments can I use when defining a service?

Yes, the @ arguments are references to services. From Symfony's Introduction to Parameters:

  You can of course also reference services, which looks a bit different in each format. You can configure the behavior if the referenced service does not exist. By default, an exception is thrown when a non-existent service is referenced.

  Yaml

  Start the string with @ or @? to reference a service in Yaml.

  @mailer references the mailer service. If the service does not exists, an exception will be thrown;
  @?mailer references the mailer service. If the service does not exists, it will be ignored;

You can also use %-wrapped parameters which are slightly different; they can be used to refer parameters or get access to special SYMFONY__ prefixed server environment vars. (See How to Set External Parameters in the Service Container.)


How do I load a library defined with hook_library() on node/edit pages?

I would call drupal_add_library() in a hook_form_alter() implementation, like this:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node_edit_form']) && $form['#node_edit_form') {
    drupal_add_library('MODULE', 'LIBRARY');
  }
}

This should ensure the library is loaded whenever a node form is displayed.

And using hints from Berdir to use hook_form_BASE_FORM_ID_alter and from kiamlaluno to use #attached:

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $form['#attached']['library'][] = array('MODULE', 'LIBRARY');
}


Use previously-submitted values as default values in a GET-method form

You will have to set query parameters on submit and then you can fetch them and use as default values.

1] Redirect on submit

$form_state->setRedirect($route_name, $route_parameters, $options);

2] Fetch query parameters

$params = \Drupal::request()->query->all();


Unable to loop through all nodes in a content type and load them without hitting memory limits

I was able to get this to work by using the following command pulled from the deprecated node_load() function.

\Drupal::entityManager()->getStorage('node')->resetCache(array('NID'));

The fixed script would be:

$query = \Drupal::entityQuery('node')
         ->condition('type', 'product')
         ->execute();
$nids = array_keys($query);

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    print $node->title->value;
    \Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
}


How to get taxonomy term name/label from a field?

The field only stores term IDs. So either get the term ID and load the term from it or load the referenced entities directly.
/**
 * Implements hook_entity_presave().
 */
function MYMODULE_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof \Drupal\node\NodeInterface && $entity->bundle() === 'MYBUNDLE') {

    if ($field = $entity->get('field_MYFIELD')) {

      if (!$field->isEmpty()) {

        $label = $field->referencedEntities()[0]->label();
        // dpm($label);
        // Code on...
      }
    }
  }
}

Consider installing Devel. It gives you some handy debugging helpers like dpm($some_var) to dump variables into core's status messages block so you can inspect them easily.


1. theme user registration form

implement hook_theme:

function MYMODULE_theme()
{
  $return = array(
    'my_custom_registration_form' => array(
      'render element' => 'form',
      'template' => 'my_custom_registration_form'
    ),
  );

  return $return;
}

implement hook_form_alter:

function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{
  //dpm($form_id);
  if ('user_register_form' == $form_id) {
    $form['#theme'] = 'my_custom_registration_form';
  }
}

create my_custom_registration_form.tpl.php file in MYMODULE directory, clear the cache, check if it works;

<?php dpm($form) ?>

copy html from your static file (just form part), put it into my_custom_registration_form.tpl.php, example (this will be different in your case):

<?php print render($form['DESIRED_FIELD']) ?>

...

//render other fields (hidden fields), without them submit won't work
<?php print drupal_render_children($form) ?>

// or you can render them manually

// <?php print render($form['form_build_id']) ?>
// <?php print render($form['form_token']) ?>
// <?php print render($form['form_id']) ?>

2. In login form i want to remove tabs LIKE create new account and request new password - you can do it with CSS, or by removing $tabs variable from page template (you can create specific page template just for login page),

3. enstand of these tab i want to give like just before login button -
with hook_form_alter fnction you can add other fields (manage theme) to the form

P>S: dpm() - is from Devel module


How do I create an AJAX callback to Drupal video link?

You need a route and callback defined in a hook_menu. Below is a kickstarter not a complete example ;)

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

  // an endpoint to add an entity to the default flag_list
  $items['node/%/play'] = array(
    'page callback' => 'example_module_video_count',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'delivery callback' => 'ajax_deliver',
  );
  return $items;
}

Here is the callback

function example_module_video_count($nid = NULL) {
    /* do you stuff */
    $node = node_load($nid);
    $commands = array();
    /* add some ajax commands if required, look at ajax_command_invoke */
    return array('#type' => 'ajax', '#commands' => $commands);
}

Hit the URL from jQuery.ajax()

$.post("/node/1/play", function(data) {});


this one worked:

function THEMENAME_preprocess_html(&$variables) {
  //view name as body class
  $variables['view_title'] = '';
  $route = \Drupal::routeMatch()->getRouteObject();
  if ($route) {
    $view_title = $route->getDefault('_title');
    $variables['attributes']['class'][] = 'view-' . $view_title;
  }
}


Creating argument to filter multiple NID's in a single filter-criteria

The "Contextual filter" solution is only needed if you wish to filter your results dynamicly by passing the necessary filters through the URL.

If I understand your question correctly you wish to filter your view on 4 specific nid's only (witch will never change)?

In that case you could modify your views filter setup and split into 4 seperate filters (each filtering on 1 nid). In the dropdown menu (where you have the "add" button to add a new filter) you have a config page where you can rearrange your filters and more importantly you can specify conditionals using filter group's. In your case I would create a second filter group for the 4 nid filters and use the "Or" operator between them.


Ways to implement auto voting feature on a content type?

The Rate might be useful for what you are trying to accomplish.

  This module provides flexible voting widgets for nodes and comments.

  Administrators can add multiple widgets. By default, there are 8 widget types to choose from:

  Thumbs up
  Thumbs up / down
  Number up / down
  Fivestar
  Emotion (this makes me mad, angry...)
  Yes/no
  Slider (Drupal 6 only)
  Custom


I had to use another drush location. With the one in [~/public_html/drupal/vendor/drush/drush] everything seems to work.


Ben Your solution is not ideal, as you now have your own version of the toolbar module, and should there be any bug fixes and security fixes, you will not benefit from those, without upgrading your version of the toolbar module.

Solution 1.

CSS will by it's design overwrite itself, since the theme CSS files will be included last, any rule you make in your theme that is identical to what's in the toolbar will take presedence.

Solution 2.

Sometimes it can be a pain to revert styles to browser default, if that is the case, creating a css file with the same name as the one you want to remove and including it in your theme, will make Drupal skip the one in the module and use the one in your theme. In this case creating a toolbar.css file anywhere in your theme and adding it in your info file, will remove the toolbar.css file from the toolbar module and fix your problems.
Remember to clear cache

Solution 3.

If by some reason you have problems making solution 2 work, you can instead remove the css file using hook_css_alter, this only works in Drupal 7+


I'm hoping this answer works for you. If you're wondering if you can set a default value for a field in a content type when adding new content, the answer is yes.


Use custom HTML file for page created by Views?

When you edit the View, under the Advanced settings on the right-hand side you should see "Theme information". If you click that it will give you the content of the theme templates for the View, which you can then override by copying into your theme, in a file with a corresponding name.


Zero pad Drupal 7 Form API Date Control day and month HTML select element

I think you can use #date_format

  $format = 'm d Y';
  $form['date_from'] = array(
     '#type' => 'date',
     '#title' => t('select a date'),
     '#date_format' => $format,
   );

More values:
http://php.net/manual/en/function.date.php


User registration form at a new menu path got error after submit

My mistake in my hook_menu(). The page arguments should be array('user_registration_form') and I removed the custom page callback mymodule_employee_create_form(). It did work as expected.

function mymodule_menu(){
    $items['employee/create'] = array(
        'title' => t('Create Directory'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_register_form'),
        'access callback' => 'mymodule_access_directory',
        'type' => MENU_NORMAL_ITEM,
        'weight' => 0,
    );
    return $items;
}


AJAX added form element disappears after failed validation?

Generally it's not good to create the elements in the ajax callback. What I usually do is add the form elements to the main form, but wrap them in the if statement, and then in the ajax callback just refresh the container of that element or the whole form if it's small.

function SOMETHING_form($form, &$form_state) {

  $form['nominee'] => array(
    '#type' => 'checkbox',
    '#title' => t('I am nominating someone else'),
    '#ajax' => array(
      'callback' => 'return_nominee_email_element',
      'wrapper' => 'nominee-email-wrapper',
      'progress' => array('type' => 'none'),
    ),
  ),

  if(isset($form_state['values']) && $form_state['values']['contact_details']['nominee'] == TRUE) {
    $form['nominee_email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email'),
      '#required' => TRUE,
      '#prefix' => '
',
      '#suffix' => '
',
    );
  } else {
    $form['nominee_email'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }

 return $form;
}

function return_nominee_email_element($form, &$form_state) {
  return $form;
}

See if something like that works for you.


Have Google Analytics code still run on force download

For that kind of thing, you can use the GA "event tracking" to track the click event for the file download.

  Events are user interactions with content that can be tracked independently from a web page or a screen load. Downloads, mobile ad clicks, gadgets, Flash elements, AJAX embedded elements, and video plays are all examples of actions you might want to track as Events.

The GA module provides some click event tracking for files by default in the config, else you can check here for more info on adding such a feature:

https://developers.google.com/analytics/devguides/collection/analyticsjs/events


How do I use hook_views_query_alter() to re-write a query?

While exploring a site-building alternative (see comments in OP), here is a direct answer to the question:

Implementing the hook_views_query_alter should do what you want:

function my_custom_module_views_query_alter (&$view, &$query) {
  $display_id = $view->current_display;
  $uid = $view->args(0); // for a view that is loaded from a URL like /myview_url/UID

  // Your code from the OP follows, modified accordingly
  // You have a query object available as an argument by reference
  // You can add joins and filters to it
  ...
}

You would need to implement the hook_views_api in addition to placing the above code snippet inside the my_custom_module.views.inc file, a minimal implementation would be:

function my_custom_module_views_api() {
  return array(
    'api' => '3',
  );
}

Cheers!

P.S.: Have a look at this one, if you haven't already => http://www.kdweb.co.uk/blog/drupal-module-views-hook-sequence


How to adjust the login pages with bootstrap?

Solved by changing the bootstrap class to

col-md-6 col-md-offset-3


How to attach username at the end of url?

Try this:

go here: admin/config/search/path/patterns

and add: /[user:name]

to your replacement patterns.


Different responsive image per breakpoint

Are they completely different images?

Then I'd use Paragraphs module and create a heavily customized template outputting your different images as <source srcset="..." media=""> inside a single <picture> tag. Modern browsers will only download the correct version for the visitors viewport. (Manually add a polyfill library if required.)

Is there one large source image rendered with different focal points or different crop areas (Modules "Focal point" or "Image widget crop")?

Then I'd create a specific breakpoint group only for your banner. Create a responsive image style for this group and use Select a single image style for each individual breakpoint width. Drupal will then automatically render a similar markup as above and also add polyfills for older browsers.

In any case, definitely use a <picture> tag with multiple <source srcset="...filename..." media="(...mediaquery...)">s for art directed responsive images.


Is there a way to display primary tabs vertical in separate block?

The Tabs rendered in page.tpl.php like this:

<?php if ($tabs): ?>

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

<?php endif; ?>

in the main content div:
You can override the page.tpl.php in your custom theme and move this part of code to sidebar:

something like :

<?php if ($tabs): ?>

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

    <?php endif; ?>


How can I place a  new  textfield in the tab vocabularies in a content type?

The fieldset for the vocabularies used by a node are added from taxonomy_form_alter(), using the following code (the relevant part is the one between "// 3" and "// 4"):

// 1
if (!isset($node->taxonomy)) {
  $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
}
else {
  // After a preview or form reload, the terms must be converted to objects.
  reset($node->taxonomy);
  if (!is_object(current($node->taxonomy))) {
    $node->taxonomy = taxonomy_preview_terms($node);
  }
  $terms = $node->taxonomy;
}

$c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $node->type);

while ($vocabulary = db_fetch_object($c)) {
  if ($vocabulary->tags) {
    if (isset($form_state['node_preview'])) {
      // Typed string can be changed by the user before preview,
      // so we just insert the tags directly as provided in the form.
      $typed_string = $node->taxonomy['tags'][$vocabulary->vid];
    }
    else {
      $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
    }
// 2
    if ($vocabulary->help) {
      $help = filter_xss_admin($vocabulary->help);
    }
    else {
      $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
    }
    $form['taxonomy']['tags'][$vocabulary->vid] = array(
      '#type' => 'textfield',
      '#title' => $vocabulary->name,
      '#description' => $help,
      '#required' => $vocabulary->required,
      '#default_value' => $typed_string,
      '#autocomplete_path' => 'taxonomy/autocomplete/' . $vocabulary->vid,
      '#weight' => $vocabulary->weight,
      '#maxlength' => 1024,
    );
  }
  else {
    // Extract terms belonging to the vocabulary in question.
    $default_terms = array();
    foreach ($terms as $term) {
      // Free tagging has no default terms and also no vid after preview.
      if (isset($term->vid) && $term->vid == $vocabulary->vid) {
        $default_terms[$term->tid] = $term;
      }
    }

// 3
    $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
    $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
    $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
  }
}
if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
  if (count($form['taxonomy']) > 1) {
    // Add fieldset only if form has more than 1 element.
    $form['taxonomy'] += array(
      '#type' => 'fieldset',
      '#title' => t('Vocabularies'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
  }
  $form['taxonomy']['#weight'] = -3;
  $form['taxonomy']['#tree'] = TRUE;
// 4
}

The fieldset, which is then changed by the Vertical Tabs module in a tab, is added only when there are more than one vocabulary associated with the content type of the node being created.

To add a new field in that fieldset, you should implement hook_form_alter() in a module, and add code similar to the following one:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && && $form['type']['#value'] . '_node_form' == $form_id) {
    if (isset($form['taxonomy']['#type']) && $form['taxonomy']['#type'] == 'fieldset') {
      // Add your field.
      $form['taxonomy']['mymodule_field] = array(
        // …
      );
    }
  }
}

The module you write should be executed after the Taxonomy module, or the module will not find the fieldset added by the Taxonomy module. The module is executed after the Taxonomy module if it has a name such as TaxonomyAddendum, or if the weight of the module is higher than the weight of the Taxonomy module (10 should be enough).

As for altering the existing fields for the taxonomy terms, you should look at the code between the comments "// 1" and "// 2"; as form is build using the vocabulary ID, as in $form['taxonomy'][$vocabulary->vid], you need to know it to get all the form fields used for the taxonomy terms. If you want to change the form field for a vocabulary for which you know the ID, then the code is simpler, as you don't need to get all the vocabularies that are associated to the node being edited; that is also true if you want to alter the form field for a vocabulary you know by name. You can use the following code to get a vocabulary object knowing the vocabulary name.

$result = db_fetch_object(db_query(db_rewrite_sql("SELECT v.vid, v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' AND v.name = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $type, $vocabulary_name));

$type is the content type that, in your case, is $form['#node']->type; $vocabulary_name is the name of the vocabulary.

If you know the vocabulary ID, then you can simply use taxonomy_vocabulary_load() to get the vocabulary object, which you could need to populate the taxonomy term form field.


How to prevent certain bundled CKEditor plugins from loading

We can disable CKEditor plugins by following hook as show with the example for disabling image and image2 plugins:

/**
 * Implements hook_ckeditor_settings_alter()
 */
function MYMODULE_ckeditor_settings_alter(&$settings, $conf) {
  // Comma separate names of plugins to remove.
  $plugins_to_remove = 'image,image2';
  $settings['removePlugins'] = !empty($settings['removePlugins'])
    ? $settings['removePlugins'] . ',' . $plugins_to_remove
    : $plugins_to_remove;
}

(taken from my own article: http://kb.detlus.com/articles/drupal/drupal-7-disable-ckeditor-bundled-plugins/)


How do I check by default a checkbox from a checkboxes control after an AJAX call

Thanks @IvanJaros, i have read it and i think i'm doing everything fine but i can't understand why is not working.

I have modify selectAjaxCallback to solve this problem:

public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      $select = $form_state->getValue('select');

      foreach ($this->values['checkboxes_df'][$select] as $key => $value) {
        $form['container']['checkboxes'][$key]['#checked'] = $value;
      }
      return $form['container'];
    }

This code works, but i'm not sure if it's the right way to solve this problem.

Thanks.


Add unique class to webform radio form-item div

You can add particular css while creating that field in webform configuration itself.See below section in your webform

For this particular clas you can add css in your code.


I installed the theme on my computer and those elements are not printed using regions (as you said), are printed using the template file (and that's because there are no blocks with them, they are printed directly in the template file - except the menu that is printed using $primary_nav variable).

So, if you want something like you said, you need to add that content in blocks. Or, if you only want to add them in the same area or div in the page, just move them in the template file (for example, move "#menu-wrapper" in the "#header-bar" div, and you will have them together).


Is there a way to export or import individual display views?

Not that I know of.

An option. If they’re so similar that you can just do export and reimport to another view, you could keep them on the same view, clone the display, rename the display, override whatever field/filter you need to change and change it.


The issue was because the PHP GD Library was not installed in my machine...  So I installed the GD Library using sudo yum install php56w-gd and the things working good actually.

Note that to access to admin page (my aim) we can deactivate the captcha module using  this command : drush dis captcha


Try hook_form_alter

function hook_form_alter(&$form, &$form_state, $form_id) {
 // If you can find the $form_id you can print the exact form.
 print_r($form);
}


Author of question flags only nodes that are answer to his question (node reference)

Are they 2 nodes or 2 node types? If types, just create 2 separate .tpl files for them (node--type1.tpl.php and node--type2.tpl.php).

If they are the same content type, you can check that the node reference exists inside node.tpl.php like so:

Edit: code below now only prints the link if the current user is also the author of the node.

global $user;
if ($user->uid == $node->uid && isset($node->field_my_reference_field_name[LANGUAGE_NONE)) {
  print flag_create_link('select_answer', $node->nid);
}


"An AJAX HTTP error occurred.HTTP Result Code: 200"

we need to uncomment .htaccess file in php_value auto_append_file none may be it work.
in ajax return value must be defined.if not exist show this kind of error.clear cache.
 one other solution if you working on the local you need to disable newest module than check it[first you need to take DB backup].


Time also matters (date fields also has time, usually it's set to 0 am). Check in your database what time is associated with the date. If the time is i.e. 11 am or even 00:00:01 am (H.m.s), it will be excluded. It also can be changed the base date by your settings. (i.e. when you create a new date it can be created by default to 0 o'clock and to 12 o'clock too. Or even it can be the node creation time too.

Please note, when you compare date/time most probably the UNIX timestamp will be compared (in views at least)! Reason: drupal save UNIX timestamps into the database, when you create a view you will see the relation is in the query, so the inputed date will be converted to timestamp and a default time. And this default time can be mess up the things.


Are there any benefits/caveats with using Entity Reference over Term Reference?

Swings and roundabouts really, it depends on your use case...

Behind the scenes there's essentially no difference - both field types relate one entity to another by way of an ID, so it really comes to down which type provides you with the 'frills' you need/want.

As you mentioned Taxonomy has the open tagging widget, which is nice, but then Entity Reference has Views integration (by way of Entity Reference View Widget) which means you can define as complex a view as you like for your selection widget. Also very nice.

And then there's Inline Entity Form which you also mentioned. That's a superb tool obviously, but only really useful if you need it in your project.

What Taxonomy has going for it is that it's part of core, and doesn't require a bunch of other modules installed to work. But then in a normal Drupal build a lot of those modules will probably already be there. It also maintains a term index table for nodes which can help with performance, but obviously only if you're relating your terms to node types.

I think your choice is going to come down to what widgets/formatters you need for a particular situation to be honest, it's too tight to call :)


What you're asking doesn't really make sense.

MENU_LOCAL_TASK is used as metadata for a route defined in hook_menu().

#prefix and #suffix are properties for render arrays.

The two concepts are not compatible.


How to expand trimmed body text to full body text in the same Views page?

Consider using the Views Accordion module. Here is an excerpt from its project page:

  ... provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.

  For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.


How to add twig template for OwlCarousel format?

You need to rename it like this: owlcarousel-views--expert-talk.html.twig


Get yesterday's content with contextual filter in views block

Try this one

Content: Post date (>= -1days)

Instead of this

return date("d", strtotime("-1 day"));


How to make the Views Slideshow controls actually work?

Would it be possible to share the link?

It is also possible that there is a jquery conflict (ran into this issue a while ago). In my case it was superfish + flexslider, both with their own jquery source that were not interchangeable. This lead either the slider not working, or the menu not working.

I solved it by using jQuery.noConflict();
https://api.jquery.com/jQuery.noConflict/


How to populate search form with search term in View / Panels / Page?

Looks like from that link that the search form is the search block form, so you can do this as a theme form alter (you could also make a custom module in a similar fashion with form alters but this should serve your needs).  This goes in your template.php for your theme:

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'search_block_form':
      //checking if arg(2) exists so it doesn't try to do this if some visits the search page straight away
      if(arg(2)){
        $form['search_block_form']['#default_value'] = arg(2);
      }
      break;
  }
}


How to make my user notifications module notify node authors about new comments?

As per the "Or is there another way to make this work without the custom module I'm struggling with?" in your question, IMO the answer is yes. Read on for more details about how to "send a notification to the article owner when some user comments on the review added to an article." (as in your question).

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_notify_node_author_about_new_comment" : {
    "LABEL" : "Notify node author about new comment",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "comment:node:author:mail" ],
          "subject" : "A new comment was posted to the node you authored",
          "message" : "A new comment was posted, you can find it at [comment:url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Use the Rule UI to import it in your own environment. Some more details about this rule:

Event: After saving a new comment.
Condition: Check that the user who posted the comment is different from the node author (I'd think it doesn't make sense to notify the node author of comments posted by the node author, right?).
Action: Send an eMail to the node author, with a link to the comment that got posted.

Feel free to add any rules conditions that may fit to further improve the above prototype, to fit your actual requirements.

Note that the above rule doesn't depend on any other module, though you could make it way more sophisticated if you'd also get the Message module involved (eg to create a log file of all such eMails ever being produced, if that's what you'd want to do).

BTW: no need for custom code ...


How do I sort the list of modules by the number of open issues?

No, there isn't.

The number of issues isn't really relevant because you need to see what type of issues there are (cosmetic / blocking), how actively the module is maintained, how many maintainers, etc.

Big modules can have a lot of issues, but if they are frequently updated it's no problem. If a module has only one (blocking) issue but it isn't resolved due to lack of maintenance than it's worse.


Display Node or Entity Reference Content

The keyword you are looking for here is 'relationship'. You want to create a relationship between your two content types using your entity reference field. Once this is enabled, all the fields available for the 'leasing contact' field will be available.

This tutorial from NodeOne is the best out there for explaining the process: http://nodeone.se/en/using-entity-reference-in-views


Entity Type Manager: How to retrieve webform entries with webform_submission_data conditions

Don't think you can query webform fields like entity fields, but it should be possible in an SQL select query:

$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');

$query = \Drupal::database()->select('webform_submission_data')
  ->fields('webform_submission_data', ['sid'])
  ->condition('webform_id', 'my_form_id')
  ->condition('name', 'field_account_type')
  ->condition('value', 'normal')
  ->distinct();

$ids = $query->execute()->fetchCol();

$submissions = $submission_storage->loadMultiple($ids);

If you want to query the uid from the main table too, join both tables:

$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');

$query = \Drupal::database()->select('webform_submission_data', 'd');
$query->join('webform_submission', 's', 'd.sid = s.sid');
$query->fields('d', ['sid'])
  ->condition('d.webform_id', 'my_form_id')
  ->condition('s.uid', $uid)
  ->condition('d.name', 'field_account_type')
  ->condition('d.value', 'normal')
  ->distinct();

$ids = $query->execute()->fetchCol();

$submissions = $submission_storage->loadMultiple($ids);


Access User Data from external script inside a custom module

The code snippet is bootstrapping Drupal by assuming it's in Drupal's root path (i.e. require_once 'autoload.php';) To have it runnable from the module dir, you'll have to alter the relative path to make it work from wherever your script is at (e.g. is your module is in DRUPAL_ROOT . 'modules/custom/my_module/scripts/my_script.php' you would have use the path ../../../../includes/autoload.php to reach it).

Depending on what you're doing, you might want to consider a custom Drupal Console/Drush command as a part of your module instead of a PHP script that has to assume/find the location for bootstapping Drupal.


How to view what query was ran when a form is submitted?

Install the devel module https://drupal.org/project/devel, and choose the option display query log. The queries will be shown on the bottom of each page.

In admin/config/development/devel:

Check 'display query log'

Sometimes, I prefer just switching on logging in my.cnf for MySQL, because it shows the complete query as executed. If you do that, do not forget to switch logging off again when you are done. Otherwise, you'll fill up your disk/partition.

In the [mysqld]section, add:

log=/var/log/mysqld

Restart mysqld.


The easiest way is to create a custom module and use hook_form_alter():

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'user_register_form') {
    $form['account']['name']['#title'] = t('Full name');
    // perform other changes here
    // var_dump() or krumo() the contents of $form to see what you can change
  }
}

If you prefer you can also a variation of hook_form_alter to target the form specifically instead of having to do an if

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['name']['#title'] = t('Full name');
  // perform other changes here
}


How does Drupal handle autoloading of classes?

All files listed in .info files are parsed when modules are rebuild (Only changed/new files in that list are, for performance reasons).

That information is then stored in the {registry} and {registry_files} tables. So if you want to get all classes or those according to a given naming pattern, you can query those tables.


Custom module Pager does not work with Ajax filter

I have discovered a sort of workaround.  It requires storing the result of current_path() in a JS setting variable, and rewriting the path in JS when the pager is regenerated.

Sample code:

php
// building an ajax form...
global $base_path;
$settings = array(
    'my_module' => array(
    'my_path' => $base_path . current_path(),
  ),
);
drupal_add_js($settings, 'setting');

That will make the current page's path available in your JavaScript file to manipulate.  There are still kinks though, especially with AJAX filtering and AJAX paging all at once.  I will update this once I resolve all those kinks.


How can I redirect users to the order information after adding product

I've solved this by replacing last 3 lines with

return $this->redirect('commerce_checkout.form', array('commerce_order' => $cart_id_value));

And as ssibal suggested, here I do not use hard-coded URL (thanks for that).


Is there a way to force some block caching despite system block caching option is disabled?

With latest Drupal 7.33 release there is a new setting variable now:

/**
 * Block caching:
 *
 * Block caching may not be compatible with node access modules depending on
 * how the original block cache policy is defined by the module that provides
 * the block. By default, Drupal therefore disables block caching when one or
 * more modules implement hook_node_grants(). If you consider block caching to
 * be safe on your site and want to bypass this restriction, uncomment the line
 * below.
 */

$conf['block_cache_bypass_node_grants'] = TRUE;

Setting the above to TRUE the "cache blocks" option becomes checkable.


Set a numerical field to perform Views Global Math Expression calculations

Another solution that worked for me is to "Strip HTML tags":
Rewrite results --> [x] Strip HTML tags


You have selected field cardinality to one . So its not reflecting checkbox.
Please follow the below steps you can achieve what you asked

Go to Structure > Content Type.
Select the {{Custom Content Type}} . Click on Manage Fields.
Edit the taxonomy Entity Reference field.Click on Field Settings Beside Edit Tab
Change Allowed number of values from Limited to Unlimited


Checkbox so user can decide whether image should be displayed or not

Mh, there are several ways.

One of this is to add a boolean field to the content type.
Then you can create a template for the node, or the field, and display it only if the value of the boolean field is "on".

What do you think?


You need to enable the Datetime Range module.  It is currently an experimental module in Drupal 8, and not enabled by default.  On admin/modules it's in the Experimental group:

Enable it, and a new field type will appear, Date Range.


Further optimizing CSS delivery with AdvAgg?

This is the issue you'll want to follow: https://www.drupal.org/node/2396609 Inline critical css.

You can get rid of this message by using "Deferred CSS Execution: Use JS to load CSS". It's under the Experimental Settings of the CSS section. When you enable this, the page will no longer wait for the CSS to download before it starts to render. The bad part is you'll get what's known as a flash of unstyled content (FOUC). The issue I linked to above has to do with inlining the CSS that's needed to display the above the fold content so the FOUC doesn't happen.

Another way to get rid of the message is to inline all the CSS. This can be done by going to the Inline CSS/JS on specific pages section; just use the CSS section. Pick the pages you want to be optimized; node/* works for all nodes as an example.

The bundler comes into play when you look at the connection view from http://www.webpagetest.org/. If you're opening a connection in order to download a single css and/or js file then you should lower the number of bundles and see if that prevents a new connection from being used; this is super helpful with HTTPS connections which take up a lot of time to open. If there are a lot of files being transferred (image heavy site) then using more bundles will help with getting a better cache hit ratio in the browser. I found that 4 for both works pretty well in most sites but going higher or lower really depends on the site. Higher is usually better if the visitor is going to hit multiple pages. It's sorta an art form in order to get it optimal. Here's the issue for Drupal.org in regards to using AdvAgg for front end optimization: https://www.drupal.org/node/2493801


You may want to investigate Page Manager (Ctools suite).  This module allows you to intercept a URl and create variants based upon conditions (contexts) from the URL call.  Page Manager works very well with Panels which allows you to break down regions in your them into subregions and insert views in the panel.  Panels is fairly easy to use and even if you do not want to include additional sub regions, it combines well with Page Manager to accomplish what you want.  You can find more on how to use Page Manager at nodeone.se
By way of an example  you could create a panel page using Panels or Page Manager (it works the same starting in either module).  If the path were /blog/%blog then the page definition will intercept all /blog/anything URLs.  You could then create two variants, one to act if there are no comments and one if there is. You would then add a layout and include a view for each one.
Another approach might be to use Page Manager variants to redirect a URL request to another location so one could call the View directly and the other could go to the comment form.


$base_path is not added to AJAX URL request in login form

First off, in the settings.php file you should have an example of http://www.example.com and a comment there, saying that you should not append a trailing slash.
Next, in your case looks like http://localhost would be the correct value of $base_url, if any - try hashing out $base_url line to see if the site is fine without it - as it might be.


Create a view with 'Block' display. After it is created, make it display on the page you want.

How:

Go you sitename/admin/structure/views/add
Unchecked create a page option
Check Create a block
Give the Block title and select your desired display format
Click Continue & edit
Setup your view as per you wish
Click Save
Go to sitename/admin/structure/block
Look for your new view block "search for block name you give early while creating the view"
Click configure
if you don't want your block title replace your Block title with
Select in which region you would like to have your view
Go to end of the page, under Show block on specific pages select "only the listed pages"
enter the url of page you want your view to be available, for example if your page url is www.your_site/page1. Than add page1 in the box.

Please note you can add as many pages as you want and you can also use content type of specify in which node type you want your view to be visible.


Form Submit - Populate Title Before Validation

If you use #prefix and #suffix with display:none, it is hidden in display, but submitted and will be validated for required.
Try to use #required = FALSE and #type = 'hidden' and then set title in your submit handler.

function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    // Hide the title field
    $form['title']['#required'] = FALSE;
    $form['title']['#type'] = 'hidden';
    // Callback function to execute before validation
    array_unshift($form['#submit'], '_previous_meetings_set_meeting_title');

}

And you could also use Automatic Nodetitles with which you may use token replacement.


Drupal uses filenames only for theme suggestions 'template' => 'my_wall1'. But you can still place the template in a subfolder below templates and Drupal will still discover it.

Not tried this myself, but according to hook_theme() documentation: You can add a drupal root relative path if you want a very specific directory for the Twig file:

function my_module_theme() {
  return [
    'wall1' => [
      'template'  => 'my_wall1',
      'variables' => [
        'w1' => NULL
      ],
      'path' => 'DRUPAL_ROOT_RELATIVE_PATH'
    ],
  ];
}


I have had success with

$data['tabs'][0]['entity.node.canonical']['#link']['title'] = t('Overview');


Which module(s) should I use to create a customer support section?

See Similar Module Review page and choose the one that works best for you.


How to make a field readonly using hook_form_alter

It sounds like you could accomplish what you need to with Field Permissions. On a field-by-field basis you can set permissions to:

  Create own value for the field
  Edit own value for the field
  Edit anyone's value for the field
  View own value for the field
  View anyone's value for the field

So you would easily be able to allow your users to create the value for the field initially, but as soon as they have it only becomes editable by an admin.


How to adapt the date format in the admin/content page?

Date (and time) formats can be configured via admin/config/regional/date-time. It can be used to specify the format for data types Long, Medium and Short.

Other tabs that are available on that same page:

Formats (to define your own custom formats).
Localize (for language specific tuning).
Date Views (for date views specific to "day", "week" or "month").


An illegal choice has been detected. Please contact the site administrator.in dynamic select list dependent dropdown

i recently made a 3 level dependent dropdown and had the same issue with some of the problems i found on the way. First you need to re-organize your code a little bit more. have in mind that the callback function should normaly look something like this:

//callback
    function _get_state_field(&$form,&$form_state) {

     return $form['get-quotes-shipping0']['states'];
}

Any code inside the callback has the potential to intervene with the proccess, with some exceptions.

Without taking a longer look to your code i think it should look somethink like this:

<?php

 module_load_include('inc', 'location');
  if ($form_state['values']['country'] == '_none') {
    unset($form['get-quotes-shipping0']['states']['#options']);
    $form['get-quotes-shipping0']['states']['#default_value'] = '_none';
     return $form['get-quotes-shipping0']['states'];

  }
  else {
      $states = location_get_provinces($form_state['values']['country']);
 $form['get-quotes-shipping0']['states']['#options'] = $states;
  }

$form['get-quotes-shipping']['country'] = array(
      '#type' => 'select',
      '#options' => array('_none' => '- None -') + country_get_list(),
      '#multiple' => FALSE,
      '#weight' => 3,
      '#title'=>t('Country'),
      '#default_value' => (isset($_SESSION['selected_country'])) ? $_SESSION['selected_country'] : '_none',
      '#ajax' => array(
          'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => '_get_state_field',
            'method' => 'replace',
       ),
    );

    $form['get-quotes-shipping2']['actions']['get_quotes'] = array(
      '#type' =>'submit',
      '#value' => 'Get Quotes',
       '#submit' => array('custom_changes_get_quotes_submit'),
      '#validate' => array('custom_changes_get_quotes_validate'),
      '#weight' => 1,
    );

   $form['get-quotes-shipping0']['states']['#type'] = 'select';
     $form['get-quotes-shipping0']['states']['#title'] = t('State/Province');

   $form['get-quotes-shipping0']['states']['#prefix'] = '
';
   $form['get-quotes-shipping0']['states']['#suffix'] = '
';
    $form['get-quotes-shipping0']['states']['#options'] = array('_none' => '- None -') + $squadron_options;
    if (isset($squadron_options[0])) {
      $form['get-quotes-shipping0']['states']['#default_value'] =  $squadron_options[0];
    }

    //callback
    function _get_state_field(&$form,&$form_state) {

     return $form['get-quotes-shipping0']['states'];
}
?>

This is the code i wrote, try to follow the same structure it's working for me perfectly.

Tell us how it went, have a good coding!


Your problem resides in the way you are calling the css function in jQuery. Try this, it works for me:

(function($) {
  Drupal.behaviors.my_node_toggle = {
    attach: function(context, settings) {
      $("#change_css", context).click(function() {
        $('a').css("color","#ff0");
      });
    }
  };
})(jQuery);


How can I make revision log message required based on revision checkbox by node_form_alter?

I found an answer after hours of searching. Basically, I just need to add a custom hook validation for revision log. See below for my code.

function MYMODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
    // change revision log status based on revision checkbox
    $form['revision_information']['log']['#states'] = array(
        'required' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
        'visible' => array(
          ':input[name="revision"]' => array('checked' => TRUE),
        ),
    );
}
function MYMODULENAME_node_validate($node, $form, &$form_state) {
    // add revision log validation
    if (empty($form_state['values']['log']) && ($form_state['values']['revision'])) {
        form_set_error('log', 'Revision log message cannot be empty!');
    }
}

I hope this helps someone who needs revision log message required.


Looking at theme(), I notice that the "pattern" property is never used. What the function does is using the following code.

  // If there's no implementation, check for more generic fallbacks. If there's
  // still no implementation, log an error and return an empty string.
  if (!isset($hooks[$hook])) {
    // Iteratively strip everything after the last '__' delimiter, until an
    // implementation is found.
    while ($pos = strrpos($hook, '__')) {
      $hook = substr($hook, 0, $pos);
      if (isset($hooks[$hook])) {
        break;
      }
    }

In your case, theme() first looks for publication__news key in theme functions array, and then it looks for the publication key. As in your case there isn't any match for publication__news, it uses publication, and the template file associated with that theme function.

This is documented in theme().

  If the name contains a double-underscore (__) and there isn't an implementation for the full name, the part before the __ is checked. This allows a fallback to a more generic implementation. For example, if theme('links__node', ...) is called, but there is no implementation of that theme hook, then the 'links' implementation is used. This process is iterative, so if theme('links__contextual__node', ...) is called, theme() checks for the following implementations, and uses the first one that exists:

  links__contextual__node
  links__contextual
  links

  This allows themes to create specific theme implementations for named objects and contexts of otherwise generic theme hooks.


Upgraded Contrib modules & Drupal to 7.14 now SSL doesn't turn green

I am not sure if it would cause your problem, but Secure Pages requires patches to core.  The two you need are listed on the main project page.  I use 961508-23-32-D7 instead of 961508-21.  I am not 100% sure which version of 471970 I am using (that is just for unit tests, anyway).  Both apply to 7.14, but with some fuzz.


Image gallery where I can insert images and video

There are a ton of ways ...

You can create your own view, see Flickr-like responsive photo gallery for Drupal 8

Or go for a module like juicebox, or a simple colorbox or (my favorite) photoswipe gallery. These modules use an image field (with multiple values), and then offer a display for the field. For videos you need to make a view using their handlers, not sure which suppports what now ..

You can go further and further .. fe. by using the media_entity (now in core ! media 2.0) with slick_media (more like a slideshow) etc. - see here https://drupal-media.gitbooks.io/drupal8-guide/content/

It really depends on your needs.


Prevent anonymous users from accessing "node/" node/%nid and taxonomy/term/%tid

Have you tried in the template.php? what if you do something like:

function yourtheme_preprocess_page(&$variables, $hook){
   if(!$user->uid){
      if((arg(0) == 'node') || (arg(0) == 'taxonomy')){
         //redirect to login
      }
   }
}


I have fixed this now by adding:-

.region-sidebar-second .block-inner {
  background-color: white;
  border: 1px solid #CCCCCC;
  border-radius: 10px 10px 10px 10px;
  padding: 10px 20px 20px;
  position: relative;
  margin-bottom: 20px;
}

Sorry, it was a lack of knowledge of css causing the problem.


You shouldn't use format_date() anymore.  You should create a DrupalDateTime object, and then use the format() method.

$date = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('c', $my_iso_8601_date);
$my_rfc2822_string = $date->format('r');


"$.fieldValue is not a function" alert on login form submit

In the parent theme was a ajax.js override function that caused the error. It can be found in theme_root_dir/js/misc/. You just have to empty it. Don't forget to empty your cache afterwards. Now it should work.


When I add the comments to each node in a Views content list am I creating a n+1 database query problem?

You are creating a n+1 select problem, but you would do that if you created a list of full nodes since extra queries will happen on every full node display.

This isn't necessarily problem though, as you probably don't want to display 100 or 1000 nodes this way, but instead use a pager. When using a pager, n will never be more than your pager count which could be something like 10 or 20. 10 or 20 queries is not ideal but hardly a problem either unless you need to run a very high performance site, but if that were the case, you probably wouldn't use views anyways.

Views has some cache options which could be used to optimize, and reduce all of the queries to a single query on the cache instead. That is an easy of increasing performance.


How to add Login/Register link in the right header in Skeleton theme

Drupal has this feature where you can create menu links for user/login and user/logout and only the appropriate one will be displayed automatically. Same goes for user/register.

So create a new menu, add links "Login" (user/login), "Logout" (user/logout) and "Register" (user/register). In admin/structure/block move your new menu to where you need, and apply necessary styling.


PHP Errors with Drupal 8 (Shared Hosting)

Following @Clive's advice, I committed the /vendor and /core directories. The php errors shown in my initial question were resolved, but new, similar php errors appeared. After much trial and error, I discovered the Drupal VM was added some sort of configuration to the Drupal install. Whatever that configuration may be, it did not translate to the server environment. I downloaded a fresh Drupal 8 copy and manually installed it. After I pushed up the fresh files, it worked like a charm.


This module might help Query Parameters To URL.

There's a D8 sandbox: Drupal 8 port

The module seems very useful, maybe it would get more attention if more people used it.


How to fix display problems with CKEditor?

CK Editor supports to manage toolbars. In toolbars you can manage Buttons. See the guide.


How can I disable specific layouts provided by contrib modules via the layout API?

Kind-of. With IPE you could use the patch in https://www.drupal.org/node/2849219.


Performing an HTML substitution from AjaxResponse rather than using a wrapper

So, I used the source, and I found out that Drupal\Core\Ajax\ReplaceCommand calls getRenderedContent(), I found an implementation in CommandWithAttachedAssetsTrait where I saw that it expects an array, as I should have well known. So I ended up with the following calls:

$response
  ->addCommand(new RemoveCommand('label[for^="edit-struttura-input"]'))
  ->addCommand(new ReplaceCommand('input[id^="edit-struttura-input"]', array( $form['struttura-input'] )))
  ->addCommand(new InvokeCommand('#edit-field-next-field-to-edit', 'focus')  )

Note that I removed the wrapper, as suggested by @4k4, but then I had to select on a match on the start of the ID of the element, and to remove the label, since it is added by each new rendering. As a command to get rid of the datepicker I simply moved the focus to the next element to edit, which is very convenient to the user.


How form layout of user login page can be changed Drupal 7 without altering its tpl file ?

Have a look at hook_form_alter. You have to change the #weight property of the form elements.

If you don't know what I'm talking about have a look at the FAPI reference and quick start guide.


Config Entity list_builder controller path throws Route Does Not Exist error

You have somewhere in your code the wrong route.

Probably your route in *.routing.yml is:

entity.my_new_entity.edit_form

But now you are redirecting to

entity.config_entity_id.edit_form

where there is still the placeholder from some example code.


I think you want the References module. At the moment it dosn't have the views limitation on valid values committed but there is an issue with a working patch which should allow you to do what you want.


I would suggest that instead of calling cd within your script, you either set up drush aliases or pass the --root and --uri parameters to the cron request.

/home/myuser/.composer/vendor/bin/drush -v --root=/home/myuser/public_html --uri=fr.mysite.com core-cron

That should make sure that drush is running in the right context.

You can also make sure that drush is running with the php that you would like by setting the DRUSH_PHP environment variable.


Is there a module that can record when and for how long each user logs in for? (Drupal 7)

You are looking for User Visits Advanced module, It have the option to track the hours visited by the users.

  The User Visits Advanced module is a contribute module for the User
  Visits module. It is extremely useful for social networking sites who
  wish to provide their users with statistics about the number of times
  a the users profile page is being viewed and by which other users.

  This module comes with its own database table to store statistics per
  user profile (uid). At cron time, the data from the user_visits table
  is collected, aggregated and stored in the user_visits_adv table. It
  stores

  the total number of visits per uid
  the number of visits of the X past days per uid
  the most recent visitors uids of the past Y hours


Adding a taxonomy term translation changes the original language value!

You need to make sure it is translatable in the language settings.

Go to:

/admin/config/regional/content-language

Make sure that taxonomy term is checked in the custom language settings.  If not, check and save.

Then find the Taxonomy section in the form.  In this section, make sure that your vocabulary and fields you want translatable are checked.  Include the show language on edit option as well

Once you have done that, go to:

http://www.solarwindsmsp.test/admin/structure/taxonomy

And create translations for the vocabulary for each language you want.

Also edit the vocabulary settings and make sure there is a default language specified for new terms.

Next, if you have existing terms, you need to edit the term and set a default language in the dropdown.  E.g. english instead of not specified.

Once you do this, you will get a translate option on the edit / delete dropdown in the list.  Select translate to add additional languages.


including jquery.ui 1.6 directly from theme.info

The correct way to include jQuery UI, from README.txt:

In your module, call the following function:

jquery_ui_add($files);

For example:

jquery_ui_add(array('ui.draggable', 'ui.droppable', 'ui.sortable'));
jquery_ui_add('ui.sortable');  // For a single file


How to put multiple entity fields inline as sub fields?

Have you considered Paragraphs? It allows you to 1) create predefined sets of fields and 2) allows you to add fields that allow you to add those predefined fields. You have the option to restrict the paragraph selection as well as the number you can add.

A closely identical module is Field Collection although their project page suggests moving to Paragraphs instead.

It's not the two dropdowns you're looking for, but allows you to select a type and add as many as you want.


Omega does it this way:

in omega.info

settings[alpha_region_xxx_force] = ''

in `omega/alpha/includes/theme-settings-structure.inc

$form['alpha_settings']['structure'][$section][$zone]['regions'][$region]['alpha_region_' . $region . '_force'] = array(
  '#type' => 'checkbox',
  '#title' => t('Force this region to be rendered'),
  '#description' => t('Enabling this will always render this region, even if it is empty.'),
  '#default_value' => $item['force'],
);

Call alpha_alpha_page_structure_alter() in alpha_page_alter()

#omega/alpha/template.php
foreach ($theme->regions as $region => $item) {
    if (($item['force'] || !empty($vars[$region]))) {
      $temporary[$item['section']][$item['zone']][$region] = !empty($vars[$region]) ? $vars[$region] : array();
...

this way your code should be:

function THEMENAME_page_alter(&$page) {
    $regions = system_region_list($GLOBALS['theme'], REGIONS_ALL);
    foreach ($regions as $region => $name) {
        $page[$region] = !empty($page[$region]) ? $page[$region] : array();
    }
}


I am not certain if I understand what you are asking here, but  this question is bound to come up on searches for anyone trying to figure out contextual filters.  The information you present leads to several questions and comments:

It is unclear what your contextual filter will due without knowing more about the view fields, setting and path definition you have given it.   Also, is this the contextual filter screen for the page or block?

To define the location for the argument in the path for a page view you place a % character at the location in the path definition for the view. eg. in Example.com/content/%/items, any URL value matching the path pattern will generate a view with the value of the % passed on to the contextual filter. IN this way you have a view definition performing generalized filters as defined in the first column of the view definition form page and additional filtering as defined in the third column under the 'Advanced' option.  For a page view you complete the requirements for the contextual filter under the heading "When the filter value IS available or a default is provided"

For a block you must complete the section "When the filter value is NOT available" and select "Provide default value".  IN the drop down list you can tell the filter whether it is intercepting a content, taxonomy or user id node number or you can tell it to select a raw value from the URL and which position in the string it is.  In the example I gave above the context value we are looking for (the % sign) is in the second position.

However the value is passed, the context filter will further filter the view as defined on the view form for that page or block.


Field formatter to display base 64 data image

Try this:

use Drupal\Component\Render\FormattableMarkup;

$src = $item->value;
$image = new FormattableMarkup('<img src=":src"/>', [':src' => $src]);
$elements[$delta] = [
  '#markup' => $image,
];


ABT term reference field hidden in Node View

Make sure to assign "Allow users to view ABT terms on node page." permission to desired roles.


how to put a submit button with a pre-defined submit function by calling drupal_render?

Are you returning those $render_elem from your form function, when drupal_get_form calls that form id callback? Because i see you call drupal_render_children, but drupal need to know about it in form of form api array. drupal_get_form expecting you return from your form_id function form api array of form elements, so it can do some operation like checking, if current request is POST and contains form_id of your form and some name of submit button.

EDIT: Try add all submit buttons to your form array, but set their property #printed => true, so they won't be rendered, but drupal will be notified about those buttons and can run your submit functions.


Drupal 301 redirects for matching paths without .htaccess

Probably the Global Redirect module suits your needs.

You may have to implement the timestamp feature as a new token with a custom module.


How to wrap body text around image for drupal 8

Don't edit css files in a contrib theme, because the changes will be overwritten when updating the theme. Create a subtheme and add a library with your own css file, see https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme


How to give a user the rights to "clear cache"

You may try UI Cache Clear.

Project page says:

  Clears specific cache bin without flushing the whole site cache.
  Allows to clear cache without full administrator permissions.
  Provides setting to clear current page cache automatically when    clearing Block, Views or Panels cache.
  Admin menu and Shortcut integration