How to write webform settings and conditions programmatically

I had a similar requirement :

The site will have some landing page contents and the site owner can add those contents at different times, and once a content of type landing_pages will be created some blocks (already created) will get enabled on that node details page and a new webform node with some predefined fields will get created and get enabled as a block on that page in particular places.

I did it in D6.

My approach for the dynamic webform block :

I created a webform node with all the default & predefined fields, say with nid = 100
Enabled 'Available as block' option by visiting 'Form settings' tab in the path 'node/100/webform/configure'
Created a custom module 'landing_pages'
I cloned the nid = 100, each time a new landing_pages content is created
In hook_init() used this code :

/**
 *Implementation of hook_init().
 */
function landing_pages_init() {
// Update the 'blocks' DB table with the blocks currently exported by modules.
_block_rehash( $theme = NULL );
}

In hook_node_api() used this code :

/**
 *Implementation of hook_node_api().
 */
function landing_pages_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
 switch ($op) {
   case 'insert' :
     if ($node->type == 'landing_pages') {
       $node_id = 100;
       // function to create & save the clone node
       $new_nid = clone_node_save_custom( $node_id, $node->title );
     }
   break;
   case 'load' :
     if ($node->type == 'landing_pages') {
       /*updating webform block*/
       $result2 = db_fetch_object( db_query( "SELECT n.nid , n.title FROM {node} n WHERE n.type = 'webform' ORDER BY n.nid DESC LIMIT 1" ) );
       $var_result2 = 'client-block-' . $result2->nid;
       $result3 = db_result( db_query( "SELECT b.bid FROM {blocks} b WHERE b.module = 'webform' ORDER BY b.bid DESC LIMIT 1" ) );
       $nid = $node->nid; // Can avoide this step & directly use $node->nid
       $var_result1 = 'node/' . $nid;
       $check1 = db_query( "SELECT bl.bid FROM {blocks} bl WHERE bl.pages LIKE '$nid' AND bl.module = 'webform'" );
       /*if blocks table doesn't have any entry for 'pages' like this 'nid'*/
       if (db_affected_rows() == 0) {
         $check2 = db_fetch_object( db_query( "SELECT b.bid, b.region, b.status, b.visibility, b.pages FROM {blocks} b WHERE b.delta LIKE '$var_result2'" ) );
         /*if blocks table doesn'thave any entry for 'delta' like '$var_result2'*/
         if (db_affected_rows() != 0) {
           /*if blocks table doesn't have any entry for 'region' & pages,0 as entry for 'status' & visibility*/
           if ($check2->region == '' && $check2->status == 0 && $check2->visibility == 0 && $check2->pages == '') {
             $exp = explode( '-#-', $result2->title );
             if ($exp[0] != '')
               $title = $exp[1];
               db_query( "UPDATE {blocks} b SET b.module = 'webform', b.delta = '%s', b.theme = 'YOUR_THEME_NAME', b.status = 1, b.region = 'sidebar_second', b.visibility = 1, b.pages = '%s', b.title = '%s' WHERE b.bid = %d", $var_result2, $var_result1, $title, $result3 );
             }
           }
         }
       }
    break;
    case 'delete' :
      if ($node->type == 'landing_pages') {
        $res = db_query( "SELECT b.bid, b.delta FROM {blocks} b WHERE b.module IN ('webform' , 'block') AND b.theme = 'YOUR_THEME_NAME' AND b.pages LIKE 'node/$node->nid'" );
        while ( $row = db_fetch_object( $res ) ) {
          if (! is_numeric( $row->delta )) {
            $exp = explode( 'client-block-', $row->delta );
            if ($exp[0] == '' && is_numeric( $exp[1] )) {
            //This validation can be skipped
              $type = db_result( db_query( "SELECT n.type FROM {node} n WHERE n.nid = %d", $exp[1] ) );
              if ($type == 'webform') {
                node_delete( $exp[1] );
            }
          }
        }
        else {
          db_query( "DELETE FROM {blocks} WHERE bid = %d", $row->bid );
          db_query( "DELETE FROM {boxes} WHERE bid = %d", $row->delta );
        }
      }
    }
    break;
 }
}

Supporting functions :

/**
 *Definition of clone_node_save_custom().
 */
function clone_node_save_custom($nid, $nodetitle) {
 if (is_numeric( $nid )) {
   global $user;
   $node = node_load( $nid );
   if (isset( $node->nid ) && clone_is_permitted( $node->type )) {
     $original_node = drupal_clone( $node );
     $node->nid = NULL;
     $node->vid = NULL;
     $node->tnid = NULL;
     $node->name = $user->name;
     $node->uid = $user->uid;
     $node->created = NULL;
     $node->menu = clone_node_clone_menu_link( $original_node );
     $node->book['mlid'] = NULL;
     $node->path = NULL;
     $node->files = array();
     $node->title = t( '!tit -#- !title', array('!tit' => $nodetitle, '!title' => $node->title ) );
     $node->clone_from_original_nid = $original_node->nid;

 if (variable_get( 'clone_reset_' . $node->type, FALSE )) {
   $node_options = variable_get( 'node_options_' . $node->type, array('status', 'promote' ) );
   foreach ( array('status', 'moderate', 'promote', 'sticky', 'revision' ) as $key ) {
     $node->$key = in_array( $key, $node_options );
   }
 }
 drupal_alter( "clone_node", $node, $original_node, "save-edit" );
 node_save( $node );
 return $node->nid;

  }
}
}

/**
*Defines clone_node_clone_menu_link()
*@param $node
*/
function clone_node_clone_menu_link($node) {
if (variable_get( 'clone_menu_links', FALSE )) {
  // This will fetch the existing menu link if the node had one.
  node_invoke_nodeapi( $node, 'prepare' );
  if (! empty( $node->menu['mlid'] )) {
    $old_link = $node->menu;
    $link['link_title'] = t( 'Clone of !title', array('!title' => $old_link['link_title'] ) );
    $link['plid'] = $old_link['plid'];
    $link['menu_name'] = $old_link['menu_name'];
    $link['weight'] = $old_link['weight'];
    return $link;
  }
}
return NULL;
}

Theme used is ZEN
Region I needed the webform be enabled is 'sidebar_second'
We shall have control over the settings of each webform for each Landing Page

Hope it helps.


As an alternative, consider using the Content moderation notifications module:

  Allows notifications to be sent to all users of a particular role, or to the content's author when a piece of content is transitioned from one state to another via core's content_moderation module.

I've used it with good results in several sites.


Moving a Drupal website from one server to another, an error needs to be fixed

Try disabling the update module, the quickest/easiest way would be via Drush using drush dis update.

If you cannot use drush follow this: http://drupal.org/node/157632
"phpMyAdmin

To disable a module via phpMyAdmin you must login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save."


I want my LinkItem to get target="_blank" if my node has the checkbox checked

According to your answer to my comment on the question, you are using a view. To have my solution work, it needs to display fields, not teasers.

First off, you do not need to add an additional field to the node type/content type.

All you need to do is to add the already displayed link field in views a second time. All fields get a views internal machine name which is often identical to the field's machine name. However, if you add a field twice, you will end up with two machine names, thus you can determine which version of the rendered field to use at some point.

So, you end up having the same field (Link - field_link) showing up twice in your view's field list. The one added first will be accessible through the token [field_link], the second one by using [field_link_1].

In the first one's settings, choose the plain URL formatter and then go to the "Rewrite result" section. Select the option to output the field as link and enter [field_link] as url and _blank for target:

Finally, set the option "Exclude from display". Repeat that with the second link field, but use [field_link_1] as url and do not set the target.

With both field instances set up and excluded from display, add your checkbox field which may have the machine name field_link_is_external.

Now you need to rewrite that field to be [field_link]:

If the checkbox is checked, the link version with target set "_blank" will be shown.

Next, you need to set the "No result behaviour" as follows:

If the checkbox is not checked, it's value is zero, hence we treat 0 as empty and thus the second link field (w/o target) will be shown.

And that's all there is to it. No need for any editor to enter some url twice. They just need to set the link and decide whether or not to check that checkbox.


You can set that in the URL aliases configuration.

In http://example.com/admin/config/search/path/settings

In the section 'update action', check one of the two:

Do nothing. Leave the old alias intact.
Create a new alias. Leave the existing alias functioning.

The default is:

Create a new alias. Delete the old alias.


This might sound like a dumb solution, but the simplest and fastest solution of hiding fields would be hiding with CSS depending on a parent (paragraph) attribute or class. E.g. in paragraph preprocess

if ($paragraph->get('your_field')->value == "hide credit") {
  $variables['attributes']['class'][] = 'paragraph--credit-hidden';
}

and in CSS

.paragraph--credit-hidden .field--credit {
  display: none;
}

Other options would be either additional view modes for media entities (if not to many permutations), additional cache contexts (depending on the case, given your problem description most likely not a good solution), corresponding to your host paragraph settings. But given your description I'd go the KISS way and avoid the coding overhead.


Should I use Libraries API if I only wish to use a 3rd-party library for my own custom module? version detection, duplicate declaration

I think the answer would be to check for an API module that wraps the 3rd-party code inside a Drupal module, in my case this would be the Flickr API module, which has been fixed to use Libraries API:

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

If there isn't a wrapper for the 3rd-party code, then this would be the case to make one, by oneself.


You try code:
 use Drupal\views\ViewExecutable;
 use Drupal\views\Plugin\views\query\QueryPluginBase;
....

   /**
    * Implements hook_views_query_alter().
    */
    function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
     $query->addWhere(0, 'node__field_data.nid', [1,2,3], 'IN');
    }


All changes to form must be done through hook_form.  Adding a new form in a js callback function will not be accepted as new elements to a form in Drupal.


Create a node programmatically then reference an existing node to that node?

As for the second part, you need to pass node ID or array of node IDs to node_load function first argument.

Your code should look like the following:

$node2 = node_load($nid); // pass integer node ID or array of integers

$node2->field_reference['und'][0] = array(
  'target_id' => $node->nid, // pass integer node ID not node object
);

node_save($node2);

drupal_goto("node/{$node->nid}");


I know this is a pretty old question but seems unanswered yet.
This Drupal 7 snippet will help you to load a taxonomy term but you need to know the name of the vocabulary it belongs to, lets say it is 'position'.
Ex. www.example.com/foo/6-class/bar

$term_path=drupal_get_normal_path('position/'.arg(1));
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

If you know your url is an alias to your taxonomy term, just use

$term_path=drupal_get_normal_path(current_path());
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

The drupal_lookup_path with source and uri approach did not work for you because probably that path is not an alias, or at least not for your taxonomy.

Hope this helps someone.


Node Menu Parent is the module you need to achieve this:

  The Node Menu Parent module gives us an extra option under the content
  type settings to choose a specific parent menu item per content type.


Drupal views get fields after filters without html markup

After suggestion from AlfredArmstrong I checked plugin style docs.
To get filtered data without rendering html template simply do:

 $data = $view->style_plugin->render_fields($view->result);

Under $data will be array of filtered fields from view.


How do I add dropdowns in Filter Criteria in Views module?

The filters in views and how they are exposed to the user reacts a bit differently depending on the type of filter that is used. The type of filter that used, is controlled by defining the data to views using hook_views_data and hook_views_data_alter. This is a bit code heave and not always something you need to do your self as many modules including views does a lot of this for you.

Two common filters used is

views_handler_filter_in_operator
views_handler_filter_string

The two are are fundamentally different because their assumptions and requirements are very different.

The first one, is the one that you would like to use. It's used when you store a value that has a defined list of possible values. An example could be content types which is the example that @Danielle used in her post. Since nodes can't have any random value for their content type, it's possible for views to display a list of checkboxes in the Admin interface when using this filter and a select list / multiple select list for the user when it is exposed.

The second one is used when a string is stored in the database. Using nodes as an example, the title field would be a good candidate for such a filter. Since titles can be any text, it doesn't make sense to expose title selection of a node as checkboxes or select lists, instead you get some other options like you are seeing in your view. You can filter by if the string contains a word (beginning /end / somewhere), it's length etc.

If the one that did the views integration didn't bother using the in_operator type of filter, and describe to views (by using a php function) which options are available, you will have to do it using hook_views_data_alter.

What you need to do is:

Create a subclass of views_handler_filter_in_operator
Implement get_value_options
Tell views about your new handler.

In code it would look like this

/**
 * Define my custom in_opeator
 */
class my_custom_in_operator extends views_handler_filter_in_operator {
  // overwrite the get_value_options function.
  function get_value_options() {
    if (isset($this->value_options)) {
      return;
    }
    $this->value_options array('option_1' => t('Option 1'), 'option_2' => t('Option 2'));
  }
}

/**
 * Implements hook_views_data_alter().
 */
function my_custom_views_data_alter(&$data) {
  $data['entity_type']['property']['filter']['handler'] = 'my_custom_in_operator';
}

And you're done. In reality it's actually quite simple. But finding out how to do is not as views is quite complex.


Take the #'s off the nested #ajax values.  IE

  '#ajax' => array(
      'callback' => 'formajax_callback',
      'wrapper' =>  'replace_this',
      'effect'  => 'fade',
      'event' => 'blur',
      'keypress' => FALSE,
    ),


Views is created in a very object oriented way, which is really great. What this means is that if the default Views behavior doesn't work for you, you can extend the classes that Views supply and alter only what you need to overwrite. I wrote a blog post about this focusing on filters, but the principle is the same for contexts, sorting ...

In views lingo a context is called an argument.


Modifying target vocabulary when migrating taxonomy terms with migrate_d2d

After poking around some more, I found my answer in this issue and the Migrate module documentation.  Based on what I found there, this is what I came up with:

/**
 * Override of DrupalTerm6Migration. Only for People and Organizations vocabulary
 * since we need to split terms out to two new vocabularies.
 */
class NBPeopleOrganizationsTermMigration extends DrupalTerm6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // Set field mapping for destination vocabulary, since we need to
    // set it on a row by row basis.
    $this->addFieldMapping('vocabulary_machine_name', 'vname');
  }

  /**
   * Implementation of Migration::prepareRow().
   *
   * Need to redirect terms into either Journalists or Non-Journalists vocabularies
   * based on whether term is listed in nb_migrate_journalists table.
   *
   * @param $row
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    // Create journalists array from nb_migrate_journalists table.
    static $journalists = array();
    if (!$journalists) {
      $sql = "SELECT * FROM nb_migrate_journalists";
      $result = db_query($sql);
      foreach ($result as $record) {
        $journalists[] = $record->tid;
      }
    }

    // Set value for name (mapped in constructor above) based on presence in $journalists array.
    $row->vname = in_array($row->tid, $journalists) ? 'journalists' : 'non_journalists';
  }
}

Basically it just creates a mapping between the destination vocabulary machine name and the vname variable, which is then populated in the prepareRow() method.


I dont think there is a module you can use.

The form will contain an element such as

<?php
  $form['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
    '#maxlength' => 128,
    '#autocomplete_path' => 'cities/autocomplete',
  );
?>

Addition to hook_menu

You must add #autocomplete_path to your hook_menu function.

<?php
    function cities_menu(){
    ...
    // path with autocomplete function for cities
    $items['cities/autocomplete'] = array(
      'title' => 'Autocomplete for cities',
      'page callback' => '_cities_autocomplete',
      'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
      'type' => MENU_CALLBACK
    );
    return $items;
?>

Make a call to the Database.

<?php
/**
 * autocomplete helper
 * $string = string for search
 */
function _cities_autocomplete($string) {
  // Fetch most used cities.
  $matches = array();
  $result = db_select('cities', 'c')
    ->fields('c', array('city'))
    ->condition('city', '%' . db_like($string) . '%', 'LIKE')
    ->execute();

  // save the query to matches
  foreach ($result as $row) {
    $matches[$row->city] = check_plain($row->city);
  }

  // Return the result to the form in json
  drupal_json_output($matches);
}
?>

Make sure your autocomplete handler has appropriate menu permissions set on it,

From : Textfield that uses autocomplete


Quickest Way To Create a Pre-Register Form

What you suggest (using Rules for this) is far too complicated for me.

To do this with the minimum hassle, I would just set up a standard Drupal site and create a fixed front-page that says: "Pre-register for my great new site."   Configure permissions so that if the logged in user doesn't have admin permissions, all he/she is allowed to see is this fixed front page.

Then use String Overrides to replace the text "Create new account" in the login box with the text: "Click here to pre-register".  I.e. the by "pre-registering", the user really creates a standard account on the site.

Then auto-subscribe everyone that pre-registers to a newsletter (for a newsletter module you can, for example, use  Notify). This will let you post updates on the site about the ongoing development, etc. that also are automatically sent to those who've pregistered as a digest newsletter e-mail.  (Notify let you auto-subscribe new users and also has a master switch to make subscribing and unsubscribing a breeze).

Later, when you've done setting up the site, you can ask the user to confirm his/her committment by ticking some field in the user profile, and silently convert those that confirm to regular users by given additional access permissions (and delete the rest).

Disclosure: I am the maintainer of Notify.


Creating a Date Field that will display 'Year' to 'Current'

This is doable using Conditional Fields despite its rather minor limitation (http://drupal.org/node/360824). You can't trigger fields' display by a checkbox's off value. That will require you to negate the "I currently work here" checkbox to something like "Past position". You can still decide if you want it checked by default or not, and using JavaScript you can hide the "Past position" checkbox and control its value using the desired checkbox with the opposite meaning.

Saving 'Current/Present' to the database is not an issue really. You only need to check the value of the checkbox field and you can disregard the 'Current/Present' value if this is an ongoing position. To make the To date field work as expected, though, make it Required and choose an arbitrary Default value for it, which will be used even when the field is not displayed. Now would be a good bet.

Here's an image which pretty much wraps up the 5 minute content type setup.

It's obviously going to take a little more than that to make the form look and behave the exact way you want. For information on theming the resulting form, see Theming a form with conditional fields.

Also see Conditional Fields Docummentation


Can't understand how to invoke my own theme() function

You just need to set it on the $form element inside your form function:

function formexample_nameform($form, &$form_state) {
  $form['#theme'] = 'formexmaple_nameform';
  // ...

When you use render element with a theme the variable on which you set #theme is the one that's passed through to the theme/preprocess functions.

Don't forget to add drupal_render_children() at the bottom of your template file or the form won't render correctly:

echo drupal_render_children($form);


Drupal 7 Views 3 Contextual Filter - preview works as expected, the actual page not, why?

Found the answer to the problem...

There are path aliases to nodes that were deleted before, and accidentally those aliases look exactly like how the view with arguments should look like. So, there were an alias of 'team/peter-jackson-junior' to 'node/xyz', this overridden the path to the view, but 'node/xyz' was deleted and so it is natural that it gives back 'The requested page could not be found.'.


i would say remove the if/else and only leave the else code, as you never want to show $user_picture

$employeeid = token_replace('[current-user:field_employeeid]');
?>

    <img src="<?=base_path()?>sites/default/files/pictures/<?=$employeeid?>.jpg"/>


Ckeditor fake linebreaks with pasted text

If you're experiencing weird behavior on the editing side of CKEditor it's probably because of the CSS file being loaded by CKEditor.

CKEditor implements this in a way where it doesn't show up in my firebug.

I can see the margins and padding when I hover on an element however nothing is shown when it lists the styles effecting the element. This causes the problem above.

How to fix it:

Changing the CSS file works, go to the CKEditor configuration page and select the CSS drop down menu.

Change CKEditor default to Define CSS and enter your own path for the CSS file.

What I did however was edit the CKEditor default css file. It's located in ../modules/ckeditor/ckeditor/contents.css

I was getting a margin of 20px appearing on the top and bottom of all my elements. There was nothing in contents.css about it, I don't really know where it's coming from.

But I added the following snippet which fixed it.

p,
h1,
h2,
h3,
ul li {

margin: 0 auto;

}


How do I add a #process callback to a fieldset form element without overwriting the existing callbacks?

When you add a #process function to a form element, the default ones defined from hook_element_info() are not added. Using hook_form_alter() to add a #process function doesn't change the result, as hook_form_alter() is invoked before the default #process functions are added to the form element. This happens in form_builder(), which uses the following code.

 // Use element defaults.
  if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
    // Overlay $info onto $element, retaining preexisting keys in $element.
    $element += $info;
    $element['#defaults_loaded'] = TRUE;
  }

If $element['#process'] is already set, it doesn't get overriden by $info['#process'], which means the default functions are not added.

What you can do is invoke the default #process function from the one you define. If mymodule_process_function() is the function you add, it should contain code similar to the following one.

function mymodule_process_function($element, &$form_state) {
  if (isset($element['#type']) && ($info = element_info($element['#type'])) && isset($info['#process'])) {
    foreach ($info['#process'] as $process) {
      $process($element, $form_state);
    }
  }
  // ...
  return $element;
}

If the #process function is necessary in any form where a fieldset is present, then you can implement hook_element_info_alter() to alter the information returned from system_element_info() about the fieldset form element.

  $types['fieldset'] = array(
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#value' => NULL,
    '#process' => array('form_process_fieldset', 'ajax_process_form'),
    '#pre_render' => array('form_pre_render_fieldset'),
    '#theme_wrappers' => array('fieldset'),
  );

The alternative that requires less code to be written is to add a #after_build function to the fieldset. #after_build functions are functions that are called after the #process ones, receive $element, and &$form_state as argument, and need to return $element. As system_element_info() doesn't set any #after_build function, there is less code to execute.
For compatibility with any module that implement hook_element_info_alter(), and which could alter the fieldset definition, code similar to the one I shown before should be used also for the #after_build property.


Try audit Files module

  Audit files is designed to perform audits of your upload directory and
  the corresponding database records. It will cross check that all files
  in the database have a corresponding physical file, or it will check
  that all files in the upload directory have a corresponding entry in
  the database.

  This module can be helpful in identifying orphan files that have not
  been deleted when their corresponding node was removed.

  The module has configurable options to ignore specified files and/or
  directories.

  The reports allow you to permanently remove files or database entries
  that represent orphans.


I've managed to find an answer in a Stack Overflow answer https://stackoverflow.com/a/30570027/1094862

For completeness I've copied the relevant code below:

$main_menu_tree = menu_tree_all_data('menu-name', null, 3);
render_menu_tree($main_menu_tree);

function render_menu_tree($menu_tree) {
  print '
';
  foreach ($menu_tree as $link) {
    print '
';
    $link_path = '#';
    $link_title = $link['link']['link_title'];
    if($link['link']['link_path']) {
        $link_path = drupal_get_path_alias($link['link']['link_path']);
    }
    print '' . $link_title . '';
    if(count($link['below']) > 0) {
      render_menu_tree($link['below']);
    }
    print '
';
  }
  print '
';
}


Make a custom block to render a published content

The easier way to achieve this problem is by creating a view block. That only show the content that is been published. Then you going to add that view block on any region that you wish.

Here is the code for a export view block that only show content that have been published.

uuid: 36b6dd0f-8a30-4d08-a718-24afe8b4cfc0
langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_published
label: 'Content Published'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: some
        options:
          items_per_page: 5
          offset: 0
      style:
        type: default
      row:
        type: fields
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          settings:
            link_to_entity: true
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          order: DESC
          entity_type: node
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: 'Content Published'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }


How do I target a specific term or node in a toked?

The link node module is doing this for you. Here is a quote about it (from the module's project page):

Once installed you (or any user who can post) can add an embedded href link to any node using the syntax (where N is a number, and NNN is a node id):
[node:NNN]
Parameters follow the part and are comma separated name="value" pairs:
[node:NNN,title="Original version of the picture"]
MultiLink supports Link Node, so if someone is viewing in another language it gets converted to [node:101] or whatever the correct node is for the translated version automatically.


Set query option distinct so that results are included just once

and check your filter criteria, maybe you included some date condition.


Filter view by users without a matching record in the related userpoints table

I figured it out:

function MYMODULE_views_query_alter(&$view, $query) {
 if($view->name = "nameofview") {
     $query->where[1]['conditions'][] = array('field' => 'userpoints_total.points', 'operator' => 'IS NULL',);
    }
}


I ended up implementing a custom function on the base of this post :

private function async( $method, $url, $params = array() ){
    // Get URL parts
    $url_parts = parse_url( $url );

    // If needed, append params to query url
    if( $method === 'GET' ){
        $url .= '?' . http_build_query( $params );
    }

    // Open socket
    $port = isset( $url_parts['port'] ) ? $url_parts['port'] : 80;
    $fp = fsockopen( $url_parts['host'], $port, $errno, $errstr, 30 );

    // Build HTTP request
    $request = $method." ".$url." HTTP/1.1\r\n";
    $request.= "Host: ".$url_parts['host'].":".$port."\r\n";
    $request.= "Connection: Close\r\n";
    if( $method === 'POST' || $method === 'DELETE' ){
        $post_string = Json::encode( $params );
        $request.= "Content-Type: application/json; charset=utf-8\r\n";
        $request.= "Content-Length: ".strlen( $post_string )."\r\n";
        $request.= "\r\n";
        if( isset($post_string) ){
            $request.= $post_string;
        }
    } else {
        $request.= "\r\n";
    }

    // Send request and immediately close the pointer
    fwrite($fp, $request);
    fclose($fp);
}


Tried to reproduce this but wasn't able to make it. Below is my process.

no prlp module

created new user with notify email
used onetime login link
changed password
logged out
logged in using the new password. SUCCESS

with prlp module

request new password
used onetime login link
changed password in the one time login page. SUCCESS
logged out
logged in using the new password

5.1. using username 'asd'. SUCCESS

5.2. using email 'asd@asd.com'. FAIL (not relevant)

enabled logintoboggan (to use email as login)

login using email and new password. SUCCESS
logout
request new password
used one time login link
changed password in the one time login page. SUCCESS
logged out
logged in using the new password

7.1. using username 'asd'. SUCCESS

7.2. using email 'asd@asd.com'. SUCCESS

Anything you'd like to add or to test?


How to get location (longitude and latitude) from json data show on map?

1) Add Geofield in your content type.

2) Select widget type as "Latitude / Longitude".
Here you can store values and show it on map.

For your reference listed some links :

Setting drupal 7 locations

Getting Started with OpenLayers in Drupal 7

Openlayers


Disable modules when browsing mobile site

The load caused by modules is handled by the server, so merely having the modules enabled will not affect the performance of your mobile site.  In any case, it is impossible to disable the modules because you could be serving web pages to both mobile and desktop machines at the same time.

Instead, what you want to do is add a mobile theme.  There are lots of ways to do this but the Mobile Tools module is a good way to get started.

For a more specific solution, you'll have to identify which modules are causing the performance problems on your site so that workarounds can be found.


$page parameter doesn't appear to contain all the information used to render a page

I would suggest using hook_preprocess_HOOK. In this instance I think hook_preprocess_node is what you want but _page may work as well.


Whats the most effective way to intergrate a javascript cost calculator to a specific node

You can use JS injector module

  Allows administrators to inject JS into the page output based on
  configurable rules. It's useful for adding simple JS tweaks without
  modifying a site's official theme - for example, a 'nighttime' color
  scheme could be added during certain hours. The JS is added using
  Drupal's standard drupal_add_js() function and respects page caching,
  etc.

or simply use drupal_add_js in body field with enabled PHP input mode and take a look at this page


hook_form() is only meant to be used by a module that provide content type:

This hook, implemented by node modules, is called to retrieve the form that is displayed to create or edit a node. This form is displayed at path node/add/[node type] or node/[node ID]/edit.

Emphasis mine.
It provides the form, and does not do alterations.
If you want to modify base form created by another module, you need hook_form_alter():

Perform alterations before a form is rendered.
One popular use of this hook is to add form elements to the node form. When altering a node form, the node object can be accessed at $form['#node'].

Again, emphasis mine.


Why doesn't the field table in the Drupal database use entity_id as a primary key?

The primary key for a field table is compound, consisting of:

entity_type
deleted
entity_id
language
delta

It's probably just the way your GUI is displaying the data that's confusing. This is Navicat's representation, for example:

If not, then something fishy has happened. Since the entity_id is supposed to be part of the compound key, if it isn't, it should be safe to add it to the rest. Take a backup first just in case.


How to force regeneration of Twig templates?

Not sure why you get that specific error, but have a look at drupal_flush_all_caches(), which does

PhpStorageFactory::get('twig')->deleteAll();

That said, I'm not sure if this will solve your problem, as I've never seen that error, not sure how it could end up expecting a class that is not there.


how to connect android app to drupal database?

Here is a module that will help in this venture, for Drupal 6.x and 7.x sites:

DrupalGap

It leverages PhoneGap (Cordova), Drupal + Services + Views Datasource (Views JSON). It provides a starting point for creating multi platform (Android, iOS, etc) mobile applications for Drupal websites.


You are likely looking to use hook_view_query_alter, additionally you might want to look into some related questions on Drupal answers How do I use hook_views_query_alter()?.


Can't do with core functionality. You need to modify form using hook_form_alter. Probably you would want to use Drupal form's AJAX to make fields appear.

I don't know if there is a contrib module to do this, I can't see any.


My online research led me to this page.

I created a view to include 'row_count' using the following query:

SELECT
    `company_code`,
    `basis_id`,
    `mortality`,
    `commission`,
    `initial_expenses`,
    `recurring_expenses`,
    `discount_rate`,
    `date_saved`,
    (
    SELECT
        COUNT(0)
    FROM
        `actuarial_bases` `b`
    WHERE
        (
            (`a`.`date_saved` <= `b`.`date_saved`) AND(
                `a`.`company_code` = `b`.`company_code`
            )
        )
) AS `row_number`
FROM
    `actuarial_bases` `a`

then modified my query to:

$query = \Drupal::database()->select('bases_in_force', 'b')
         ->fields('b', ['company_code','basis_id','mortality','commission','initial_expenses','recurring_expenses','date_saved','discount_rate'])
                    ->condition('row_number',1)
                    ->orderBy('date_saved', 'DESC')
                    ;
$results = $query->execute();


Drupal 8 - Alter page attachments AFTER form submit

I see two ways of doing this.

Options 1: Make the form Ajax. Either by using Form API in Drupal or Jquery. Then in success function call your custom js event. Or else you could also do something like this:

 $('#some-form-123').submit(function() {
    _gaq.push(['_trackEvent', 'Contactform', 'Form submitted']);
  });

The above code is an example, you need to use it for your event.

Option 2: In Drupal set a cookie when the form is submitted. Then in page load, check if the particular cookie exists. If it does exist invoke your custom event and unset the cookie. Then, the cookie is only present if the form is again submitted.

See the following:

https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
https://github.com/jquery-form/form
https://github.com/js-cookie/js-cookie


How can I check whether a username is in use?

You need add the condition for if the user exists or doesn't exist and then you are able to create two actions, depending on the user exists or not.

The problem is that this is not possible to do with Rules out of the box. It's not hard to add a condition like this, but it required custom code in a custom module. If this is not an option, what you are asking for is impossible AFAIK, as it doesn't exist.


This page has everything you need to know, including example payment method modules you can use as reference implementations:

http://www.drupalcommerce.org/developer-guide/utilizing-core-apis/writing-payment-method-module


If you are using Admin Views you can edit the view and change the exposed filters and uncheck "remember the last selection".

A screenshot to illustrate this for the content:title field:


How to customize the text of "SUBMITTED BY" (article)

In node.html.twig change the line SUBMITTED BY to WRITTEN BY

  {% if display_submitted %}
    <footer class="node__meta">
      {{ author_picture }}
      <div{{ author_attributes.addClass('node__submitted') }}>
        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}
      </div>
    </footer>
  {% endif %}


Don't allow "Delete this field" if a module is activated

The module field lock allows you to lock fields for certain roles. You can use that module out of the box or you can copy it and adjust it so that the fields only lock if your module is activated.


Will all Drupal 7 Ubercart 3 orders be deleted if I disable & uninstall all Ubercart related modules?

If you uninstall them, then yes.

EDIT:

No, they will not. Good call, duckx (I shouldn't have assumed that the D7 version implemented hook_uninstall_schema()).


Redirect from node page after form submission?

Another approach is to simply implement hook_form_alter and put this code into it:

    function MY_THEME_OR_MODULE_form_alter(&$form, &$form_state, $form_id) {
      // dpm($form_id)
      // dpm($form)
      if($form_id == 'article_node_form') {
        $form['actions']['submit']['#submit'][] = 'my_node_form_submit';
      }
    }

    function my_node_form_submit($form, &$form_state) {
      $form_state['redirect'] = 'MY_URL';
    }


Drupal 8 update.php/selection - access denied

After several frustrating days I figured the problem was from my configuration.
The conf file has
     "fastcgi_param SCRIPT_FILENAME $request_filename;"
instead of
     "fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;"

Making this correction solved the problem.

Am grateful for all the support.


how to get the form id of a particular form using Devel execute PHP in drupal 7?

I don't think it's possible to do this without something (either your custom module or another module) implementing hook_form_alter(). The Devel execute PHP form is in a block which has no real idea what forms are available on the page.

I'm sure you know the way to get the form ID but just in case this will print it at the top of every form:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('whatever permission you want')) {
    $form['mymodule_form_id'] = array(
      '#markup' => '
Form ID: ' . $form_id . '
',
      '#weight' => -10000
    );
  }
}

If you really don't want to do this, though, why not just use developer tools/firebug to inspect the form element on the page itself...you'll find the form id in one of the hidden input fields.


Your original conditions looks in usergroup_id, while the D7 versions checks user_id?

Also, there is no duplicate() method, only distinct().

You can use something like dpm((string)$query) to debug the generated query, and dpm($query->getArguments) to get the arguments passed to it.


Does drush sql-sync support inter-db syncing?

No, you cannot switch database types using drush sql-sync.  However, the DBTNG Database Migrator tool will do the conversion for you.


View listing related nodes by taxonomy term

Many of the Drupal features seem magical, but sometimes there are more steps to configure to make them work.

How to use Views Preview with Contextual filters

Contextual filters are strictly linked to individual Fields. It isn't enough to use only the NID Contextual filter (in your Preview) that would then be able to "pull" all the other information, no matter if you have the other Contextual filters set up.

What you enter into the Preview field is what Drupal would take from the URL, or the specified default value as if the URL value is available.

If you have two Contextual filters, you need to enter two filter values into the Preview, one for each filter, in the correct order, separated by /.

To test the complete situation you enter a value for both Contextual filters, for example thriller/35 or 21/35 if Thriller has TID 21 and your first Contextual filter is for term ID and not term name, and 35 is the "current node" NID.

Most Contextual filters have the Exception value set to all. This is a sort of a bypass, the Contextual filter behaves as if it weren't there.

So if you have two Contextual filters and you enter all/all you will see the Views results as if there are no Contextual filters at all.

This is useful when you have to test a Contextual filter while making sure the other one isn't in the way. So you enter all/35 to see all nodes but not the current one (if the current one has NID 35). Or you enter thriller/all so see nodes tagged Thriller but the current one is still on the list.

The Views Preview field (arguments) can test only the part of the Contextual filter that has Provide default value or When the filter value IS available or a default is provided options.

Preview does help to test and configure Contextual filters more quickly, but it doesn't gurantee that you have set them up correctly for cases that don't take values from the URL, so you have to test the Block on the appropriate location anyway.


Making a file downloading system with valid input in a custom drupal 8 form

you can do this with the $form_state->response($response)

  $response = new BinaryFileResponse($file->getFileUri();
  $form_state->setResponse($response);


Show prices excluding Tax/VAT but calculate and display only on checkout

My solution, all replies/comments are welcomed!

Edit rule "Calculate tax" (admin/config/workflow/rules/reaction/manage/commerce_vat_calculate) and add conditions for check if "Entity has field": commerce_customer_billing, commerce_customer_address
For not showing tax on cart (only on checkout): Add condition of type "NOT Data comparison": "Data to compare: [site:current-page:path], Operator: is one of, Data value: cart"
Use hook_commerce_price_formatted_components_alter() for edit labels (incl./excl. Tax) depending on whether the customer is liable for Tax/VAT or not.

Result in checkout process with a customer liable for VAT:


Not exactly. But, you may find it helpful to goto Views -> Settings -> Advanced Settings from admin/structure/views and check the Show SQL Query in your View Preview.

Then goto a view and generate a preview and you will see the SQL statement Drupal is using to generate a query. Some parts of the Views lifecycle to render a views display though are fulfilled by PHP and not SQL. For example drupal Fields are inserted into each row of the the resultset if your display mode is either Fields or Rendered Entity. By this I mean the raw SQL does not perform a JOIN upon every field_data_* table used by your content type -- this is handled in PHP, and not SQL. All of this is also dependent on the Storage mechanism being used by Drupal (the default is SQL, but other backends exist such as NoSQL backends).

I'm just saying the SQL preview will show you ~70% of what Drupal is doing to generate your view. But there is some behind the scenes processing with sql metadata and hook processing going on too.


I rolled a module for that now: https://www.drupal.org/project/ckeditorheight

  This module changes all ckeditor text fields to respect the "rows" setting of the field. How rows translate into pixels is a global setting, configured via a pixel factor and offset.


How to change date format of a custom entity in an update hook?

When I changed base fields in the past they always updated in the plugin definitions on a cache clear. Also if this involved a schema update, by the way, which then produced a warning on the status page that there is a mismatch with the database, for which you then would need what you've described in the question.

In your case, though, my guess would be that the new settings are not valid for a timestamp field. The field formatter datetime_default is probably only working for a datetime field.

So try to change the field formatter in the base field definition to:

    'type' => 'timestamp',


LinkItem: how to create a disabled / null link

A different option:

Add a class to your disabled links.
Create a JS behavior that targets a.your-class and uses preventDefault() on the click event.
Add to libraries file for your module and add library as needed.

...
  $('a.your-class').click( function (e) {
    e.preventDefault();
  });
...


How to get Final SQL query when using Views?

Try the Views Show Query  module

This module shows real SQL query in Views UI during live preview.
'Real query' means it is rewritten by query_alter hooks. For instance, node access checks are added, so this requires selecting the user on behalf of which the query is supposed to be executed. So the module adds 'User ID to show final query' field in views preview form. You must enter numeric user ID in this field to view the real SQL query.
This module makes it possible to show SQL query not only during live preview, but when the view is executed normally. You can add footer to the view with the following PHP code:

<?php
$rows = array();
$view->exposed_input['views_show_query_uid'] = 1;
views_show_query_views_preview_info_alter($rows, $view);
drupal_set_message($rows['query'][0]);
?>


How to resolve my warning in my custom service?

You need to add an argument to your services.yml for the class to be injected:

services:
  custom_forms.custom_forms_service:
    class: Drupal\custom_forms\Service\CustomFormsService
    arguments:
      - @request_stack

Note that you should make a few changes to your service as well:

First, add an type hint for the argument:

public function __construct(\Symfony\Component\HttpFoundation\RequestStack $requestStack) {

Next, you will use the $requestStack instead of Drupal::request():

$this->cityname = $requestStack->getCurrentRequest()->query->get('cityname');


This is most probably a problem with settings for the temporary directory, which is a typical issue moving from Linux OS to Windows or vice versa (this goes for the warning messages that you described)

You should go to: admin/config/media/file-system and set the temporary directory correctly for your local system.

The first two messages are PHP notices which are not critical, but indicating that there is a minor issue within your template files not correctly verifying variables. This is something that would normally be suppresed in a production environment and therefore you might not see this on your other server but it is there too.

By the way: I doubt that you are using Drupal 8 as you are indicating in tags, because page.tpl.php is something that clearly points to Drupal 7.


How to get Responsive Image Styles to work with existing images?

What web server are you using? If nginx you might want to look at your site config.

I have the following in my drupal nginx config:

  # Set up a rewrite.
  location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
    try_files $uri @rewrite;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    try_files $uri @rewrite;
    expires max;
    log_not_found off;
  }

Since you said you never used image styles before, I assumed you might be missing these in your configuration.


Tagging of multiple content items at once

You can create and customize a vbo view, which would allow you select multiple content items and add a taxonomy term to all the selected items at once.

Jason


I think that the main reason prefering EntityFieldQuery over db_select is that you don't have to know about the lower-level structure, in other words: how stuff is stored in the database. This improves loose coupling.


How do I put the copyright / name site in footer

First, make sure your site name is stil configured correctly. You can do this by going to yoursite.com/admin/config/system/site-information.

If the site name is there and still does not show up, then the theme you've selected is likely not working correctly. Head over to yoursite.com/admin/appearance and click on 'Settings' next to the theme you're using. Browse around and see whether there are any options to set the copyright message.

Failing that, modify the message directly in the template files. You will have likely installed your theme to /sites/all/themes/theme_name or /sites/default/themes/theme_name. Browse to this folder and look for a file called page.tpl.php (it may be in a subdirectory). This file will likely contain the copyright message which you can change right then and there. Alternatively, the copyright message maybe in the html.tpl.php file, which should be in the same location as page.tpl.php.


Webform/SwiftMailer - TypeError in encodeString() - must be of the type string, array given

The cause and my solution:
In the Webform's email handler configuration -> "Send from (website/domain)" section -> "From email" field, I used the [site:mail] token.
In EsmtpTransport.php line 378, the $address parameter had a value of ["email@example.com" => string(0)].
By modifying the "From email" field to "Site email address" solved my problem.
Hope this helps.


Expose filter in block to show results on view page

Create a page view using filter you want.Step 1) Enable the block in your View

Step 2) Put the exposed filter block where you want it to be

Step 3 ) Test the result


How can I get translated path aliases for a custom language switcher?

Seems you can do what you want with Url options and a language object like following.

// Get all activated languages.
$languages = \Drupal::languageManager()->getLanguages();

foreach ($languages as $language) {

  // Get the current URL in each language.
  $url = \Drupal\Core\Url::fromRoute('<current>')
    ->setOption('language', $language)->toString();

  // And add it to a custom array.
  $variables['my_langswitch'][$language->getId()] = $url;
}

But as I already said in the comments to your question, this should actually be put in a custom block. And since it's all just about a little bit of changing markup I'd even go for JavaScript here and stick to the built-in language switcher. Also as I'm not sure how above works with caching enabled.

If you prefer getting the paths one-by-one, get a language object first and then use that to get the path alias.

// Get Swedish language
if ($sv_language = \Drupal::languageManager()->getLanguage('sv')) {

  // Get Swedish URL.
  $sv_url = \Drupal\Core\Url::fromRoute('<current>')
    ->setOption('language', $sv_language)->toString();

  // Add it as custom variable.
  $variables['sv_url'] = $sv_url;
}


How to prevent jQuery from loading during ajax callback

This'll do it:

var msg = $('#edit-message');
msg.once('fsrevs_user', function() {
  msg.after('
Do Once
');
});

msg.after('
Do Every Time
');


Can Xdebug be triggered by Drush commands?

you have to remember that with drush you are (most supposedly) in cli, so this should help :

https://stackoverflow.com/questions/1947395/how-can-i-debug-a-php-cli-script-with-xdebug

also, try running the command with the option -d (--debug) - it should give you quite a lot of info about what is going wrong.


Total number of published comments from the logged in user

You do not have to execute a rule every time a user submits a comment. If you have approved a comment for the user, then the permissions systems can handle it.

First create a new role 'Comments approved' and give the role a single permission to 'Publish comments without approval'.

Then create a rule triggered on the event 'After publishing a comment'. Have the rule perform the 'Add user role' action giving the comment author the Comments approved role.

This will mean that the user will be able to publish comments after you have approved their first one, and you will be able to remove the role from the user if they abuse the privilege.

If you want to get really fancy, create another role called 'Moderation only' with no additional permissions. If you have to control comments from a particular user, assign them this role, and in the conditions for the rule, check to see if they are a 'Moderation only' user, and do not assign the 'Comments approved' role if the 'Moderation only role' is present.


The short answer is, you can't. I have an issue posted to hopefully make this, and other filters, a reality soon.

In the mean time, you can however create a custom service resource that uses POST, and from there build a custom callback function to return your desired results.

Alternatively, you can use the Views JSON module (a sub module of Views datasource) or Services Views to easily create a View (with contextual filters, normal filters, sorts, etc) that returns JSON data to you via GET.


Create imagefield with maximum number of values programmatically

When scanning though the field definition of the media fields, you'll notice the multiselect property on line 118. Which gets the value of $multiselect from line 103:

$multiselect = ($field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED);

So in your definition you could try adding this multiselect property with an integer value (eg. 5 to allow 0-5 images), or FIELD_CARDINALITY_UNLIMITED.

$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
        'multiselect' => FIELD_CARDINALITY_UNLIMITED
      ),
    ),
);


Commerce 2 how to set to live paypal signature API Credentials

Ok I sussed this out quicker than I expected. So for anyone else having this issue do this..

Login to the merchant account NOT the developer account.
Menu on Top right Click Profile > Profile and settings
My selling preferences > API access > update
Under Pre-built payment solution > Manage API permission
Under Option 2  > View API Signature
Under View or Remove API Signature expose the fields to show the Credential API Signature, API Username, API Password.

Add these to your PayPal settings in the commerce payment making sure you set this to live.


Add Field to Custom Content Type Programatically

My suggestion is to use the Core Configuration Manager to "automatically" generate all the options you need. See https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration

The approach I'd use would be to create the new content types and all their fields through the UI. Then go to Configuration -> Development -> Configuration synchronization -> Export (tab) -> Single item

From there, you just need to select your various pieces of content one-by-one. For example, if you select "Content type" from the Configuration type menu and then Article (or your custom content type), you'll see the configuration you'd put in the .yml file in your custom module config/install folder. Just eliminate that first uuid: line. If you scroll down past the configuration text area, you'll see the name of the file name you need. For article, it's "node.type.article.yml"

Besides the content types, you'll also need the Field and Field storage configuration types (and probably Entity form display and Entity view display). Pay attention to the config dependencies to make sure you get all the pieces of configuration you need.

Once you get everything you need into configuration files, you can delete everything you created through the UI, install (or reinstall) your custom module and then check whether everything is as you want it. If it's not, you can make changes through the UI and export the config again to fix your custom module configuration yaml files. Or you can just edit the files directly once you see how everything is organized, especially if you're just making little changes like the label or description text for a field.

For me, this approach was much less painful than "scouring through the API", trying to find all the various keys and possible values.


Adding a link to download the original image to a view

You can use the DownloadFile module, which allows you to download Files or Images, and it's usable in views.


Drupal7 unlike drupal6 does not use sessions for anon users. This is an improvement for performance reasons. If you see that there are sessions created it means that there is a contrib module that creates them, so it may be a bad idea disabling them. You can inspect the contents of the session to get an idea which module is using it.

If this is d6 site, you may check the pressflow distribution.


Drupal 6 Views "No result behaviour" use a view

You can simulate this if you instantiate the view in code.  The general steps are

Make a custom block.
In the block view callback, instantiate and execute the view you want, but don't generate output.
Check the number of rows.  If zero, then repeat #2 with your alternate view.
Generate the output for the view, and add to the block output.
Use the block in place of the view where you need to.

If you do everything properly, all of your view templates will be used, so you aren't really losing anything.

All of the views related function are documented at drupalcontrib.org, but I think that is the Drupal 6, Views 3 version.  Googling on views_get_view will also get you started and should lead to examples of generating views with code.  If you have Advanced Help installed, you will also see some information there.

I have done something similar before, but I can't find the code.  I can remember, I will update the answer with some stubbed out code.


I can suggest you a simple way to do this. You can pass the calculated value stored in a variable to the next form function.

Like I had two step form & at first step of the form user select some name from given name(checkboxes), I store them in array & pass them to the next form function like --

function MYMODULE_form($names)//Use your module name instead of MYMODULE.
{
  $return_form = drupal_get_form('MYMODULE_get_form', $names);
  return drupal_render($return_form);
}
function MYMODULE_get_form($form, &$form_state, $names)
{
  $form = array();
  $i = 0;
  foreach($names as $name)
  {
    $form['item']['name'.$i] = array(
      '#type' => 'markup',
      '#value' => $name,
    );
    $i++;
  }
}

Try something like this, if it solves your problem. Use simple variable if you don't have multiple values.


Why can't my user see the private groups they are members in?

I think this has to do with publishing the content.

If I published a group that was marked as invite only, it would then show up in the list of groups as invite only, and content would only be viewable by members. Seems like an imperfect solution though, as to me, an invite only group should be hidden. But if you do use this solution, be sure to mark the content type to default to published.

There's problems with Drupal and unpublished content sometimes. In this case, the usual solution (Views won't display unpublished nodes when explicitly told to) didn't seem  to fix it.


Domain access - prevent redirecting to default domain on account creation

Apologies - it turned out that the default domain had been set as the base URL in the settings.php file. When a user requested an account, they were being returned to the default domain homepage


Contact form - Custom fields are not sending content

Drupal 8 will handle custom fields on contact forms 'out-the-box', they will be rendered in the message body by contact module. If custom fields don't appear in message body, someone messed up.

In this particular case, attribute 'name' of 'input' html tags were modified, and $_POST came with a wrong schema. $_POST['field'] instead of $_POST['field'][0]['value'].

Here shows the hint:
"message":[{"value":"Any message"}] - Correct (field[0]['value'])
"field_customa":[] - Wrong (field[])


How to avoid sending 2 emails at the same time?

You could get pretty close to what you're trying to do by simply (and only) using the Rules module. Some more details about this approach:

Use Rules Event "Before saving content".
Use as many Rules Conditions as needed, for any of your fields you want to validate.
Use Rules Action "**Send Mail".

For more details, Have a look at this rule (in Rules export format):

{ "rules_field_validations_before_saving_nodes" : {
    "LABEL" : "Field validations before saving nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "example1@mail.com, example2@mail.com, example text",
          "subject" : "Subject of eMail triggered via Rules",
          "message" : "Message content of eMail triggered via Rules",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event is "After saving new content", but as a sample I've limited it to content type "article" only (omit or adapt that extra verification as needed).
In my case I have a selection list field with machine name field_optionlist.
This field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As a sample, I decided to add these Rules Conditions (validations), in the order specified:

a validation to ensure that this rule only applies for nodes that have a field with machine name field_optionlist.
a validation about attempts to save a node where "The selected value" of field_optionlist equals Custom.

If all these Rules Conditions are satisfied, then the Rules Action will send an eMail (feel free to change the eMail subject/body to whatever you want).

If you want, you can use the Rules UI to import the above rule in your own site. But before doing so, make sure you have defined 2 similar fields (with machine names field_optionlist and field_free_format_text). As a variation, adapt the machine names to similar fields you already have (attention about field-optionlist versus field_optionlist though, same for the 2nd field, important!).

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Voilà, the above solution depends on Rules, nothing but Rules ...


How can I automate the "Clear Cache" everyday?

Despite you saying it didn't work with cron, I would suggest using cron in some way.  :)

The CacheFlush module claims to allow configuration of this via its UI (although I haven't used it so cannot personally vouch for it).

If you are implementing custom code, drupal_flush_all_caches() will handle the flushing for you.

The Rules module also allows acting on Cron runs. Using rules you could either write a custom action that uses drupal_flush_all_caches() or find a module that provides one (I haven't seen any for D8 but that doesn't necessarily mean one doesn't exist).

You could also potentially do it outside of Drupal, using a cron job on your server to call drush cr for your site.

Aside: I would suggest also considering why you need to do this and what alternatives there are. I can't really think of many (any?) cases where I would want to do this instead of just invalidating the cache of specific content entities/pages as they are changed.


htaccess www redirect not working correctly?

Your RewriteConditions says if starting with www.mysite.com then redirect to http://mysite.com

This rule is not affecting clean urls. Clean urls must enabled at http://mysite.com/admin/settings/clean-urls


Number of users registered daily in table format using views

Here are the steps to create a 'view' to display users details in table format.

1) Add new view and select  Users from Show option

2) Select Format as Table and Add user fields whatever you want to display at output.

Note: If you want to display all users (including blocked) just remove User: Active(yes) from Filter Criteria.


I believe this question is too broad to have a correct answer. As noted in the comments, there are a few ways that this symptom could occur (i.e. modules that intervene), and tools to diagnose further (e.g. the sql query tool).

For my money, your best bet is to first figure out what code is actually handling the url - you might be able to do that with some debug code, or else by inspecting the menu tables (which are also routing tables in Drupal 6).


How to restore complete database keeping the site in maintenance mode in Drupal 7

Add a maintenance-page--offline.tpl.php page to your theme , and whenever the connection to DB is lost drupal will show this page instead of an error , but designing this page you cant use formal variables which are used in theme like $title or $styles and ... cause these are stored in DB and in your situation there is no access to that , so you must add them using php or just implement some strings .

Check this page for more help : Theming the Drupal maintenance page


You forgot to print the results. Use:

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

Explanation:

During a page request, Drupal keeps all the data it loads in PHP arrays for as long as possible. The reason for this is, that as long as the data is in arrays, it can be changed by other elements. This is the power of Drupal's module system.

The array posted in the question is such a data array, it's called a "Render array". Eventually this array must be converted to HTML, this is what render does: it converts a drupal render array to an HTML string. Calling render often happens at end of a page request.

So calling render gives you an HTML string that should be returned to the user, e.g. by printing it in a template file.


How can I get a list of all active enabled contexts on drupal site with drush?

i would say something like this:

drush php-eval "print_r(context_active_contexts());"


Get radio field value in data selector in rules

Step 1

To get your rule to work like you want it to work, for the "Complaint"-part you should use these Rules Conditions (in the specified order):

Entity has field, for your "select list" field.
List contains item, whereas:

the list is also about that same "select list" field.
the item you want to check for (if it is contained in the list) is "Complaint".

With those 2 Rules Conditions, your Rules Action to be performed is to send the eMail to complaint@web.com.

For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.

Step 2

Create a similar rule by reepeating Step 1, but now for "Feedback".

Step 3 (optional)

If you'd be willing to also use the Conditional Rules module, you could merge the rules from Step 1 and 2 in a single rule, ie because this module allows you to include Rules Conditions as part of Rules Actions.


How to pass an array to drupal7 form select as value of #options?

Have a look at the Form API docs for select lists. #options is the correct property to set the options, and #default_value is used to set a default value.

Using #value means the user input will be ignored, and whatever you've set as #value will wind up being the submitted value. Since you're declaring a non-multiple select list, that value needs to be an integer (not an array) anyway.

Try something like this:

$region_value = array(0 => 'US', 1 => 'EU');
$form['region_options'] = array(
  '#type' => 'select',
  '#prefix' => 'Region',
  '#options' => $region_value,
  '#default_value' => 0, // e.g. Set US as default selected value (appropriate array key from $region_value)
);


Make sure your module is named custom_block to match the function names you have used for your hooks. If you have to change the name of your module you will need to re-enable it.
Technically you should uninstall the module, then rename and re-enable - unless it isn't properly installed ans you can't uninstall it. This will keep unwanted data out of your database.

You also should not be printing things outside of functions in module files, like the views code at the top is doing.

Printing markup should be done at the theme level in templates, or in appropriate functions in your module (like you are going in your hook_block_view()).


How can I remove the descriptions from the registration page programatically?

Your structure is just a bit off.

$form['name']['#description'] = t('');

Should be:

$form['account']['name']['#description'] = t('');

If your ever unsure of what an array looks like, always a good idea to download devel and dpm item so you can see what the structure looks like.


how to render create page form & list of contents in page.tpl.php

It is recommended to render the forms either in preprocess function or in the custom module. Example of rendering the form in preprocess function:

function MYTHEME_preprocess_page(&$variables) {
  // Assigning node_admin_content form to the variable.
  $node_admin_content = drupal_render(drupal_get_form('node_admin_content'));
  $variables['node_admin_content'] = $node_admin_content;

  // Assigning page_node_form form to the variable.
  $page_node_form = drupal_render(drupal_get_form('page_node_form'));
  $variables['page_node_form'] = $page_node_form;
}

Now to render this form in page.tpl.php:

Admin Page

  <?php print $node_admin_content; ?>

  <?php print $page_node_form; ?>


Possibly you can try this :

Create a views block with current uid in contextual filter & have all the account fields in that views block
Use 'editablefields' module & make use of it for Inline Edit
Enable the block where you need

Hope it helps


Instead of using the Webform Report module, you can use Views and Views Aggregator Plus to display the submission data. You can use the aggregation function sum for the selected fields (to aggregate your webform submission results tables).

Credits: Waluyo Adi Siswanto.


How do you switch a site's language by using GET variables? Is there a module?

Use the Language Switcher module for multiple Language.

  Language Switcher for Drupal 7 is an enhancement for core language switcher block in local module. It's very useful for websites with multi-languages where you want to display content in different languages side-by-side


How do I allow users to remove their pictures from their user profile?

If you use Field Permisions module, you should check the permission settings for that field. There are 5 permissions for each field: "Create own, edit own, edit anyone's, view own, view anyone's". It seems that you didn't give the 'edit own value' permission to users.


Can't get value from cache_page table only cache_default

Provide the cache bin page, otherwise it defaults to default:

\Drupal::cache('page')->get($cid)


You Can go for Twilio Module

The Twilio module provides integration with the Twilio cloud communication platform
allowing for your Drupal site to integration Voice and SMS functionality.

What you can do using this module

Ability to store and access TwiML
Rules event to act on incoming SMS message
Rules action to send an SMS message
Rules event to execute TwiML scripts
Hook for incoming SMS messages
Hook for incoming voice calls
User object phone number storage and validation
Uses libraries api to manage the Twilio php library
Support for international texting
Support for MMS


Stupid bug. The script would change the current directory. Drupal code, it seems, assumes that it will be running from Drupal root, so the file attachment paths are relative internally. chdir(DRUPAL_ROOT) before calling file_save_data fixed it.


How to add an image upload field in a custom Field Type

What you want to do, is to save a reference to the file which is uploaded.

Since what you are making is an image upload with extra text field, you should consider using either

\Drupal\image\Plugin\Field\FieldWidget\ImageWidget
\Drupal\image\Plugin\Field\FieldWidget\FileWidget

as foundation to your widget. That way you should be able to reuse much of the trick image/file handling and just add custom parts or overrides for your custom widget.

You should also consider using either

\Drupal\image\Plugin\Field\FieldType\ImageItem
Drupal\file\Plugin\Field\FieldType\FileItem

as foundation to your field type, since they also handle a lot of things for you. The image variant adds a lot of stuff, like alt, height, width, which is something you probably want/need at some point, so no reason making all of this yourself.


Additional tab in custom module's admin configuration page

It seems that first main path 'admin/commerce/leads' needs to be defined, and then other two items added.  The first item inherits the properties of the main menu item, and the second defines its own callbacks. Far from obvious, but it works for me now:

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

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/active'] = array(
    'title' => 'Active',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed',
    'page callback' => 'leads_subscribed',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('administer leads'),
  );

  return $items;
}


How to get Drupal 7 to search attached PDF and Word documents

To help you, you've this nice module Apache Solr Attachments. If you download the module you'll have a README.txt that give you some clues how to help you install and configure Tika.


How to display additional fields in user profile?

This is just a CSS issue. Use developer tools/firebug to determine the class/id of the element wrapping each field, and add a CSS rule such as the following to your theme:

.field-wrapper-1, .field-wrapper-2 { display: block; }


How to display multiple blocks using a custom calendar module?

It looks like you should review that "return $block;" that you inserted in the while() statement.

PS: not sure why you didn't (couldn't) post your own answer, which is why I do so now anyway ...


How can I inject container to a class with constructor having arguments?

Instead of adding $options to your create method you shall add a method to set the options.

Take a look at this code to see how you can inject $logger in your class:

class MigrateUpgradeDrushRunner implements ContainerInjectionInterface {

  /**
   * The logger channel factory.
   *
   * @var LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The options.
   *
   * @var array
   */
  protected $options = [];

  /**
   * MigrateUpgradeDrushRunner constructor.
   *
   * @param LoggerChannelFactoryInterface $logger
   *   The logger channel factory.
   */
  public function __construct(LoggerChannelFactoryInterface $logger) {
    $this->logger = $logger;
  }

  /**
   * {@inheritDoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.factory')
    );
  }

  /**
   * Set the options.
   *
   * @params array $options
   *   The options.
   */
  public function setOptions(array $options) {
    // Do something...
  }

}


Get node bundle (content type) from EntityInterface

I did manage to find it after all $entity->bundle() it was pretty easy ...

 if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article') {


Yes, any file uploaded into an image field in Drupal is accessible by its File API.

To address your issue, there are many ways to go about this. One solution that comes to mind is a multistep solution:

Create a content type with an image field. You'll be using this content type to manage any background images you want.
On the node type that you want to add an image background to, add an Entity Reference field that references the node type created in #1 with a Checkboxes/radio button widget.
Edit your theme's template.php to add/update the MYTHEME_preprocess_node($variables) function. Inside of this function you'll be using $variables['node'], node_load(), file_load(), &  drupal_add_css() to retrieve your selected image node reference, load the node, lookup the referenced file, & add inline CSS to your node display.


1)

Follow the Path below:

C:\Program Files (x86)\DevDesktop\AcquiaDevDesktop\datamodel.xml

2)

Open the " datamodel.xml " using the Notepad++ or any other similar programming language editor program

3)

Edit the Link written within:

 HERE HERE HERE

 HERE HERE HERE

to any link required by you .


Kernel tests: Url toString with language option

Solution
I could solve it by register the PathProcessorLanguage class and add the language.types and language.negotiation config.
public function register(ContainerBuilder $container) {
  parent::register($container);

  // Define the default language.
  $language = Language::$defaultValues;
  $language['id'] = 'de';
  $language['name'] = 'German';
  $container->setParameter('language.default_values', $language);

  // Register PathProcessorLanguage.
  $container->register('path_processor_language', PathProcessorLanguage::class)
    ->addTag('path_processor_outbound', ['priority' => 100])
    ->addArgument(new Reference('config.factory'))
    ->addArgument(new Reference('language_manager'))
    ->addArgument(new Reference('language_negotiator'))
    ->addArgument(new Reference('current_user'))
    ->addArgument(new Reference('language.config_subscriber'));
}

protected function setUp() {
  parent::setUp();

  // Add additional languages.
  ConfigurableLanguage::createFromLangcode('fr')->save();
  ConfigurableLanguage::createFromLangcode('it')->save();

  // Define language settings.
  $this->config('language.types')->setData([
    'configurable' => ['language_interface'],
    'negotiation' => [
      'language_interface' => [
        'enabled' => [
          LanguageNegotiationUrl::METHOD_ID => 0,
        ],
      ],
    ],
  ])->save();

  $languageKeys = array_keys($this->container->get('language_manager')->getLanguages());
  $this->config('language.negotiation')->setData([
    'url' => [
      'source' => LanguageNegotiationUrl::CONFIG_PATH_PREFIX,
      'prefixes' => array_combine($languageKeys, $languageKeys),
    ],
  ])->save();
}

Addition
If you want to use/test path alias configs too, just register the AliasPathProcessor class...
public function register(ContainerBuilder $container) {
  parent::register($container);

  // ...

  $container->register('path_alias.path_processor', AliasPathProcessor::class)
      ->addTag('path_processor_outbound', ['priority' => 300])
      ->addArgument(new Reference('path_alias.manager'));

  //...
}

... and add the path alias entry for the specific language.
protected function setUp() {
  parent::setUp();

  // ...

  $pathAlias = PathAlias::create([
      'path' => '/foo',
      'alias' => '/bar',
      'langcode' => 'it',
    ]);
    $pathAlias->save();

  // ...
}


You can put this on html.tpl.php in drupal 7 , else you can have it on page.tpl.php.

As a note if you are putting it on page.tpl.php remember you have to put it on every other page overriding template page--front.tpl.php etc.


Is it possible to have 2 different thumbnail image styles for the same field?

You can put more than one filter on a preset, so it is possible, depending on the aspect ratio of the new and the old, that you can add a first filter that will remove the black bands and a second that will change the size.

Otherwise, you might try programmatically making image style change the aspect ratio of all your old images, deleting your old images, then copying the images in your changed image style directory to your root file directory. Image styles doesn't change the name of the file.

If either of those options doesn't work for you, you can create a custom field formatter that looks at the file id and decides which image style preset to use (as you suggested above except don't so this in the theme system as the new formatter would be available to any node view as well as in the views module). See: http://www.computerminds.co.uk/articles/creating-new-field-formatters-drupal-7


First add a paragraph--your_paragraph_machine_name.html.twig to the templates directory of your theme.

Accessing your paragraph fields can be done by adding twig variables in a format similar to {{ content.field_your_field }}.

If you want only the field value, that's a little trickier. For instance if you had a List (text) field and wanted to get the value from the selected option, you could do something like:

{% for item in content.field_select_list %}
  {% if item is iterable %}
    {% for key,value in item %}
      {% if not value is iterable %}
        {% if key == '#markup' %}
          {{ value }}
        {% endif %}
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}

You can always run a {{ dump(content) }} to see the structure and get the values you're looking for. Hope this helps!

EDIT: You can avoid all the silly nested loops. The above example should be written like:

{% set value = content.field_select_list.0['#markup'] %}
{{ value }}

For a Text (plain) field it might look something like:

{{ content.field_text.0['#context'].value }}

To get a URL value from a Link field I've seen suggestions like:

{{ content.field_link['#items'].0.value.uri }}

But it would have an "internal:/" prefix, so I've had better luck with something like this:

{{ content.field_link.0['#title'] %}


Sound like you have removed a dependency from the codebase that a field a certain field depends on, usually it's a module. If that's the case you will need to reinstate it, then uninstall it. But also, you might want to try drush entup and drush updb

Also, it's a good idea to check the error reports for a more detailed explanation of what has happened


Are you running the alpha-4 or the current dev version of the feeds module? There have been a number of tickets discussing the same error condition you are having with node_save on import that coalesced around this issue on Drupal.org with a resulting patch committed to the current dev branch. You can try downloading the current dev branch of feeds (almost a year older now than alpha-4) or applying the patch at #25 in the above issue if you don't want to accept all of the updates since the last alpha release.


Views: how to make an OR condition between filters and contextual filters

There is a module for that (albeit a sandbox module). Download Views arguments in filters. As it is a sandbox module you will have to use git.

With this module you add your contextual filter as a global null contextual filter. Then in your normal filter's section, you refer to your contextual filter via the format %N (%1 etc). In this way you bring your contextual filter down to the normal filter section in views, and you can now apply the conditional clauses there, as well as the other filter logic.


How can I ensure that fields from a Views query plugin work as tokens?

Eventually I realised that it was only tokens containing hyphens that weren't working, and sure enough, it turns out that hyphens are not allowed in Twig tokens. Or, to be more accurate, they are interpreted as minus signs (https://www.drupal.org/project/drupal/issues/2371633). That was why the {{ access-url }} token was returning zero: access minus url equals zero, apparently. So I just replaced all of the hyphens with underscores.


Can I add CSS to a YAML generated page ?

You can still use the hook_preprocess_page for a specific path like this:

/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_page().
 *
 * @param $variables
 */
function mymodule_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/solr-search/content') {
    $variables['#attached']['library'][] = 'my_module/my-css-library';
  }
}


Restricting "view content" to members of a group

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

It seems that you would want to grant access to what, in Group, is called "Members" (similar to what in your question is called 'Group members'). But you woudn't allow access to "Anonymous" (site visitors that are not logged it). However, you also need to think about which access you want to give to "Outsiders" (=  logged in users who are not a member of a group).

With the above in place, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.

More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.


Profile2: How to understand if user has not an associated profile?

If you are doing profile2_load_by_user and profile object is showing, then its profile object has been created. If Profile object has not been created for a user, then its profile object will be empty, means its pid has still not been created.

You can check for the same, in your database, inside profile table.


Why is migration lookup failing during synchronisation of Group entities?

s/migrate_plus.migration.users/users/

The "migrate_plus.migration." is not part of the migration plugin ID - it is only part of the filename for the config entity.


It is required Invite by e-mail module, it provides an Invite Type.


Hierarchical menu of all Terms of a Vocabulary & Contents of the Terms

I think this is just a straightforward menu - nothing automatic needed. When you add a new node, just choose it's parent menu item.


Ability to order fields for each content in a content type

It's not clear how you define the order of the field, but if you put extra information in the node and want to use this to change the order of the fields before output, you can use the weight property to change the order in an alter hook:

hook_node_view_alter(&$build) {
if ( $build['field_sort_order']['0']['#text'] == 'sort it this way' ) {
   $build['field1']['#weight'] = -10;
   $build['field2']['#weight'] = 10;
   ...
}
...


Node is not created, but nid is returned

Hope this will help you,

In Drupal 7, The $node object you pass to node_save() wouldn't get it's nid member populated unless the node has been successfully saved to the node table in the database.

The auto-increment ID actually comes from the database table so if the $node object has a nid, you can pretty much guarantee the record has been successfully inserted into the table.

Im just guessing check for "node" table paging.

Clear drupal cache and check again.

I have used the below code and it is working fine for me, you can refer this.

  $node = new stdClass();
  $node->type = "page";
  node_object_prepare($node);
  $node->title = 'test node';
  $node->language = 'it';
  // Set node body details
  $node->body[LANGUAGE_NONE]['0']['value'] = 'test body';
  $node->body[LANGUAGE_NONE][0]['summary'] = text_summary('test body');
  $node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
  //.. other fields goes here
  $node->uid = 1;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;
  if ($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('NODE : ' .$node->nid);
  }


What is the best way to set up demo for Drupal themes and live switch between them?

http://drupal.org/project/switchtheme is the one to use for that.

  Adds a block to allow users to switch between enabled themes.

  Themes can be given 'user friendly' names and access can be controlled
  by user role.

If you need to enable/disable blocks for certain themes, do so at Admin > Structure > Blocks for that theme.


No, Drupal doesn't place restrictions on the names of any template file or folder.

Restrictions for file naming are handled at the OS level.


Password strength with password type field on registration

You can do this with jQuery, something like this should work.

$(document).ready(function () {
  $('.password-field').blur(function () {
    $('.password-comfirm').val($(this).val());
    $('.password-comfirm').hide();
  });
});


Can my site's administrators bypass required profile fields during user creation?

The only easy way I can think of is to make this fields not required. Then the admins can leave it empty.

I'd just let the Admins enter the extra data, even if you don't really need it. Admins are specially trust worthy users. It's not likely that you have a lot of them.

If you must: Create your own form using Drupa FAPI and create a new user by calling user_save in the submit function.


AJAX form - replacing #default_value not working

This is taken from the description of #default_value in the form api documentation:

The value of the form element that will be displayed or selected
initially if the form has not been submitted yet

Because your form has been submitted, it wont be using #default_value. Just use #value, the user will still be able to change it.
2021 edit.....
As people have pointed out, the above is wrong as although it will allow you to set the value, it wont allow the user to submit an altered value.
Now using Drupal 9, in a form alter, I needed to set some default field values when an ajax button (which I inserted) was clicked.
I needed to set default values on the node "body" field and "field_url" link field.
I removed the user input for these fields before setting a default value.
$userInput = $form_state->getUserInput();
unset($userInput['body']);
unset($userInput['field_url']);
$form_state->setUserInput($userInput);

$form['body']['widget'][0]['#default_value'] = 'my default value set after ajax callback';
$form['field_url']['widget'][0]['uri']['#default_value'] = 'my default value';

To be honest, I am not 100% sure it is the correct way, but it does work.


I figured out my problem and it had to do with classes as I suspected. For whatever reason, a snippet of javascript that was not previously interfering with the preview functionality just recently started breaking the view. I'm still not entirely sure why but I'm guessing I removed the class in another template and so it was never being rendered and now my javascript was overwriting it.


Theme multiple rendered nodes as item_list

This should render multiple nodes using an item list.

$nodes = node_load_multiple($nids);
$build = array(
    '#theme' => 'item_list',
    '#items' => array_filter(reset(node_view_multiple($nodes)), function(&$node) {
        if (!is_array($node)) {
            return false;
        }

        $node = drupal_render($node);
        return true;
    }),
);

return drupal_render($build);


How to add more than 7 links in the shortcuts bar?

It's the shortcut_max_slots() function that makes that decision; fortunately that function wraps around the return of a variable from the database (also called shortcut_max_slots), so you can simply set that variable and be done with it.

There's no way to make it unlimited without hacking the shortcut module directly, so you probably want to go for a high number:

variable_set('shortcut_max_slots', 100);


Review this post

You will find there is a value box and a output box.

Your code above suggest you are doing the display from the value box and that won't work.

move most of your code to the value box and then end with:

value = $stockex[2];

then paste

<?php
    print $value
    ?>

in the output box.

Good Luck!


How to redirect form to a url having wild card character in drupal?

You cannot do this in a form because the redirect has to be definitive. You much know the variable being put into the % via some means.


is there a way to make template for set of nodes?

You can't do like you explain.

What you can do instead is to add a custom template suggestion for the specific nodes in the preprocess_node function to make the nodes use a specific template that can have any name.


Superfish - File not found: sites/all/libraries/superfish/sfsmallscreen.js

Download the Superfish library and extract it to sites/all/libraries/superfish (so that the superfish.js will be located at http://example.com/sites/all/libraries/superfish/superfish.js)


How can I detect if the current viewed page is administrative?

This can be done with path_is_admin(current_path()).

For example, the following hook implementation can be used.

function mymodule_init() {
  if (user_access('administer modules') && path_is_admin(current_path())) {
      drupal_set_message(t('Message'));
  }
}