String Overrides is not overriding the "Read more" string

Might need some tweaking, but you can change the text in hook_preprocess_node(). If you set it to "Read more" you can override it with stringoverrides after, or change it to what you want at once.

In your themes template.php, add:

/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_process_node(&$vars) {
  // Change default text of the read more link.
  if (isset($vars['links']['node']['#links']['node-readmore'])) {
    $vars['links']['node']['#links']['node-readmore']['title'] = t('Read more');
  }
}

Related modules:
http://drupal.org/project/readmorecontrol
http://drupal.org/project/read_more
http://drupal.org/project/linkoutreadmore


Have you looked at Elysia Cron? I have it installed on all my sites as it allows finer control over how cron is run and has "Protection from external cron calling by cron_key or allowed host list"


How to store Views templates with a module instead of a theme

This took me a while to figure out as well. The following code should be placed in your .module file (the code assumes your module is called "NAME")

/**
* Implements hook_views_api().
*
* Enabling using templates inside module
*/
function NAME_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'NAME'),
    'template path' => drupal_get_path('module', 'NAME'),
  );
}

This will tell Views to look in the root directory of your module. I personally am a fan of adding a subdirectory to the module to hold template files. To do this append the directory name to the end of the template path, eg:

'template path' => drupal_get_path('module', 'NAME') . '/templates',


This can be achieved using exposed filters feature of the Views module. Here is an article explaining this process in detail.

http://www.bryanbraun.com/2013/08/06/drupal-tutorials-exposed-filters-with-views

You would also need the Better Exposed Filters(BEF) module for displaying the filters as links.


Why are my views arguments not being handled properly?

Do you have a page display for your hightlights1 view with a path of highlights1/%/% set up?

Edit the path of your view's page display and ensure it's highlights1/%/% -- the percent signs each represent an argument for views to collect from the path and use.


Why are media files used in zero places not deleted?

I've come across this before with webform submission files and the site getting confused about the path.

If you actually try and view 1 of the files in the list does it exist? As you may find it doesn't exist but drupal has kept a record of the file in the database. When drupal tries to do is file tidy up on cron run it's erroring because the file its trying to delete doesn't exist (But its not then smart enough to delete the row out of the database)

The safest solution would be to manually recreate these files in the position /admin/content/files thinks it should exist and then rerun the cron and it should delete your test file and the row in the database


Try the jQuery Map Hilight module

  It enables the simple addition of mouseover highlighting of hotspots to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.

Features

provides simple interactive graphics via HTML image maps (no flash
required).
easy to use: either select the 'highlight all image maps' default
setting or simply add class="jq_maphilight" to the  tag of any
specific image map you wish to highlight.
no jquery or javascript knowledge required: plugin configuration is
handled via an admin/settings screen rather than having to enter
jquery code.
fully configurable: options for fill, fill color, fill opacity,
outline, outline color, outline opacity, outline thickness, as well
as a fade effect.
per image map settings: add image map specific options with an
additional class.


I think you can achieve that by one of the  following modules

1)Menu Position

  Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

2) Menu Trail By Path

  Menu Trail By Path sets the active-trail on menu items according to the current url.

  For example if you are at yoursite.com/blog/category1/article1
  Menu Items with these paths will get the active-trail class on them and expand accordingly.

  blog

  blog/category1

  blog/category1/article1


Create relation between two select list for Hierarchical select option

Hope this will help you

function mymodule_form_alter(&$form, &$form_state, $form_id){

//put your form id
if ($form_id == 'two_state_node_form')  {

    $options_first = dynamic_add_options();

   $value_dropdown_first = isset($form_state['triggering_element']['#value']) ? $form_state['triggering_element']['#value'] : key($options_first);

    $form['#validated'] = TRUE;
    //put your first field name
    $form['field_select_list_1']['und']['#options'] = $options_first;
    $form['field_select_list_1']['und']['#default_value'] = $value_dropdown_first;
    $form['field_select_list_1']['und']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'dynamic_ajax_callback',
    'wrapper' => 'dropdown_second_replace',
 );
    //put your secon field name
  $form['field_select_list_2']['und']['#prefix'] = '
';
  $form['field_select_list_2']['und']['#suffix'] = '
';
  $form['field_select_list_2']['und']['#options'] = dynamic_second_dropdown_options($value_dropdown_first);
  $form['field_select_list_2']['und']['#default_value'] = isset($form_state['values']['field_select_list_2']) ? $form_state['values']['field_select_list_2'] : '';
 }
}

function dynamic_ajax_callback($form, $form_state) {

    return $form['field_select_list_2'];
}

function dynamic_add_options() {
  return array(
        'None' => 'None',
        'Nokia' => 'Nokia',
        'Samsung' => 'Samsung',
        'HTC' => 'HTC',
        'Apple' => 'Apple'
    );
   return $options;
}

function dynamic_second_dropdown_options($key = '') {
    $options = array(
        'None' => array(
            'None' => 'none',
             ),
        'Nokia' => array(
            'Lumia 520' => 'Lumia 520',
            'Lumia 620' => 'Lumia 620'
        ),
        'Samsung' => array(
            'Galaxy S3' => 'Galaxy S3',
            'Galaxy S4' => 'Galaxy S4'
        ),
        'HTC' => array(
            'Hero' => 'Hero',//trancate the code
            'One' => 'One'
        ),
        'Apple' => array(
            'iPhone 4' => 'iPhone 4',
            'iPhone 5' => 'iPhone 5'
        ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

this is demo for you demo


In Rules, how can I use a set the value of a taxonomy term reference field to multiple values?

As it turns out, this is actually fairly easy to do in Rules.  By updating to the latest version of the Entity API (rc3-- I was stuck on rc1 due to a different bug that I resolved earlier today) with Rules 2.1, I was able to do this in the following way:

Choose the action "Set a data value".
Choose the taxonomy term reference field to set.
Control-click to select the taxonomy terms to add.

That's all there is to it, but there is one potential gotcha: these values didn't always save correctly for me.  This may be because I opened multiple tabs in Firefox and tried to save many different rules at once; for whatever reason, sometimes only one of the two values got saved.  I fixed this by simply checking all the values again manually and re-saving them until the values stuck.


Boosted Varnish for Drupal - what to do with "Control: no-cache" headers?

drupal_add_http_header() in your own module will allow you to override Drupal's headers.

Not that it's needed - your headers will only be set to no-cache when you hit Drupal directly. Not for boosted statics. It is a good thing. You want to keep HTML from boost in varnish, after all, not the one generated directly.

I'm proposing to leave it be. Files from Boost cache will not generate these headers, so will be cacheable for varnish. You will only skip caching pages generated on direct Drupal hits. But you want to skip them. They may contain messages, for example. Boost does not cache when there are errors and messages, so leaving no-cache in Drupal will let you to use this behavior and make varnish respect it.


URL alias in view with subfolder of the Drupal installation

Open your root .htaccess file and uncomment RewriteBase /

This should set the new root for your Drupal installation when operating out of a sub folder. This is usually required when enabling Clean URL's.


Only one of my site node's doesn't print it's alias

assuming you are using Pathauto to accomplish this, try:

check the settings under /admin/config/search/path/settings and make sure the Update action is set to Create a new alias, Delete the old alias
edit the node, and make sure the 'generate automatic URL alias' is checked and save the node again - this should reset the alias for the node


Node title inside layout (Layout Discovery + Field Layout)

I wasn't able to get variables inside layouts due to this bug https://www.drupal.org/project/drupal/issues/2861840
Drupal 8.5 fixed the problem.
Now, inside mytheme.theme if I put this:

function MYTHEME_preprocess_layout(&$variables) {
  $request     = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title       = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
   $variables['node_title'] = $title;
}

I'm able to use {{ node_title }} inside layouts.


Theme Image Style for image located in module directory

I just came across this and had to write the code to handle this.

This effectively clones theme_image_style() to create image derivatives during execution of the page request. Generation bypasses the security issues that would otherwise normally trigger a 404, but that also means a slower page the first time the page is visited.

I am only using the public file schema, but I would expect this to fail with the private file schema based styles.

    /**
     * Implements hook_theme().
     */
    function MODULE_theme() {
      return array(
        'remote_image_style' => array(
          'variables' => array(
            'style_name' => NULL,
            'path' => NULL,
            'width' => NULL,
            'height' => NULL,
            'alt' => '',
            'title' => NULL,
            'attributes' => array(),
          ),
        ),
      );
    }

    /**
     * Returns HTML for an image using a specific image style.
     *
     * Clones theme_image_style() with the additional step of forcing the creation
     * of the derivative to bypass any 404 issues.
     */
    function theme_remote_image_style($variables) {
      // Determine the dimensions of the styled image.
      $dimensions = array(
        'width' => $variables['width'],
        'height' => $variables['height'],
      );
      image_style_transform_dimensions($variables['style_name'], $dimensions);

      $variables['width'] = $dimensions['width'];
      $variables['height'] = $dimensions['height'];

      $image_style_dest_path = image_style_path($variables['style_name'], $variables['path']);
      if (!file_exists($image_style_dest_path)) {
        $style = image_style_load($variables['style_name']);
        image_style_create_derivative($style, $variables['path'], $image_style_dest_path);
      }
      $variables['path'] = file_create_url($image_style_dest_path);
      return theme('image', $variables);
    }


Drush contrib modules not available if executed externally

The solution is to pass the environment variable $HOME to check_output, in this case /home/admin:

check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True, env={'HOME': "/home/admin"})

This force the /home/admin/.drush directory to be read. If everything is fine this command:

drush ev 'print(drush_server_home());'

should return /home/admin. If drush_server_home() returns an empty string, contrib modules installed inside .drush on home directory will not be available.

Ensure to install contrib modules with the same user controlling the /home/admin directory.

Read the documentation of the language you're using to pass the $HOME variable on command execution.


Why is arg() failing to get the router object on pages with aliased URLs?

arg() is intended to work with system paths. if you are viewing you node page with system path (node/#) or by alias then arg(1) must return nid of the node.

How are you defining your alias? Are you using path module interface?
Perhaps the alias is a result of a custom menu hook by some module, rendering a node by some arbitrary logic.

I would also like to share a hack to overcome this issue if you get alias in arg() and this alias is truly defined by path module directly on node then drupal_lookup_path('source', 'your/node/alias') will return the system path of your node e.g. node/#


How to add fields wrapper in field preprocess

Based on the question I'm assuming you are asking for D7 ...

You should use a "container" for this. Something like this:

$element = $vars['element'];
if($vars['element']['#field_name'] == 'field_example') {
  foreach($vars['items'] as $key => $item) {
    // Do whatever you want...
  }
  $vars['items']['#type'] = 'container';
  $vars['items']['#attributes'] = array(
    'id' => "some-id",
    'class' => array(
      'some-class',
    ),
  );
}

See this other question for more details. Also, if you want to get a little more fancy you can look at using theme wrappers.


Get the fields from a reference entity (content type) in a Paragraph field

The referenced entity is not built yet, so you can't access the formatted field content.

You can get the field value from the database by using the paragraph object:

{{ paragraph.field_testimonial.entity.field_testimonial_titel.value }}

This is unformatted, which might work for a title field.

If you want a formatted output better use a custom view mode for the referenced entity to configure the fields, or in this case one field, if this is all you want to display.


The entity passed in the $form_object is simply ignored, as the whole $form_object thing - it is used only to determine the form id. You may add entity to the form_state, but with the original drupal form generation it is ignored too.

To set the node edit translation you need to set $form_state->set('langcode', $langcode);

The full thing emulating drupal's node edit form looks like so:

public function customEdit($type = 'node', $id, $langcode) {
    $request = \Drupal::request();
    $entity = Node::load($id);
    $form_object = \Drupal::entityManager()->getFormObject('node', 'edit')->setEntity($entity);

    // Add the form and form_state to trick the getArguments method of the
    // controller resolver.
    $form_state = new FormState();
    $request->attributes->set('form', array());
    $request->attributes->set('form_state', $form_state);

    $args = \Drupal::service('controller_resolver')->getArguments($request, array($form_object, 'buildForm'));

    $request->attributes->remove('form');
    $request->attributes->remove('form_state');

    // Remove $form and $form_state from the arguments, and re-index them.
    unset($args[0], $args[1]);
    $form_state->addBuildInfo('args', array_values($args));

    $form_state->set('langcode', $langcode);

    $render_array = \Drupal::service('form_builder')->buildForm($form_object, $form_state);

    return $render_array;
  }

The answer is actual for the Drupal 8 beta 2, I'm sure the ability to edit different language node versions would be fixed before release.


I like to use EntityAPI module for working with fields. You don't need to worry about some key exists or not. here is an example:

$entityWrapper = entity_metadata_wrapper('ENTITY_TYPE (eg. node, user..)', ENTITY_KEY_OR_ENTITY);

$protectionFieldValue = $entityWrapper->field_protection->value();

if (null != $protectionFieldValue /* put your condition */) {
  form_set_error('from', t("Protected !!!"));
  return;
}

or here is a way without an EntityAPI:

if (isset($act->field_protection['und']) && ($is_protected  = (int)$act->field_protection['und']['0']['value'])) {
    if ($is_protected == 1) {
      form_set_error('from', t("Protected !!!"));
      return;
    }
}


How do I force Breadcrumb to use a menu other than Main Menu?

Menu Breadcrumb

By default, Drupal will use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.

As an added bonus, it also allows you to Append the page title to the breadcrumb (either as a clickable url or not) and hide the breadcrumb if it only contains the link to the front page.


In Tinymce editor, how to set default font family style in select list?

You can try execCommand to make that work.

  Executes a specific command on the currently active editor.

Try this.

editor.execCommand("fontName", false, "Arial");

Another way is to use the content_css configuration option and name an own css file where you can overwrite the editors defaults (the content.css you were recently looking for). In your init function use something like

content_css: "http://sitename/css/my_tiny_styles.css",

and in my_tiny_styles.css or whatever file you choose you use

font-family: myfont1, myfont2, sans-serif;


Answering my own question:

In a custom module (or in your template.php):

1) Create a helper function:

// Helper function used to return the children of a specific menu item
function MODULENAME_menu_subtree_data($item, $tree) {
    foreach ($tree as $cid => $data) {
        if ($item['mlid'] == $data['link']['mlid']) {
            return array($cid => $data);
        }
        if ($data['below']) {
            $return = MODULENAME_menu_subtree_data($item, $data['below']);
            if ($return) {
                return $return;
            }
        }
    }
    return FALSE;
}

2) Create a reusable output function:

// Return all the menu items for the parent of the given page.
// $menuParent = menu_get_active_trail(); Needs to be called on the requesting page
function MODULENAME_parent_menu($menuParent) {
    // Get active trail to current page
    $menuParent = menu_get_active_trail();
    // Pop off last item of trail as that is the current page
    $menuParentPop = array_pop($menuParent);
    // Store the new last item in the trail as this is the parent menu item
    $menuParent = end($menuParent);
    // Set the depth to which we want to return the parent menu tree
    $max_depth = $menuParent['depth'] +1;
    $mlid = $menuParent['mlid'];
    $menu_item = menu_link_load($mlid);
    $tree = MODULENAME_menu_subtree_data($menu_item, menu_tree_all_data($menu_item['menu_name'], $link = NULL, $max_depth));
    $tree = array_shift($tree);
    $tree_array = menu_tree_output($tree['below']);
    return drupal_render($tree_array);
}

3) Place this code in your node.tpl.php file wherever you want the menu to be rendered:

<?php
// Print all the menu items for the parent of the current page.
print MODULENAME_parent_menu($menuParent = menu_get_active_trail());
?>

Notes:
- Replace MODULENAME with your custom module name or theme name if in template.php
- You can adjust the "depth" of what's returned by adjusting the $max_depth variable to suite your needs. 0 = show everything.

Totally welcome any way to improve this!


Change the setting 'Who can register accounts?' to 'Administrators only' at http://yoursite.com/admin/config/people/accounts


Displaying SQL-table as a paginated list

The call to db_select() and the following calls to methods are wrong.

The second parameter of db_select() is a table alias, which should then used when referring to the fields used by the query.
the parameters passed to the fields() is wrong; see the following snippet for an example of how the call to db_select() should be.

$result = db_select('file_usage', 'f')
   ->fields('f', array('module', 'type', 'id', 'count'))
   ->condition('fid', $file->fid)
   ->condition('count', 0, '>')
   ->execute();

Your call to db_select() should be re-written as:

$query = db_select('users', 'u')
  ->fields('u', array('name', 'uid'))
  ->orderBy('created', 'DESC')
  ->limit(20)
  ->extend('PagerDefault');


How can i list all display suite layout templates used

I think he's asking to get an overview of of which bundle / view mode uses which template file.

That's currently not easy to fine in the backend - however this is something we want to add add some place.

The fastest way to get an overview is to go to the database and look into the 'ds_layout_settings' table. The 'layout' column holds the machine name of the template used.


You need Views.

With Views you can make highly customizable lists of content. I suggest you use Drupal 7 and Views 3, because its easier to make a View in it than in the version 2. If you are using Drupal 6 try Simpleviews, which will let you create Views very easily too.

I make this suggestions because as a newcomer the full Views interface can be a bit daunting. Have a play around and good luck!


Don't understand why Kevin's answer hasn't been accepted yet, here you go with a snip of the permissions that need to be enabled.

Have a look at this module- Administer Users by Role
These are the new permissions that come with the module -

NEW PERMISSIONS
1 )Access the users overview page
  See the list of users at admin/people.  Only users that can be edited are shown.

2) Create new users
  Create users, at admin/people/create.

3) Edit users with no custom roles
  Allows editing of any authenticated user that has no custom roles set.

4) Edit users with role XXX
  Allows editing of any authenticated user with the specified role.
  To edit a user with multiple roles, the sub-admin must have permission to
  edit ALL of those roles.  ("Edit users with no custom roles" is NOT needed.)

-The permission for cancel work exactly the same as those for edit.


Is there a solution which could keep information about actions and updating of data on the site?

By using the Message module (which already has a beta version for D8), you can create your own custom "Events logging" (to register things that happened in a site).

A great sample of this you can find in (the D7 version of) Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

The Message module is an amazing module, though there is not a lot of documentation about it. It is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and (only for D7 for now, not yet for D8) Rules.

Additional info

For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation. And/or checkout the video introduction "Your Drupal site can talk" (if you want you can fast forward to about 03:30 where it really starts).


Hybridauth does remove the need of password, so I probably can remove username and password fields from the user login forms through the hooks


How to check the first item/content on Drupal View

Have you tried to print other stuff of the loop variable, maybe {{ loop.index }}, did this work? You then could if-request this. As far as I remember loop.index worked fine in Drupal.

Next thing you can try is to iterate over the keys and if-request the key for your logic. Pretty much the same as loop.index.

{% for key, items in related_content.entity.field_content_items %}
  {% if key == 0 %}

Last resort would be to target related_content.entity.field_content_items[0] directly.

But I think the first two suggestions should give you at least one opportunity to do what you want.

Thanks for the clarification. Views custom text only. OK, in that case consider to use 2 views (or just 2 displays of the same view) as outlined here https://drupal.stackexchange.com/a/104608. Then you'd attach the first view (or display) - which is limited to display only 1 row - before your second view (there must be an attachment option somewhere) and your second view then should be configured to have an offset of 1.


Services module is easy to use, but it can be tricky to configure especially if you are new to the concept. So,  I am going to post the screenshots to make configuration of Services modules easy for "Drupal Answers" users.

Following is the version of Services module installed on my machine:

Create an endpoint called 'rest' as shown below:

Select the type of server and endpoint path:

Select the list of resources that you want to enable and specify aliases:

Select the response formatters and request parsers that you want to enable:

You can test your configuration as shown below:

You can get the list of all nodes as below:

And specific node as:

Following are the excellent examples scripts provided by MichaelCole here http://drupal.org/node/910598#comment-4677738 to create nodes from any external PHP application.

I am duplicating his code for completeness of this answer.

//--------------login to the server------------------------
$service_url = 'http://example.dev/rest/user/login.xml'; // .xml asks for xml data in response
$post_data = array(
    'username' => 'test',
    'password' => 'test',
);
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "LOGIN RESPONSE:\n";
var_dump($response);

// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name . '=' . $xml->sessid;
// print "SESSION_COOKIE: $session_cookie";

file_put_contents('session_cookie.txt', $session_cookie);

//----------------create a node -------------------------------

$node_data = array(
    'type' => 'ct_metadata_core',
    'title' => 'test layer',
    'field_core_lat_n[und][0]' => array('value' => '90'),
    'field_core_lat_s[und][0]' => array('value' => '-90'),
    'field_core_long_e[und][0]' => array('value' => '180'),
    'field_core_long_w[und][0]' => array('value' => '-180'),
    'field_core_description[und][0]' => array('value' => 'National Data Buoy Center'),
    'field_core_originator[und][0]' => array('value' => 'NDBC'),
    'field_core_url[und][0]' => array('url' => 'http://www.ndbc.noaa.gov/kml/marineobs_as_kml.php?sort=pgm'),
    'field_cont_res_name_org[und][0]' => array('value' => 'test'),

);

$service_url = 'http://example.dev/rest/node'; // .xml asks for xml data in response
$session_cookie = file_get_contents('session_cookie.txt');

$node_data = http_build_query($node_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session

curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "CREATE NODE RESPONSE:\n";
var_dump($response);

//----------------logout from the server-------------------------

$service_url = 'http://example.dev/rest/user/logout';
$session_cookie = file_get_contents('session_cookie.txt');

// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // have curl_exec return a string

curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
curl_setopt($curl, CURLOPT_POST, true);             // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, ""); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
print "LOGOUT RESPONSE:\n";
var_dump($response);


We need to use in D7 :

$form_state['cache'] = TRUE;
$form_state['no_cache'] = FALSE;

instead of

$form['$cache']=TRUE in D6


How do you clear cache on a block when node of certain bundle added or updated?

You can easily create a custom cache tag related to properties on nodes by invalidating it yourself.

Based on this article:
https://www.drupal.org/project/views_custom_cache_tag

I created a custom tag for each node type, that is invalidated on node update:

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function mymodule_node_presave(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function mymodule_node_delete(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

Then in my build array for my block I added:

$build['#cache'] = [
  'tags' => [
    'node_type:article',
    'node_type:video'
  ],
];

This means this block will only refresh when nodes that are of type "article" or "video" are created or updated.

You could do the same process for any property on an entity, not just bundle.  For example, if you want a list of nodes to stay cached unless the nodes within it change their url alias, you could add code that checks if the url aliases is changing and then invalidate your tag node:123:url_alias".


Redirecting a page after form submission

Beside the drupal_goto() function there's also the 'redirect' property in the $form_state

See https://api.drupal.org/comment/18139#comment-18139


"Save Configuration" in Drupal 7 Module not visible

Sounds very much like a custom module is hiding the module save button to stop people adding/changing things. I've had the misfortune of inheriting sites with these sort of "security features" before too.

If you do have any custom modules installed. the simplest thing you can do to test is get Drush installed, run drush dis CUSTOM_MODULE and check to see if the button comes back. Then you'll know if it's the custom module's fault at least. You can also disable them manually in the system table but you should only do that if you really know what you're doing.

The upshot of that is you can also use Drush to install the other modules outside of the UI, so even if that's not the problem you'll still be able to install new modules.

Also, to find out if a change to core files is responsible for the problem, grab the Hacked module and run a report. If you install the Diff module along with it you'll get a side-by-side diff of exactly what has changed in core/contrib modules.


Two Factor Authentication for admin/OAuth2 for REST API

There's no public plugin for this as far as I'm aware of (note, I'm author of the drupal.org TFA module).

I do think it's a quick write, depending somewhat on how your REST API is authenticating the request and particularly whether you create a Drupal session and invoke the user login process.

You can allow a REST call to skip the TFA process very similar to how the TfaTrustedBrowser works. The loginAllowed() method on this plugin (implementing TfaLoginPluginInterface) will be invoked and you can check the request headers/global scope (user UID) and return TRUE to tell TFA to not block the login action.


How to put description on top of the input box, for a new field added to comment form?

You need to add a description field to your array:

$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Your Title'),
    '#description' => t('The paragraph you would like to put a comment on (enter 0 if you want to put the comment on the entire article'),
    ...
);

This way the explanation will show up under the field.


I'm using CiviContribute and need CAPTCHA

You should probably be asking this on the CiviCRM stack.

You can set a catpcha on a Profile. So check which Profiles you have set for the Contribution page. Then edit the Advanced settings for that Profile where you can set captcha.

Check answer here too


Domain Access: Edit admin/domain/content/ display settings, filters etc

Domain Access does not provide a view like you want.
You could try the Admin Views module which overrides the standard content admin page with a view.
Also, Domain Views module which integrates domain access with views.


Loading Personal contact form and access denied

You need to check for flood before rendering the contact form

global $user;
// Check if flood control has been activated for sending e-mails.
$limit = variable_get('contact_threshold_limit', 5);
$window = variable_get('contact_threshold_window', 3600);
if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms')) {
// Don't display forms
}
else {
  $recipient = user_load(array('uid' => $fptr->uid));
  $output .= drupal_render(drupal_get_form(
  'contact_personal_form', $recipient));
}


Webform Mail not arriving at gmail address

From the link in your bounceback message:

"A message might be blocked if it contains suspicious-looking or spammy text or if the sending IP has had a history of sending unsolicited messages."

Either one of these possibilities might be the issue.  To rule out "suspicious-looking or spammy text" you should look at the emails your webform generates.  Is there any text they have in common that might be triggering gmail's spam rules?  If you send such a message to a gmail address manually, do you get the same bounceback?

The more likely explanation is that the sending IP has had a history of sending unsolicited messages.  This is especially likely if you're running in a shared web hosting environment.  If this is the problem, there's likely little you can do about it, other than asking your host to move your account to a different server.


Prevent sites from receiving modules installed by other sites in a multi-site instance

Yes, the multisite system can do that out of the box. From the Site-specific modules and themes section of the multisite docs:

Each site configuration can have its own site-specific modules and themes in addition to those installed in the standard 'modules' and 'themes' directories. To use site-specific modules or themes, simply create a 'modules' or 'themes' directory within the site configuration directory. For example, if sub.example.com has a custom theme and a custom module that should not be accessible to other sites, the setup would look like this:
sites/sub.example.com/settings.php sites/sub.example.com/themes/custom_themesites/sub.example.com/modules/custom_module

So just make sure you don't put modules that shouldn't be shared in /sites/all/modules; put them in /sites/SITE/modules instead.

Can site A can "block" (for lack of a better term) a module installed by site B, in which site B installs to sites/all/modules?

You could implement hook_system_info_alter in site-exclusive modules to prevent certain ones from ever being displayed to the user on those sites, but as there's no record anywhere of what site downloaded/installed a module to /sites/all/modules, you'd have to keep those modules up to date manually. Unless you supplement that with an API exposed from each site that let each other site know what it had installed and what should/shouldn't be available to install.

Is best practice to configure specific modules per site rather than trying to prevent the transposition?

I think it's fair to say an inclusive rather than exclusive approach is better practice here, any other approach is a bit awkward. It gets more complicated the more automated/robust you want an exclusive approach to be, whereas doing it the other way round just works.


How do I migrate the content of a SQL table?

You can achieve it using the Feeds module.

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.
  Import or aggregate CSV files
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files

Reference

Importing data from a comma separated value (CSV) file into one multi-value field.
Importing content with the feeds module


There's no out of the box way to display a field in twig with two different formatters.  But it can be done with a hook in a custom module.

You can repurpose a field in hook_entity_view or hook_ENTITY_TYPE_view().

Here's an example:

function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article' && $view_mode == 'teaser') {
    $settings = [
      'type' => 'pdf_special_formatter',
      'settings' => $build['field_pdf']['#items']->getSettings(),
    ];
    $build['pdf_alternate_display'] = $build['field_pdf']['#items']->view($settings);

  }
}

Note that the settings may need to be altered before sending to another field formatter.  You'll have to look at that field formatter for the required settings.


You need to tell Drupal about your files somehow.

You could write a script yourself.

Another approach would be to use the archive upload of File entity, but you won't be able to upload hundreds of them in a single archive either, the file will simply get too big.

Maybe there is also a module for this, but it's likely not available yet for Drupal 8.


All pages showing "Access Denied" if not logged in

When you are logged in as admin, go to /admin/people/permissions and make sure that anonymous users are given View published content permissions.

If you are new to Drupal, you should probably stay away from the database tables for now.


How can I show the flagging field edit form on a node?

Here's the code I ended up using:
/**
 * Implements hook_node_view() for MYMODULE.
 */
function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($node->getType() == 'MY_CONTENT_YTPE') {
    if ($display->getComponent('my_flagging_form')) {
      $flag = \Drupal::service('flag')->getFlagById('MY_FLAG');
      $flagging_entity = \Drupal::service('flag')->getFlagging($flag, $node);
      $form = \Drupal::service('entity.manager')
        ->getFormObject('flagging', 'edit')
        ->setEntity($flagging_entity);
      $build['my_flagging_form'] = \Drupal::formBuilder()->getForm($form);
    }
  }
}

/**
 * Implements hook_entity_extra_field_info() for MYMODULE.
 *
 * Https://www.webomelette.com/creating-pseudo-fields-drupal-8
 */
function MYMODULE_entity_extra_field_info() {
  $extra = [];

  $extra['node'][NodeType::load('MY_CONTENT_TYPE')->Id()]['display']['my_flagging_form'] = [
    'label' => t('My flagging edit form'),
    'description' => t('This shows the my flagging edit form.'),
    'weight' => 100,
    'visible' => TRUE,
  ];

  return $extra;
}

For more details, see this question.


Be careful with the https://www.drupal.org/project/entity_clone module. Because it may happen that you've made a ton of product clones and then decided to edit, let say, price of some variation on a clone or a "parent" product. The price will change everywhere. The same with deletion of variation. Moreover, the same with deletion of any of the clones or the "parent". All variations will be deleted everywhere. But that's not the end. If you try to delete any of variation-less clones you'd get fatal error. So, to delete this clone you need to save at least one variation.

That's because variations are entities which can be referenced by multiple products. Read more: https://www.drupal.org/project/commerce/issues/2941524

So, as I understand you need cloning for cutting off the time spent on variations creation, which is quite tedious work, I'd say. If so, you may try the Commerce Bulk module.


Module for getting what is visible from user's webcam

I don't think there is exactly what you want at the moment, but the following module might help you on your way:

Webcam field - This is still in development

  Webcam field provides dynamically updating webcam image fields. This
  module is compatible with Colorbox.

Videochat - Has no recommended release, although seems to have a full 3.6 version

  The Video Chat module adds a fully hosted free video chat to a Drupal
  website. The chat application and video hosting are courtesy of
  Camamba and ad-supported. We hope it provides an alternative to all
  the payware chat modules out there.

Media: Webcam - This is in beta

  This project (still under active development) will add a Webcam
  capture tool for video and images to FileField. Video requires a Red5
  or Flash Media server to also be available; documentation for this
  coming soon enough.

Video conference - This requires some further set up of server components, but if you want live video streaming I should imagine you're aware that you will most likely need a RTMP protocol set up.

  VideoWhisper Video Conference is a modern web based multiple way video
  chat and real time file sharing tool. It can be used stand alone or
  integrated as extra feature to existing sites. Internet based video
  conference software is great for bringing physically distant people
  together in meetings, trainings, conferences, live events, recruiting,
  consultations, coaching and of course casual community chat.

Paid solution

AVChat

This comes at a price of $285 plus $49 for the Drupal module


As Clive said there is almost certainly no situation that CKeditor  can validly edit/create an html head element. Since link must be a child of a head element this means that CKEditor cannot create a valid link element.

That being said there is a way to add a stylesheet the the CKEditor. You will have to allow JavaScript in whatever filter you are using (so use with caution) and then insert a script like this:

<script>
  (function($) {
    $('head').apend("<link rel='stylesheet' href='my/added/stylesheet.css'>");
  }(jQuery))
</script>

Or if you don't want to use jQuery:

<script>
  var element = document.createElement("link");
  element.setAttribute("rel", "stylesheet");
  element.setAttribute("href", "/my/added/stylesheet.css");
  document.getElementsByTagName("head")[0].appendChild(element);
</script>


Saving and retrieving EntityAutocomplete value

I was able to resolve the issue by loading the entity first like so

$menu = \Drupal::entityTypeManager()->getStorage('menu')->load($this->configuration['menu']);
    $form['menu'] = [
    '#type'          => 'entity_autocomplete',
    '#target_type'   => 'menu',
    '#default_value' => $menu,
];

The value of $this->configuration['menu'] was only the machine name, not the actual entity. So the entity had to be loaded and stored in a variable first.


Using Contextual Filter to Filter "Entity Selection" on Node Edit won't pull Raw Value From URL

Try Content ID from URL instead of the Raw Value.


Once you have uploaded a file you must be having file object so use file_delete(stdClass $file, $force = FALSE) to delete the file.


Based on your code, I believe you are working on eCommerce website.

I think you need to change your target value to:

  'field_dimensions:length', 'field_dimensions:width', 'field_dimensions:height', 'field_dimensions:unit','field_weight:weight','field_weight:unit'


By default, EntityFieldQuery checks the currently logged-in user has the permission to access the queried entities. This is could be undesired, especially when the queried entity is not shown to the users, for example when a module just needs to get a list of entities to delete them.

To avoid EntityFieldQuery checks the currently logged-in user has the permission to access the entity, you need to use the following method:

addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT') for Drupal 7.15 or higher version
addMetaData('account', user_load(1)) for previous versions

Assuming you are using any version higher than 7.15, you code should be the following one.

query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'xxxxx')
  ->fieldCondition('xxx_module','tid', $tid,'=')
  ->age(FIELD_LOAD_CURRENT)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
->execute();

There could be a module that alter the query done from EntityFieldQuery and doesn't respect that tag; in that case, the query could still not return an entity revision that is not published.


Featurize user roles and permissions can't update

Since production hasn't yet been released and is still under development, I took a risk of mysqldump the drupal.role table and then importing them on prod, which fixed the issue.

LongBoardNode's suggestion of editing the RID on dev would have probably been a better idea,


what you want is hook_menu:
  function pushnotifications_menu() {
    $items['admin/config/services/push_notifications/stats'] = array(
      'page callback' => 'yourverycustomcallbackforpushnotfiers_abc_view',
    );
    return $items;
  }

  function yourverycustomcallbackforpushnotfiers_abc_view($ghi = 0, $jkl = '') {
    // all your logic here
  }

btw: DO NOT DO THIS!!:
$id = $_GET['id'];
Sse drupal_get_query_parameters() instead, if you really have to fiddle with it directly. Otherwise use $args.


How to add subtitle for menu items in Nice menu in Drupal 7

Try OM Maximenu module

  "Maximize your main navigation by adding text, images, videos,
  slideshow, tabs, menu blocks, user info ..."

  That is now possible by using OM Maximenu which can create menus with
  all other module blocks you want as attachments, modules like views,
  slideshow, menu, user, nice menus, quicktabs, and custom blocks with
  tables, lists, images, videos, etc.

Here a great list of menu 7 Mega Menu modules for Drupal


Mailchimp programatic subscription and updates of existing users

The key in the array can be MERGEX (where Xth field number in MailChimp) or whatever custom tag name you've set in MailChimp (it shows up as *|TAGNAME|*" in MailChimp field settings) . The MailChimp dropdown user fields aren't like Drupal's (with select fields containing a key/value pair); all it needs is the literal display value of option.

mailchimp_subscribe() eventually calls MailchimpLists::addOrUpdateMember() in its dependent library. Thus, the logic of adding/updating is handled for you in the function.

To put that together in the above code snippet:

mailchimp_subscribe(
    $list_id,
    $email,  //Will add or update $email in $list_id based on subscriber status
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
        // Assuming the 'type' field in MailChimp is your 3rd field
        'MERGE3' => 'client',
    ),
    false,
    false
);


Following literally the instructions for manual installation as given by David Snopek (https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm) I succeeded in installing civicrm 4.7.27 under Drupal 8.4.2.

One caveat: I installed Drupal with composer (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies), using option B on that page "drupal/drupal" as using this option put vendor under the document root, something that is necessary according to David's blog post. In the Drupal documentation it is indicated that with option B one must manually add some lines to the composer.json file but, at least with 8.4.2, it is all there. But the error code about the libraries folder may indicate that these lines are not available in your composer.json file.

I cannot provide additional help but at least, the instructions from David seem to work still with the latest versions of both Drupal and Civicrm.


publish article to home page and secondary page

Drupal has a "Promoted to front page" check box under Publishing options when you create a new node.

To use this feature, visit /admin/config/system/site-information and make sure that the field under "Default front page" is empty.  This will enable your front page to show all content with "Promoted to front page" checked.  Anything you promote to the front page will be both on the front page and also have it's own individual page.

If you have a "President" page that needs to show all the president's articles/reports, you should take a look at Views.  This will be one of your best friends and you will want to take the time to learn how to use it properly.  In short, you would use views to create a block that displays articles authored by the president.  You would be able to display the block wherever needed.


Apachesolr searching is not working with cck field

Once you add a CCK field then the CCK will not by default get indexed. You have to delete all the existing index and have to re-index all items. This is because, CCK fields are properties of all the documents (nodes) that goes to the SOLR index.

Once all the items are index then you can find those by sis_cck_field_* names where sis_* is a type of dynamic field provided by SOLR itself. You can find the CCK index status in admin/reports/apachesolr/index page or in SOLR admin (http://127.0.0.1:8983/solr/admin/schema.jsp) page.

EDIT -- 1
As mentioned, the field is indexed properly then try to search by the value of the CCK field in Apache Solr's admin search (http://localhost:8983/solr/admin/form.jsp). If you see the search results appear as per your desire then there may be a permission issue. If your field is called "field_example" then in permission page check whether "view field_example" is checked for desired roles.

Edit -- 2
In that case I think the cck field is not at all being indexed. I had the same problem once with CCk fields that stores "multiple" values. In that case what I had to do is to create a new field in SOLR index and index the item again. This may solve your problem but may not be a proper way. However you will find this way is excepted in Drupal also in this link.

You have 2 ways to achieve this.

Append the item in the body field in time of content indexing hook.
Add a new dynamic field to the document object while indexing and fetch the field while searching.

For the 1st one,

function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  $document->body .= ' '. $node->field_MY_CCK_FIELD[0]['view'];
}

For the 2nd one,

function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  // For multiple values.
  foreach ($array as $value) {
    $document->setMultiValue('sm_multiple_value', $value);
  }
  // For text field.
  $document->addField('ts_element_name', $value);
}

And while searching,

function MYMODULE_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',ts_element_name'; //Add the field name to the select query.
}


How to print date in image in Event List in Drupal

Navigate to /admin/config/regional/date-time/formats/add and add a new date format. For the replacement pattern use: M t then click save.

then navigate to: /admin/config/regional/date-time and create a human readable name for your custom date format, then select the date format you created inside the select box. click save.

Create your view add your date field and then in the field settings give it your custom date format for the format section.

Style with CSS. You're done.

You may need to create two different date formats to achieve the styling you want. One for M and one for t. Then add your date field to the view twice and add the date formats on the fields, then you can easily target the two different date elements and use css to position them the way they are in the image you provided.


Copy site to another domain - XML SiteMap wrong and Theme Settings not the same

Go to admin/config/search/xmlsitemap/settings and set the correct domain. If that does not work look at your variable table in database and make sure xmlsitemap_base_url is correct.
Make sure your folder permissions are correct. If you have caching enabled and some themes need to write temp files inside sites/default/files so make sure permissions are correct and that Drupal can write there.

If that does not work can you inspect where the styles are coming from using Firebug and also post what theme you are using and I can update my answer.


Use Webform Share(https://www.drupal.org/project/webform_share) module to export & import

Example usage 1: Prepopulated webforms

Create a webform with the required components.
Export the webform
Edit the webform content type and paste in the content from the export (under Publishing options)
Use the standard node add content links and each new content item created should be prepopulated with the exported webform.


PDOException Error While saving the view

Run update.php for your site; clear cache as well.


What is the "contract" for EventSubscriberInterface functions?

The contract is the event class itself. In case of GetResponseEvent (deprecated by the way and will be replaced by RequestEvent in future Drupal releases) you can set a response, this will stop the propagation of this event and the kernel will return the response as an answer to the request.
From where do you have the example code, I'm not sure what case 0/1 is trying to do? In the Symfony default dispatcher the return value is ignored.


Lost setting of the custom field when editing a page

According to the code in the mentioned question, you need to define #default_value property and assign the $value variable to it like this:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $client   = \Drupal::httpClient();
    $request = $client->get('http://localhost:8083/regionilist');
    $response = json_decode($request->getBody());

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select element'),
      '#options' => $response,
      '#suffix' => '

',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [
          'custom_field/my_js_custom_field',
        ],
      ],
      '#default_value` => $value,
    ];

    return ['value' => $element];
  }


Remove terms from taxonomy vocabulary for node type

I found an option in the settings for the Views filter called "Limit list to selected items" I checked that and selected all the ones I wanted to show up in the list of terms by the operator settings. That made the ones I didn't want not show up.


How to get Views Selective Filters working with Country Field from Address Field Module?

I found a workaround on this. In the content-type with the address field i created a new field with a token of the country-field that is now working like a charm with views-selective-filters.


View to display all child taxonomy terms

You actually want to list sibling entities, with another level of complication in between: the paragraph reference.
Both Unit staff and Person reference Department taxonomy, only the Person does it through a paragraph.
Had there been no paragraf and the reference was direct you could simply follow the sibling taxonomy tutorials to get what you want.
Here's an example:
Building views relationship with location
and one with additional complexity:
Views Contextual Filter by taxonomy in field collection
In your case the chained Relationships will be:
Unit staff to Department term reference > Reverse Relationship from Department to Paragraph > Reverse Relationship from Paragraph to Person.
Then you add the Person (Term Name) to your Fields, it will use the last Relationship.
This gives you a list of Unit staff nodes, each with related Persons.
If you want to show a block of Persons on Unit staff pages add the Contextual ID filter for the ID, Default value ID from URL (the most common case). Place the block on Unit staff pages, adjust the contextual options, and the block will show Persons related to the Department of that Unit staff.


You just need to make the About us as Expanded and place the menu items Testimonials, Company under the About us. Please see the attached screenshots

Here, About us acts as parent item of Testimonials and Company.
After that just need to add and set the css in style.css file to the menu to be displayed accordingly.

Hope it works for you!


Redirect logged in (authenticated) users to a different frontpage using rules or php code

If you are using a particular node as your front page:

Create a new rule, event: content is viewed
Condition: data comparison -> node:nid equals to the nid of your front page node.
Add your conditions for user roles here.
Action: page redirect -> enter the path where you want to redirect the users

If you have PHP code module enabled already:

Create a new rule, event: content is viewed
Condition: execute custom PHP code -> return drupal_is_front_page();
Add your conditions for user roles here.
Action: page redirect -> enter the path where you want to redirect the users


The first thing to do is extend SearchBlockForm so you can give it a custom ID. Put code in mymodule/src/Form/MymoduleSearchBlockForm.php

namespace Drupal\mymodule\Form;

use Drupal\search\Form\SearchBlockForm;

class MymoduleSearchBlockForm extends SearchBlockForm
{
  protected $formIdentifier;

  public function setFormIdentifier($formIdentifier)
  {
      $this->formIdentifier = $formIdentifier;
  }

  public function getFormId()
  {
    $form_id = 'search_block_form';
    if($this->formIdentifier)
    {
        $form_id .= '-' . $this->formIdentifier;
    }
    return $form_id;
  }
}

Then you can call your form like this:

$form = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\mymodule\Form\Mymodule\SearchBlockForm');
$form->setFormIdentifier('some_custom_value');

return \Drupal::formBuilder()->getForm($form);

The key line of code here is this one:

$form->setFormIdentifier('some_custom_value');

If you pass a different value each time you generate the form, each form will get a different form ID. The form ID will be:

search_block_form-some_custom_value

Which will then be available in hook_form_alter with a $form_id of search_block_form-some_custom_value


Does calling query() on a container prevent SQL Injection?

What reported there for db_query() is still valid for the method that you should use. In short, use placeholders when building the query, instead of concatenating the query string with unsafe input (e.g. the input obtained from from the user).

In Drupal 8 procedural code, you would use \Drupal::database()->query() instead of db_query(), but you would still avoid using code similar to the following one.

$count = \Drupal::database()->query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = '. $_GET['user'])->fetchField();

The correct code would be the following one.

$count = \Drupal::database()->query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = :name', [':name' => $_GET['user']])->fetchField();


The reason you can't use the title as you wish, is because it's not a Field, but a Property.

Unfortunately I can't find a meaningful explanation of the difference between the two at this time, so no link, sorry.

If it helps in any way, you can create your own title field, which will then behave more like you expect. Of course, you'll then have two "titles", so this will various annoying side effects.


Create a taxonomy view that links to different photos

Here I am adding the screenshot for the configuration section for this module which you will find in your vocabulary manage display.

Screenshot


The trick to this is to create a discount. Force users to register before purchasing an item and than check the order history of a user at checkout. If the user has no order history at checkout than give him a 20% discount, if not than charge retail price.

This can be achieved with

http://drupal.org/project/commerce_checkout_login
And either a custom module or rules


Unable to set default value for checkbox form element inside tableselect

I remember struggling with this for a moment ! The documentation is not so explicit..

The tableselect element takes a #default_value array as a multiple select element would do, that is at the same level as the #options array, and with each selected option key being mapped to a truthy value, usually integer 1.

In the foreach, you would do something like this :

if ($staging_only) {
  // $row['staging_only']['data']['#attributes'] = array('checked' => array('checked'));
  $selection[$locale] = 1;
}

And then :

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $selection,
  '#empty' => t('No content available.'),
  '#attributes' => array('id' => array('locale-table'))
);

Non present options in the selection array default to false so you can ignore unchecked values.


How to put a custom login menu in a page?

ok your question has several parts:

(The standard login form can be accessed through a block, or going to the /user path while logged out)

Custom login form:

http://picxelplay.com/blog/theming-drupal-6-registration-login-and-request-new-password-pages-not-just-forms
http://blog.aphexcreations.net/2009/04/theming-drupal-user-login-form.html
http://drupal.org/node/154236 (outdated)

Custom 'menu':

Create a block that has a link to /logout, going to that path will automatically log out your users. Make sure that the block visibility is only for authenticated users.
Add any other links or options you want.


How to create fields group as accordions?

The Field Group module is great for that usage.

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.


How to add order number to multivalue fields classes?

template_preprocess_field(&$variables, $hook) gives you the ability to manipulate fields before they are printed. Just like with template_preprocess_page() and template_preprocess_node(). Not sure what the $hook parameter is for and I have never needed it myself.

Since this is a preprocess function that will be executed for each field, you should add a condition for your field name. Something like this will do:

function THEME_OR_MODULE_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'FIELD_NAME') {
    // Manipulate the data. use dsm() or print_r() to see the array structure.
  }
}

Edit: It would seem as if $hook is always passed as the string 'field', which would be quite useless. Can anyone confirm this?

Edit 2: Okey, so you actually don't need template_preprocess_field() at all if you can override theme_field.

Below is a working example of a extended theme_field($variables) function based of the original version. There is also a good tutorial/example here, which @camcam shared in a comment.:

function THEME_NAME_field($vars) {
  $output = '';
  $i = 0;

  // Render the label, if it's not hidden.
  if (!$vars['label_hidden']) {
    $output .= '
' . $vars['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($vars['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');

    // Add Row index to classes and iteriate row index variable.
    if ($vars['element']['#field_name'] == 'FIELD_NAME') {
      $classes .= ' row-' . $i;
      $i++;
    }

    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}


How can I specify the URL alias when importing nodes into Drupal 7 (with the Feeds module)?

Try the Pathauto module to do this. I found it helpful for auto-aliasing URLs in bulk, and it is customizable... it works pretty well if you use taxonomy to improve work site flow.


I think I see your problem

hook_menu is for defining your own page paths in code. It's not for hooking into the processing of a page that already exists. So you've got a conflict where you have 2 pages with the same url and the latter (the node/view page or whatever is it with the same url) is taking precedence over your bizaudit_menu definition. So your code created path is never triggered as Drupal has found another route for your "apim/navigate" path


Printing taxonomy terms as an un-ordered list

OK, there is a module for that! Taxonomy Menu. Once installed, you can quite simply turn your vocabulary into a menu by going to admin > structure > taxonomy > {your vocabulary} > edit

You can also play around with it and get multi-level menus, which I think is what you are after/asking for.

Hope this helps!


You can alter the form and add your own submit handler in which the user will be redirected back to the edit form:

function <MODULE>_form_alter(&$form, $form_state, $form_id) {
    if (strstr($form_id, '_node_form')) {
      $form['actions']['submit']['#submit'] = array('<MODULE>_form_submit');
    }
}
// Custom submit handler for '_node_form'.
function <MODULE>_form_submit($form, &$form_state) {
  // Call default action.
  node_form_submit($form, $form_state);
  // Redirect back to the edit page for this node.
  $form_state['redirect'] = url('node/' . $form_state['nid'] . '/edit', array(
      'absolute' => TRUE
    )
  );

  $_GET['destination'] = $form_state['redirect'];
}

You might have to tweak the above code to suit your needs.


I have also noticed that the template suggestions for views is sometimes gone, but as drupal.org writes you can just name your templates like this.

For example, if you have a view called foobar, then you shall call your template views-view--foobar.html.twig.

For more information, see Views template files.


It depends what you need really.

If you only need nusoap once, for a single project, then just download the library and include it using include (or even better, module_load_include(), that way it's still a 'Drupal' method!) There's no point writing a whole new module just to include a few files.

If you think you can provide useful wrappers for nusoap functionality though (as in ones not intrinsically provided by the library itself), or if you're likely to want to use nusoap again in a future project, it will probably save you some time later on to write a new module.

If you did this then you also have the added benefit of being able to contribute the module back to the community; a lightweight Drupal-capable soap library would probably be useful to a lot of people.

If I could offer any advice it would be to plan out what functionality you'd want your new module to have (what entities it could interface with, view/rules integration etc) before you dive in and write it. It's a lot more difficult to make a module generic halfway through writing it than it is at the beginning :)


tableselect does not work for me somehow 1

I copied your code from and commented the variables and/or functions you're using since I don't know what they are for and just replaced a simple array to loop through.

/**
 * Implements hook_menu().
 */
function leomod_menu() {
  $items['leoo'] = array(
    'title' => 'asd',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('leomod_asd_form'),
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Form.
 */
function leomod_asd_form($form, &$form_state) {
  $header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  $tests = array('1', '2', '3');
  //foreach(commerce_product_types() as $product_type => $product_type_array){
  foreach($tests as $test) {
    // $field_info = field_info_instances('commerce_product',$product_type);
    //foreach($field_info as $machine_name =>$field_details){
      $rows[$test] = array(
        'field_name' => $test,
        'field_type' => $test,
        'no_of_values' => $test,
        'display_fields'=> $test,
        'field_label' => $test,
        'required' => $test,
        'product_type'=> $test,
      );
    //}
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

  //  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

Since your table structure is working, I suspect there is something wrong with these lines:

foreach(commerce_product_types() as $product_type => $product_type_array) {

and

$field_info = field_info_instances('commerce_product',$product_type);
foreach($field_info as $machine_name =>$field_details) {

Also make sure you:

Flushed caches
Show all errors while developing since you're dealing with functions there that may return some errors that aren't displayed
Check the variables and functions if they return anything by using print_r() or Devel module's dsm().


How to install ckfinder outside the ckeditor module folder?

maybe this helps:

  This module allows you to use CKFinder with the WYSIWYG version of
  CKEditor. This module requires both the libraries and WYSIWYG modules.
  Please read the installation instructions carefully.

found here: https://github.com/jrsinclair/Drupal-WYSIWYG-CKEditor-CKFinder-bridge

Update 21 August 2012 This module has now been published on Drupal.org. You can find it at: http://drupal.org/project/WYSIWYG-CKFinder


Class declaration error when using ResourceBase

It looks like the problem was not with the REST API routes, but with the module name vs. namespace: in trying to pay attention to the details of the REST API extension, I missed that my module name was different from the namespace. In the above example, the module name is

  my_module

while the namespace is

  Drupal\my_module_rest_api\Plugin\rest\resource


How to separate UI language from node's language?

I forgot this in my initial comment but you can actually solve this by installing Entity Translation!

It separates entity and interface translation. With both you can specify different language negotiation schemes. In admin/config/regional/language/configure simply set the user's language setting as the highest priority in the interface language negotiation queue.

By having URL as the first criteria and user preference in the content language negotiation queue you can attain this functionality you documented.


How can I show a single block only if the user is on iOS?

My dull ax dealing with this same issue boils down to a little module helper function along the lines of:

function _MODULE_is_iOS() {
  if (strpos($_SERVER['HTTP_USER_AGENT'],'iPad')  !== FALSE ||
      strpos($_SERVER['HTTP_USER_AGENT'],'iPhone')!== FALSE ||
      strpos($_SERVER['HTTP_USER_AGENT'],'iPod')  !== FALSE) {
    return TRUE;
  } else {
    return FALSE;
  }
}

and then using that within my block hooks, eg,

if (_MODULE_is_iOS()) {
   $block['content']= // whatever I need for iOS
}

or from within the Block Admin PHP visibility area if in a pinch.


Can't update core with composer: "Your requirements could not be resolved to an installable set of packages"

The solution in my case was to delete the vendor directory and delete composer.lock.

I am not totally sure I needed to delete the vendor directory, because I tried that first without deleting composer.lock, and it didn't work.  Deleting composer.lock was necessary.

I also changed the minimum-stability to "stable" before deleting vendor and composer.lock, but I doubt that was necessary.  In any case, I now have...

  "minimum-stability": "stable",


Download the Rules module and import the following rule:

{ "rules_reset_points" : {
    "LABEL" : "Reset points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Points" ],
    "REQUIRES" : [ "php", "rules", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "global $user;\r\n$num_pts = userpoints_get_current_points($user-\u003Euid, \u0027all\u0027);\r\nif ($num_pts \u003E 100) {return TRUE;}" } }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "userpoints-transaction:user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "loaded_points" : "Number of points in the specified category." } }
        }
      },
      { "data_calc" : {
          "USING" : { "input_1" : [ "loaded-points" ], "op" : "*", "input_2" : "-1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "userpoints-transaction:user" ],
          "points" : [ "result" ],
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Prevent more than 100 points.",
          "operation" : "Add",
          "display" : 0,
          "moderate" : "approved"
        }
      }
    ]
  }
}

Adapt the actions to your needs, add another action "Send mail" after installing the Mime mail module (this article may help you in doing that) and you're done!


I'd use a custom Action Items content type and then Rules to handle the scheduling and assignments.  Rules and fields (via content types) should be flexible enough to handle such a workflow and they have the further advantage of being well-supported and documented.


Why Drupal is faster than WordPress in general

It's almost impossible to meaningfully compare the performance of Drupal and Wordpress, because their speed varies widely depending on the configuration and installed modules / plugins.  Both are capable of scaling when sites are built by skilled developers.

Regarding the Webiny benchmark, it's almost certain that Drupal's page cache was disabled (the default setting) for the test; I ran the same ab command on an Amazon micro instance and got over 100 requests per second.

That said, the Drupal community has a lot of interest in performance (the High Performance group is a good place to start).  The core development workflow has a process to account for performance issues.  And the ecosystem offers a range of modules to scale even further, including support for memcached, boost, varnish, APC, MongoDB, CDNs, and others.


Datepicker and form_state with different formats

1.Add a js file to the module and
2.In the js add the following code using the id of date field
to change the date format of the date picker
3.check the link for reference

$( ".selector" ).datepicker({ dateFormat: "yy-mm-dd" });


Including a PHP file in Drupal via BLOCKS, or REGION

You need to create a block template in your themes template folder.

To do this, you would create a new block, in Structure > Blocks, give it a bit of dummy content and save it in a region.

Then inspect the ID of the block in the source, or in Chrome Dev Tools, or Firebug, it should be something like block-block-1

In your themes template folder, copy the file block.tpl.php and rename the copied file block--block--1.tpl.php

In that file, you should see something like...

<div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>

Just replace the <?php print $content ?> with your content from ads.php

Then, in Performance > Development, flush the cache, and you should see your template replace the content of the block you created.


I found the CKEditor custom config module. This allows one to specify arguments to ckeditor's config object. This module provides me as much configuration as CKEditor allows.

I am still testing if I can filter specific inline styles, but if I can't do that, then that's an inability of CKEditor, not Drupal's ability to interact with it.


Can an identical profile and theme name cause conflict during installation?

Yes.  Modules, themes, and profiles must have unique names.


I have fixed the problem to exclude node from Apache Solr search by installing Apache Solr Exclude Node module. To configure this module, please follow the below steps:

Enable excluding of nodes in the submission form settings fieldset in the
content type settings (e.g. admin/structure/types/page).
Find the vertical tabs fieldset "Apache Solr exclude" in the node edit form.

Check "Exclude from Apache Solr" and save.


Can I prepopulate an exposed filter text field?

You can use hook_form_alter and can give your session value as the default value of the exposed text field

The following code will help you

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-XXXXXXXX") {

    $form['#after_build'][] = 'some_function';

 }
}

function some_function($form, &$form_state) {

 $default_value=$_SESSION['ip_geoloc']['location']['city'];
 $form['xxxxxx']['#default_value']=$default_value;

  return $form;
}


If there is no nodes in current taxonomy term to display, load vocabulary and display other

Use "No results behavior" of the view ; specify a new view ("Global: View area"), showing all nodes, excluding the taxonomy term "homes two".


How can I use regex in a migration query condition?

I was able to use REGEXP operator in a normal condition() method, although it is not stated in the documentation.

The answer was found on this example.

Solution:

  public function query() {
    return $this->select('data_table', 'd')
      ->distinct()
      ->fields('d', ['ID', 'Data'])
      ->condition('Data', '"image":"\d*[^>"]', 'REGEXP');
  }


Theming long lists of checkboxes- How can I divide lists of checkboxes into multiple columns?

Quick and dirty:

.form-radios,
.form-checkboxes {
  margin-left: 5px;
}

.form-radios .form-item,
.form-checkboxes .form-item {
  font-size: 64%;
  width: 19%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  margin: 0px;
}

and play around with the font-size and width to your specifics.  If you want to restrict this to a specific form, just add its id to the mix, eg:

#FORM .form-radios, ...


How to prevent an Ajax form from submitting

I found the solution here.

// Add submit handler to form.beforeSend.
// Update Drupal.Ajax.prototype.beforeSend only once.
if (typeof Drupal.Ajax !== 'undefined' && typeof Drupal.Ajax.prototype.beforeSubmitOriginal === 'undefined') {
  Drupal.Ajax.prototype.beforeSubmitOriginal = Drupal.Ajax.prototype.beforeSubmit;
  Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) {
    if (/* Custom condition */) {
      this.ajaxing = false;
      return false;
    }
    return this.beforeSubmitOriginal();
  };
}


Which template or include file in Omega subtheme takes hook_form_alter()?

The preprocess.inc and process.inc files are an Alpha/Omega way of organizing template_preprocess and template_process functions.  Basically, if your template.php would have a mytheme_preprocess_node, you would put it in preprocess-node.inc and name the function mytheme_alpha_preprocess_node.  When you clear cache, and Drupal rebuilds the registry, the Alpha hooks will scan all of these files and wire everything up.

This doesn't mean that everything else that you put in template.php goes in these includes.  Your custom theme functions and alters should still stay in template.php.

This can help keep the size of template.php managable, but I always still end up with large files because typically needs lots of theme and alter functions for the projects I work on.


Failed opening install.inc' when upgrading Drupal 7.x core with Drush 7.x

I managed to get it fixed after tracking the issue in drush 7, this is caused as you said by trying to load install.inc as Drupal 8 folder structure while you have Drupla 7 structure

I simply modified DRUSH_ROOT/commands/core/core.drush.inc line 1120

require_once DRUPAL_ROOT . '/core/includes/install.inc';

to be like

require_once DRUPAL_ROOT . '/includes/install.inc';

I hope this help you.


Is safe adding uid=0 in users table just to use $_SESSION?

Drupal does come with a row with uid=0 by default.

Some backup tools (notoriously some versions of PHPMyAdmin) are unable to deal with that, so you will lose this row when restoring from backup.

The easiest way to get back the missing row is to issue this query (for example in PHPMyAdmin):

UPDATE users SET uid = uid - uid WHERE name = ''


How to migrate from using the Taxonomy Access Control module to the Group module?

My recommendation: go for such replacement. In doing so, you could use the approach detailed in How to bulk assign content to a group. This community documentation page explains how you can use the Rules module together with the VBO module to bulk-assigning existing content to groups.

Here is the Rules Component included in that page (in Rules export format):

{ "rules_assign_a_node_to_a_group" : {
    "LABEL" : "Assign a node to a group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "group" : { "label" : "Group", "type" : "group" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:group" ], "value" : [ "group" ] } } ]
  }
}

Refer to the community page mentioned above for more details.

PS: the above rule assumes your migration target is D7 (there is no stable Rules release for D8 yet ...). But by using the Group module you're in very good shape also to later on upgrade to D8 also, since this module supports both releases.


user register hook form alter not reaching

The naming convention for hooks is:

MODULENAME_hook_name()

So to implement hook_form_alter() in a module called MYMODULE, your function would be defined as:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // ...
}

Have a look at What is the basic concept behind hooks? for a more detailed explanation.


Prevent Search Results Being Truncated - Drupal 7

Yes, there is. Copy the /modules/search/search-result.tpl.php file into your theme directory. Then modify it like this:

  <?php /* this is just so it will be easier to access the body of the node */ ?>
  <?php $node = $variables['result']['node']; ?>
  <li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

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

  <?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>>
    <?php /* this part is modified, you could display different data then the body */ ?>
    <?php print $node->body[$node->language][0]['safe_value']; ?>

  <?php endif; ?>
  <?php if ($info): ?>

<?php print $info; ?>

  <?php endif; ?>

Note Like I said in the comment, it's easy to display content from some other field, not just the body. To see what data you have to play with do:

 <?php echo '
';
       print_r($variables);
       echo '
';
 ?>


How can I override a module's file via hook_menu_alter()?

I think this happens because your alter hook does not update the value for $items['bonus']['module'], which was automatically set to 'things' when menu_router_build processed things_menu(). Try this:

$items['bonus']['module'] = 'bonus';
$items['bonus']['file path'] = '/includes/';
$items['bonus']['file'] = 'bonus.pages.inc';

or simply this, more like the things module does:

$items['bonus']['module'] = 'bonus';
$items['bonus']['file'] = 'includes/bonus.pages.inc';


Using "access callback" and "access arguments" provided with hook_permission

Not sure exactly what you mean there but your code already has a custom access callback specified as well as access arguments?

You could have an access callback like this:

/**
 * Add order access callback
 */
function order_add_access($op, $node){

 switch ($op) {
   case 'place order':
   // Return true, if logged in user has administer nodes permission
   // and node status is published.
   if (user_access('administer nodes') && $node->status == 1) {
     return TRUE;
   }
   break;
 }
 return FALSE; // default

}


Display a field of one content type based on another selected value

You will have to use AJAX.

Using hook_form_alter you can add ID to the element which needs to be changed.

function MYMODULE_MYFORM_ID_form_alter(&$form, &$form_state, $form_id) {

 //First add id to the field to be changed

  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#prefix'] = '
';
  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#suffix'] = '
';

//Then you can add AJAX to the countries field like this:

$form ['field_country'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => array('replace_textfield_div')
          );
 }

Now in your ajax callback function:

  function MYMODULE_ajax_callback(){
    $country = $form_state['values']['field_country'];

      if($country == 'US'){

             $options = array('Bank1'=>'Bank One', 'Bank2'=>'Bank Two');
           // and so on . You can Load Banks from DB_TABLE and place them here according to your need
             $form['field_bank']['#options'] = $options;

       }
   //AND OTHERS according to your requirement

  return  $form['field_bank'];

   }

Please remember to rename the fields according to your forms and requirements.


Is this the proper way to create a recipe page

Views have a "Sort Criteria".

You can sort by "Content Type" in there,  assuming you're only showing 2 content types you should be able to set Ascending or Descending order to get them displaying the way you want.


Drush is version agnostic.  From the same page:

  It is valid to use the latest '7.x' (or master) no matter what your version of Drupal is. Drush is independent of Drupal version :)


How to add back to top using drupal behaviors?

Try wrapping it:

(function ($) {
    Drupal.behaviors.scrollToTop = {
      attach: function (context, setting) {
        $('#back-to-top', context).on('click', function(){
            $('body,html').animate({scrollTop : 0}, 500);
        });
      }
    };
}(jQuery));

Had the same issue, AFAIK the wrapper is necessary to actually fire the behavior.


Drupal Commerce causing database deadlocks

Based on your update, you might consider using the Commerce Cart Expiration module.


How would you implement function rich forms to your module

I've found the solution today myself. I've been developing Webform components. I've found this way to be the best solution without altering any database structures and still getting the full functionality I wanted to get.

Instantiating - The base of your webform component

hook_webform_component_info - will be your friend in defining your components base structure. Since I needed the planning which would consist out of more timespaces (could've done better here on the termonology ;) ), I added a component named "planning" and gave it a "feature": group. This way I can extend the component "planning" with the "timespace" component.

Values - Add a limit of subscriptions and other parameters for your timespace

_webform_edit_component - Makes it possible to alter the edit form of your component. Make sure you at least add an "limit_subscription" (adjust naming to your liking) field so we can check against it.

_webform_defaults_component - Will be needed to inject the defaults to your edit form, which you have created with the function here above.

Cosmetics and security - Make sure you get the checkbox and disable it when full

_webform_render_component - Arranges all the cosmetics on your webform component. So make sure you edit your timespace component to get the checkbox you want so people can check a timespace. Also, you can (ofcourse) add some additional markup to your liking.

Security, checking the limit

This is also the right place to check for your limits and disabling the checkbox when full. (see the function webform_events_check_timespace_limit($component), use that to set #disabled on your element. Also make sure you give your element the right validation, something like this, so they can't screw around by simply enabling the checkbox:

'#element_validate' => array('_webform_validate_timespace'),

Then check against the database in your validation function for the limits, this is how I got it done:

/**
 * Validation for timespace elements
 */
function _webform_validate_timespace ($element, &$form_state) {
    // If checked, make sure this timespace has some space left.
    if ($element['#value'] === 1) {
        $remaining_subscriptions = webform_events_check_timespace_limit($element['#webform_component']);
        if ($remaining_subscriptions === -1) form_error($element, t('The timespace that you\'ve chosen is already full!'));
    }
}

/**
 * Check if the limit has been reached, returns remaining count to the limit, or -1 when full, or FALSE when no limit is set
 */
function webform_events_check_timespace_limit ($component) {
    $limit_subscriptions = $component['extra']['timespace_properties']['limit_subscriptions'];
    if (!empty($limit_subscriptions)) {
        $count_subscriptions = webform_events_get_timespace_count($component['nid'], $component['cid']);
        if ($count_subscriptions >= $limit_subscriptions) return -1;
        else return $limit_subscriptions - $count_subscriptions;
    }
    return FALSE;
}

/**
 * Get the count of the current timespace subscriptions
 */
function webform_events_get_timespace_count ($nid, $cid) {
    $select = db_query('SELECT count(*) FROM {webform_submitted_data} WHERE nid = :nid AND cid = :cid AND data = 1', array(':cid' => $cid, ':nid' => $nid));
    return $select->fetchColumn();
}

Backoffice - Exporting, table views, analysis..

For this you need the following functions, I'm not writing out these, I could go publish a book if I would:

Exporting (CSV, Excel):

_webform_csv_data_component - The actual data per row.
_webform_csv_headers_component - The headers in the top of the sheet.

Submission view (The page you get at individual submissions)

_webform_display_component

Table view

_webform_table_component

Analysis view

_webform_analysis_component

More help

Since I've just outlined the basics of this thing, I'd recommend you check out some good examples.

I've managed to figure this all out and fix get somewhat of the following (of course; early beta screenshots)

Submission view

Analysis view

A simple export

Front-end example

Table view

Setting up a event


You're passing the wrong thing as the schema definition.

This is what you need:

$schema['myid_template_'. $template_id] = array(...);

db_create_table('myid_template_' . $template_id, $schema['myid_template_'. $template_id);


How to programmatically get webform drafts for a specific user?

You could try this:
$query = \Drupal::entityQuery('webform_submission')
  ->condition('uid', 123)
  ->condition('webform_id, 'test_1')
  ->condition('in_draft', TRUE);

$entity_ids = $query->execute();

Or via the EntityTypeManager:
/** @var \Drupal\webform\WebformSubmissionInterface[] $submissions */
$submissions = \Drupal::entityTypeManager()
  ->getStorage('webform_submission')
  ->loadByProperties([
    'uuid' => 123,
    'webform_id' => 'test_1',
    'in_draft' => TRUE,
  ]);


Disallow access to member files when they are in public file system

To Apache or any other web server, seeing

<img src="http://www.foo.com/bar.jpg">

in html and a user typing http://www.foo.com/bar.jpg into their browser directly is basically the same thing so the quick answer is "no, not really, at least from a drupal standpoint."  You could obfuscate the path with some javascript trickery but that's about it.

Now, you could look into Apache referrer access, a quick link about allowing access from specific referrers might shed some possibilities on it for you, but now you are certainly outside of drupal :)


Can you customize the User Edit page without editing the theme?

You can use panels. It has a panel page for the 'user edit page' that you can edit, put blocks, views, etc.


How do I use page_callback or pageshow to display an existing article, view, page, block, or a slide show?

If you want your app's front page to show a node, then you can just set the front page to that node, in settings.js:

drupalgap.settings.front = 'node/12';

Under the hood DrupalGap already has a page_callback (and pageshow) that can load and render all core entity types. As you noticed with nodes, you simply linke to node/[nid] to view a node.

As for blocks, DrupalGap does not interface with blocks stored in Drupal, instead DrupalGap can create its own blocks for display in the app: http://docs.drupalgap.org/7/Blocks


// $node is supposed to be previously defined node object.

$article = Node::create(array(
  'type'     => 'article',
  'langcode' => 'en,
  'title'    => $node->title->value,
  'body'     => ['value' => $node->body->value, 'format' => 'full_html'],
  'status'   => 1,
));
$article->save();

This is the code if in case, anyone wants it.


Add the field a second time so it appears twice in Fields, check exclude from display and uncheck link this field to the original piece of content. Under rewrite results check trim this field to a maximum length, and enter 1 in the textfield.

Under format click settings next to unformatted list, etc. and select the right field in the grouping options.

You'll probably need to adjust the sort criteria too


//first just run this line
    kint($results);
    //and then you can uncomment the next lines, in my case I needed the response key 'elasticsearch_response'
    $response = $results->getExtraData('elasticsearch_response', []);
    $hits = $response['hits']['hits'];
    foreach($hits as $hit){
      kint($hit);
    }


Permissions to edit only the Status of an order

Install Views Bulk Operations
Clone the default user/orders/% view of all the orders, and restrict it to your new role.
Add a Bulk Operations field to the view in step 2.
Follow the steps outlined as you add the new field from step 3. You can limit which status states the user can select while modifying.


How to register multiple member in one civicrm membership sign up form?

I don't think you can do this directly within CiviCRM via the user interface. I get around this problem by using the webform (https://www.drupal.org/project/webform) and webform_civicrm (https://www.drupal.org/project/webform_civicrm) modules. Using this you have a far more flexible approach, and can produce a sign-up form that can create memberships for multiple contacts.

I've never understood why CiviCRM, which has a membership management as a core function, does not provide this functionality itself.


How to properly create an alias to a content

Welcome to Drupal Stack Exchange :-)

You need to Enable Clean URL's .. Find more information regarding Clean URL's in D.O here

Go to  "admin/config/search/clean-urls" and enable clean URL's


How to change the condition operator in the search api query?

I have overridden these classes in my custom module

Drupal\facets\Plugin\facets\query_type\SearchApiDate;
Drupal\facets\QueryType\QueryTypeRangeBase;

And then modified this function

public function execute()

of QueryTypeRangeBase and used the correct operator.


How to create a redirect for specific domain?

You can do this by using Domain Redirect module.

  This module allows the creation of an internal Drupal path that will
  direct the user to a unique path based on the domain that the user is
  in. The link is based at the path "/domain-redirect/12345" where
  "12345" is the redirect ID that is stored in the database.

OR

Try to use Domain Default Redirection module.

  This small module provides a redirection feature instead of providing
  the default domain contents in the Domain Access suite.


How to make billing cycles available as product attributes?

Yes, you need to create different products that are linked to the billing license configurations you want. This means that if you want monthly, quarterly, and yearly billing options, these would each be tied to products and then available via a dropdown.


Facets, by their very nature, work best when you use them for 'select' type fields, not pure text.  Facets work very well - and automatically - with taxonomy terms for example, because terms are re-used and it's easy to group based on select type fields.

Whenever I've wanted to use custom fields as facets, I've implemented them as terms (tagging) or select fields, and then they work properly.

So, I'm wondering - is that something you could do?  Rather than setting up your fields as 'text', could you set them up as select-type fields (whether it's tags, which don't have to be predetermined or select options which you have to enter in advance)?  That type of field is easier to GROUP by - which is what facets are really doing.

It may not be an option, but I have a feeling that would resolve your issue.

Let us know how this gets resolved!


I think you have multi language site.
I suggest you use the Taxonomy display module, here is a quote from its project page:

  The taxonomy display module allows administrative configurable term
  display pages. This allows administrators to override the default
  presentation of taxonomy term pages per vocabulary through the
  taxonomy term page's manage display form.


Is it possible to create/manage Roles using a .yaml file?

User roles are defined in YML files called user.role.ROLENAME.yml.

Do a config export (drush cex) to get an idea how these files should look like (they will be written to your config/sync directory).

Then create your custom role YML files in my_module/config/install and they will be created when you enable your module (if you took a YML file from config/sync as blueprint, remove the uuid and default_config_hash keys)

The file should look something like this:

langcode: en
status: true
dependencies: {  }
id: my_custom_role
label: My custom role
weight: 1234
is_admin: null
permissions:
  - 'do fancy stuff'


HTML in square brackets -> output as normal HTML

That's BBCode.

One option would be to simply install the BBCode module, which contains a BBCode filter. You can then apply that filter to the text format you're using for the body field, and it'll be converted to HTML automatically when rendered.