Facebook profile details I have a webform (survey) on my site, some of the fields are personal details (age, name, DOB, etc). I want to actually force the user to login with facebook and pro grammatically obtain those few details from facebook.

Which module(s) would I be most interested in, in achieving?

Find the drupal facebook module listing on this link

So far I find fb module will be worth starting with.

  This set of modules turns Drupal into a platform for developing
  Facebook Applications. This allows you to embed your content and
  features within facebook, or allow facebook users onto your site via
  Facebook Connect.

A quick glance for module description is here.


Empty a field when it is disabled I am using #state values in a hook_form_alter() to disable field_2 if field_1 (a checkbox) is checked. It works and all is good.

Now I want to empty field_2 as well. I cannot see a way to do that with the #state.

How can I make sure that values don't get saved for fields that are conditionally disabled, even if the user enters a value first?

Interesting question. Since the $form_state variable is passed by reference to all form validation & submit handlers, you can modify it prior to it reaching the submit handler that saves it. What about adding a new validation handler that will empty the $form_state['values']['field_2'] value if the field is disabled in $form? That should ensure that the field is empty by the time anything tries to save it.


Restrict translation and editing of node to one language Edit
I found this in Workbench Access issue queue:
https://www.drupal.org/project/workbench_access/issues/2982941#comment-12670744
It seems as if I need to deactivate the translate *bundle* *node* permissions, because if those are set, the permission will be short circuited and no other access restrictions may apply, and create a hole bunch of new *translate *bundle* *node* *language* permissions on my own. In my case we have 15 node types and 6 languages. That would result in 90 new permissions. That is overwhelming.
Original Question
I'm trying to restrict the access to creating and editing of nodes in the Drupal admin section to only one language for a user. I didn't find a module which provides for this feature. Is there any module that does this?
I then tried to create my own module. I came up with this solution
File: custom_i18n_access.module
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Implements hook_node_access().
 *
 * Prevent editor role to edit and/or delete fr/en nodes. Quick and dirty.
 */
function custom_i18n_access_node_access(NodeInterface $node, $op, AccountInterface $account)
{

    $roles = $account->getRoles();

    if (in_array('administrator', $roles)) {
        return AccessResult::neutral();
    }

    if ($op !== 'update' && $op !== 'delete') {
        return AccessResult::neutral();
    }

    // Access should be restricted only if this permission is set
    if (!$account->hasPermission('custom_i18n_access_restrict')) {
        return AccessResult::neutral();
    }

    $current_language = \Drupal::languageManager()->getCurrentLanguage();
    $lang             = $current_language->getId();

    if ($account->hasPermission("custom_i18n_access_{$lang}_allow")) {
        return AccessResult::neutral();
    }
    return AccessResult::forbidden();
}

File: custom_i18n_access.permissions.yml
permission_callbacks:
  - Drupal\custom_i18n_access\Permissions::permissions

File: src/Permissions.php
<?php

namespace Drupal\custom_i18n_access;

class Permissions {
    public function permissions() {
        $languages = \Drupal::languageManager()->getLanguages();

        $permissions["custom_i18n_access_restrict"] = [
            'title' => t("Restrict language access"),
            'description' => 'Restrict the edit access of nodes',
        ];

        foreach($languages as $lang) {
            $permissions["custom_i18n_access_{$lang->getId()}_allow"] = [
                'title' => t("Allow to edit @lang content", ['@lang' => $lang->getName()]),
            ];
        }

        return $permissions;
    }
}

This custom module successfully restricts the editing and deleting of existing content to only the language I specified in the permissions. But it does not prevent new translations of the content into  other languages.
As I see it, the HOOK_node_access hook is not called for every language when on the translations subtask page. How can I achieve this? Is there a different hook for that? I didn't find any help online.

I would suggest here checking NodeTranslationHandler class, in entityFormAlter you could find a way how to restrict a user from creating a new translation.


How to show directions on a map when using the Geolocation Field module I installed the Get Directions and the Geolocation Field modules.

The Geolocation Field module displays a map, but I also want directions.

How do I get the directions shown on a map? Do I need another module?

When you download the Get Directions module, it has a README.txt that explains how to set up the module.  Make sure to:

Make sure both modules are enabled, then configure the Get Directions module at: Administer > Site configuration > Get directions.

Go to Administer > User management > Permissions and set up permissions according to your needs.

Configure up a Geolocation field on a content type, then create a node of that type and fill in the field.  You should then be able to use this URL pattern to see Get Directions module work with that node by going to

  http://{hostname}/getdirections/location/to/{node_id}

or

  http://{hostname}/getdirections/location/from/{node_id}

where {hostname} and {node_id} are filled in with correct values.

Here is the full section on all the options from the README.txt:

  For instance, if you want to "preload" the getdirections form with information
  about the destination use a URL in this format:

  getdirections/location/to/99

  Where '99' is the node id (nid) of the location. The user will only
  have to fill in the starting point.

  To do it the other way around use getdirections/location/from/99

  You can also get a map with waypoints
  getdirections/locations_via/1,2,3,99

  If you have both the starting point and destination node ids then you
  can use getdirections/locations/1/99

  Where '1' is the starting point node id and 99 is the destination node
  id (note the 's' in locations)


Updating a taxonomy term, with extra fields - taxonomy_term_update does not exist In Drupal 7, I am trying to update and delete some taxonomy terms in the proper way. So, instead of attacking the database directly, I am using taxonomy_term_delete for deleting by tid. However I cannot find taxonomy_term_update and about taxonomy_term_save, it seems not to have access to the extra fields that I added (a few fields, text and integer).

How can I make the following pseudocode to work? ( this does not pretend to work, it is just some pseudocode in a dialect of Drupal to make the question more understandable )

 $term = taxonomy_term_load ( $tid )   // or equivalent function
 $term->extra_field_1 = 23; // extra_field_1 would be numerical
 taxonomy_term_save($term) // o taxonomy_term_update or equivalent

Result: the extra_field_1 value of that term ( with tid = $tid ) is set to 23.

try

    $terms = taxonomy_term_load($tid);
    // echo "<pre>";
    // print_r($terms);
    // die();
    //dsm($terms);
    $terms->extra_field_1[LANGUAGE_NONE][0][$column_name] = 23;
    taxonomy_term_save($terms);

Use print_r or dsm(devel module if installed) and check the "$column_name".

After print the $terms you able to get "$column_name" replacement. Update that and save.


Problem with JS linked to an Ajax loaded page I am trying to load a form via ajax, the PHP callback that send the data to the Ajax request looks like this :

function group_form (){

        $node_type = 'group';
        $form_id = $node_type . '_node_form';
        $node = new stdClass();
        $node->type = $node_type;
        $node->title = 'helllooo';
        $node->language = LANGUAGE_NONE;
        $node->path = '';
        node_object_prepare($node);
        $return=drupal_get_form($form_id,$node);

    echo render($return);
}

I use to have a problem when using return instead of echo as mentioned in this Q, where the whole page was being sent via Ajax instead of just the form element. However now that i use echo all the script attached to that form do not get reloaded, witch cause problem as my form uses the date module with a jQuery popup calender, and infinite value fields witch need some Drupal JS in order to add multiple values without page reload.

So i wonder if there is a way around that, if not, anyone has anyidea of what script i should reload on the ajax succes callback in order to have my date module popup calendar and the drupal "Add more" function for infinite value field working ?

EDIT: I found that using Drupal.attachBehaviors(jQuery('#LoadedContent')); seems to be helping as it brings me from this

to this ,

though clicking on the "Add another item" Button still reload the page and i end up with this :

Thanks a bunch for the help.

Have a look at the Ajax Framework. It will make your life way easier. You can probably accomplish everything you're trying to do with out a single line of js.


How to force openid login from a single provider in Drupal 7? So with the current Drupal 7's OpenID module, one must click on the "OpenID" on the main page, which the user then enter the url of the OpenID provider to link up to. Assuming I know exactly what provider I want to use (my university's), there some way I can make it such that as soon as a user visits the homepage, or any part of my drupal site, the first thing it does is authenticates with that specific provider url before it even shows the page?

The reason being is I want people within the university network to be able to go to the site and automatically see who they are without having them perform that extra step of clicking on an "openid" button. Much like a single-sign-on solution.

You must create a custom module to generate a page "/login" that start OpenID authenticate.

Create a module with this code :

/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['login'] = array(
    'title' => 'OpenID Login',
    'page callback' => 'openid_login',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/*
 * Menu callback; start openid authenticate
 */
function mymodule_login() {

  $return_to = url('openid/authenticate', array('absolute' => TRUE, 'query' => array('destination' => 'user')));

  openid_begin("https://www.myopenid.com/", $return_to, array());
}

The example works with the myopenid.com provider.
Go to "/login" on your website to log in.


How do I add a Confirm Order button in Commerce Checkout? Using Commerce Kickstart 2

With the default checkout, the payment is taken on the Review page. Then the next page (Payment) processes with the merchant (in our case Authorize.Net).

Then there is a Confirmation Page... and the only pane on that page is Express Checkout Review and confirm' (does that refer to Paypal?).

I guess I'm expecting to a see a 'Confirm Your Order' button of some kind, but it never appears. Basically, the order is processed and goes immediately to 'Completed'.

How do I get that Confirmation page to appear?

Customers will expect to see a Confirm Order page -after- they have entered their payment... rather than going -immediately- to 'Completed'.

I recommend starting at the website.com/admin/commerce/config/checkout/rules address, which will bring you to settings page where you are seeing "Express Checkout" options, which to my knowledge is not a PayPal feature and unfortunately is just shares the same name as their Express Payment Processor.

Next you want want to create a checkout rule, which will give you more control over the order process, which can be found at website.com/admin/commerce/config/checkout/rules

This process might start to get difficult, but essentially you want to create a Rule that will trigger a more detailed confirmation page, which can probably handled numerous ways and probably out of the scope of this question.


Do we have Node Reference : Representative node similar to the Taxonomy term: Representative node Using Taxonomy term: Representative node we can get a node that represents a taxonomy term. Similarly is there a way I can get a node that represents a particular node reference field.

Use Case : I have two content types College and Teacher. For each college, I want a teacher who was recently added to the college.

The References module doesn't seem to provide a Views relationship like that. Here is one way to achieve the required functionality in your case:

Add a reverse Node Reference relationship to get teacher nodes referencing the college. This will get you all teachers for each college.
Implement hook_views_query_alter() and add the extra condition utilizing a subquery:

function mymodule_views_query_alter(&$view, &$query) {
  switch ($view->name) {
    case 'college_teachers':
      $expression = '
        field_college_node.nid = (
          SELECT n.nid
          FROM {field_data_field_college} fdfc
          INNER JOIN {node} n ON n.nid = fdfc.entity_id
          WHERE fdfc.entity_type = "node" AND fdfc.field_college_nid = node.nid AND n.type = "teacher" AND n.status = 1
          ORDER BY n.created DESC
          LIMIT 1)'
      $query->add_where_expression(0, $expression);
      break;
  }
}

(The Views-generated field_college_node alias is a bit misleading because in fact, it will reference the teacher node, not the college one.)


Using hook_menu to add a child to a menu item So I create a menu item called Sponsorship in administration in the following way:

function eac_sponsorship_menu() {
  $items['admin/sponsorship'] = array(
    'title' => 'Sponsorship',
    'description' => 'This is where all of the child sponnsorship data is stored',
    'page callback' => 'system_admin_menu_block_page',
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
    'access callback' => 'user_access',
    'access arguments' => array('access sponsorship section'),
    'plid' => 1,
    'weight' => -500,
    'expanded' => TRUE,
  );
    return $items;
}

If I want to create another menu item directly after this, in the same function, how do I make it a child to this previously defined 'Sponsorship' menu item?

I have seen examples that use a DB lookup to get the plid value. This seems a bit counter intuitive bearing in mind I've only just created the Sponsorship menu item, is there a simple way to do this using the API?

For example

$items['admin/sponsorship/child'] = array(
  'plid' => //simple API function to get admin/sponsorship mid?
}

Edit

I think I've just answered my own question...I don't need to define plid, the path of the array $items is enough:

$items['admin/sponsorship/child']

Is this correct?

An example child item would just fall under the parent item in the path hierarchy, no need for plid.

e.g

  $items['admin/sponsorship/child'] = array(
    'title' => 'Sponsor child',
    'description' => 'This is where all of the child sponsorship data is stored',
    'page callback' => 'mymodule_sponsor_child_page',
    'access arguments' => array('access sponsorship section'),
    'type' => MENU_NORMAL_ITEM
  );

system_menu has some good examples of menu item containers, using system_admin_menu_block_page,  e.g admin/appearance/*

Make sure you clear menu cache to get any new menu item to show up there.


Why am I getting this error for the schema I define in my module? I'm building a module for Drupal 7, but I have troubles with my schema, and I don't understand why.

This is my schema.

$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'unique keys' => array('id')
    );

I get this error.

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
  You have an error in your SQL syntax; check the manual that
  corresponds to  your MySQL server version for the right syntax to use
  near 'NULL DEFAULT NULL,  end_time NULL DEFAULT NULL, duration INT
  unsigned NOT ' at line 5: CREATE  TABLE {table_name} ( id INT
  unsigned NOT NULL auto_increment, nid INT  unsigned NOT NULL, oid
  INT unsigned NOT NULL, start_time NULL DEFAULT  NULL, end_time
  NULL DEFAULT NULL, duration INT unsigned NOT NULL, PRIMARY  KEY
  (id), UNIQUE KEY 0 () ) ENGINE = InnoDB DEFAULT CHARACTER SET
  utf8;  Array ( ) in db_create_table() (line 2717 of
  /Applications/MAMP/htdocs/project/www/includes/database/database.inc).

How can I fix this error?

I've managed to fix it. I've altered 2 things from my original schema, the first issue was that Drupal 7 no longer supports 'type' => 'datetime', instead use 'mysql_type' => 'datetime'. The second was 'unique keys' => array('id'), I removed this and everything works correctly.
Solution...
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'mysql_engine' => 'InnoDB'
    );


Show title of article instead of date in a Views block I'm using the Views module to show a list of the 3 most recent articles posted on a site. I've set the filter granularity to the specific date of posting and it shows three dates with bullet points in the block. What I would I like to do is get rid of the Bullet points, have the date formatted MM/DD/YYYY and then on the line below the date have the link to the article where the link is the title of the article.

I want this to look like this, where TEXT is the title of the article it links to.

Try the following steps:

Create new date format as you want (MM/DD/YYYY).
   admin/config/regional/date-time/formats
Create Date type and assign your format.
   admin/config/regional/date-time
In views: Select your date type under "Choose how users view dates and times:" when you add your date field under "FIELDS".
Add (Content:title)title field (after date field) and Enable the Link this field to the original piece of content checkbox.
Bullet point from your css


How to change rendering of div order in a field? It appears that the module label help is not compatible with Date fields. It allows you to enter text, but it does not display.

I found out that in the div with class description should be above div id edit-field-geboortedatum-und-0-value instead of below

How to achieve this? Should I change a weight key in something?

You can use $form['#after_build'] to modify a form. Put below element at the end of your hook_form function.

$form['#after_build'][] = 'FORM_NAME_after_build'; //Calls function

After build function to change the position of DIV

function FORM_NAME_after_build($form, $form_state) {
  drupal_add_js('jQuery(document).ready(function ($) {
    $("#edit-field-geboortedatum-und-0-value").insertAfter($(".description"));
  });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

  return $form;
}


Replace a content type name with a different string, in a view I have a view that appears as the following table:

Title            Content type          Published
------------------------------------------------
title1           content type 1          yes
title2           content type 2          no
title3           content type 3          yes

I want to be able to use a custom string instead of the content type name. My view should be like the following:

Title            Content type          Published
------------------------------------------------
title1           my content1             yes
title2           contents for all        no
title3           other content           yes

I don't know is it's possible to do this with Views. I don't want to change the name of content types, I only want change them in the view.

Is it possible?

Override the template file of you 'Content type' field for your particular view, and code in it.

switch($output) {
  case 'content type 1':
    print 'my content1';
    break;

  case 'content type 2':
    print 'contents for all';
    break;

  // ...
}


get list of product line item in rule php how can I get product id of line items in checkout process with rule,
I know $commerce_order are there in rule, but how can I get list of product id ?

This is a good way to get them

$line_items = $commerce_order->commerce_line_items['und'];
 foreach($line_items as $lid) {
 $line_item = commerce_line_item_load($lid['line_item_id']);
$pid[] = $line_item->data['context']['product_ids'][0];
//also you  can load products
//  $product =  commerce_product_load($pid);
 }


Create Latest Comments View Per Group OG 7.2 Hello it has been a while since i used OG Groups (and Panels) and im struggling a bit to create a view for the group home page showing the latest comments within the group. Its all to do with the Relationships and Contextual Filters. There seems to be so many relationships and filters available to me that its making me struggle a bit.

Could anyone advise me on how to make a view that will display the comments for that group? I think once i see the Relationships used there will be no holding me back from various other things.

Thanks

OG membership: OG membership from Node for the relationship and OG membership: OG membership from Node as the contextual filter not forgetting to sort the validation criteria


Views autocomplete with aggregation (and panels) I have panel that displays data from two custom content types, Funding and Partners. There are various attributes of Funding and Partners that I have exposed as filters.

There are two types of views I'm using to display data in the panel. The first type is simply a list of Funding instances. This is working just fine (I have the relationship setup between Funding and Partners, I'm using Content: title with the relationship, the autocomplete field points to this Content: title field, etc.).

The second type of view is giving me trouble. I'm using Aggregation to display the total number of Funding instances and the total amount of Funding, based on the exposed filters. This works just fine for most exposed filters, but it doesn't work for the Partner name. This is because I cannot include the Partner name in the list of fields and still get the aggregation behavior I want (including the Content: Type with the relationship gives me a list of funding, not the totals). Of course, when I remove the Partner name I no longer have to field to point the autocomplete exposed filter to.

So the way to address this is actually easy, so sorry for having posted it.

In case anyone else is having this issue...in the panel, instead of using the exposed filters for the view with aggregation, I used the exposed filters for the view that just provided a list of Funding instances.

Then, in the settings for the view with aggregation there is no need to use autocomplete (just use Contains) - because I'm not displaying this exposed filter anymore.


How can I change message set on form.inc? I am using taxonomy module in my site and have used the "Add vocabulary" form by hook_form_alter().

I want to change the error message for machine name (Machine name in use) to some other message. This message and validation is thrown from form.inc function. How can I change this message in my hook_form_alter() function?

Some code

function resources_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
    if(strstr(current_path(), 'admin/structure/resources'))
    {
        $form['#validate'][] = '_error_preservation_helper';

    }
}

function _error_preservation_helper($form, &$form_state) {
debug(form_get_errors());
    $errors = form_get_errors(); // works shows error array
    if(is_array($errors) && array_key_exists('machine_name', $errors))
    {
        // now change the error message
        form_set_error('machine_name', 'custom message', TRUE); // not works
    }
    debug(form_get_errors());   // same results

}

It's notoriously difficult to target/replace specific messages in the Drupal system. It's not impossible but it's a bit 'messy'.

I'd strongly recommend instead that you install the String Overrides module and use that to replace the specific message instead. String Overrides:

  Provides a quick and easy way to replace any text on the site.

It is available for any string in the system which is passed through the t() function, which all core error messages are.


Change plid of existing administration menu items I'm building an internal portal for an organisation and I want to change the standard administration menu, putting a number of the front-facing website options under a menu item called 'Website' and the rest under 'Drupal Config'.

So I'm simply trying to change the plid of 'admin/content', but it's not working. Could somebody guide me on where I'm going wrong please?

function eac_sponsorship_menu_alter(&$items) {

    $items['admin/content']['plid'] = 592; //592 is id of 'Website' menu item
    menu_link_save($items);

}

Also are there likely to be any repercussions from doing this?

Note that in the final solution the plid wont be hard coded as "592", but will use a DB look up to get the mlid of the 'Website' menu.

Also it is not a cache issue, when checking the DB the plid of admin/content remains to be '1'.

If you want your own top level admin menu group, you should probably create your own parent menu item and section there using hook_menu

e.g admin/website and put your menu items under that.

/**
 * Implements hook_menu
 */
function my_module_menu(){

  $items = array();

  // Provide own admin configuration menu section
  // using system_admin_menu_block_page for item groups
  // Top level section
  $items['admin/website'] = array(
    'title' => 'Website',
    'description' => 'Local website configuration.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child admin menu group
  $items['admin/website/config'] = array(
    'title' => 'Configuration',
    'description' => 'Configure website settings.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 50,
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child group menu item
  $items['admin/website/config/advanced'] = array(
    'title' => 'Advanced settings',
    'description' => 'Configure advanced website settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_website_settings_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/my_module.admin.inc',
  );

  return $items;

}

See system_menu for an example hook_menu using system_admin_menu_block_page


Encrypt entire site - request access How can I encrypt my entire site?

I also need to require password and username to access site. When visitors are accessing site, they will be redirected to a login page where they can also request membership. How to implement that?

There is no built-in way to do two-way encryption in Drupal, but there are two modules that will extend Drupal to support encryption:

Encrypt
AES

Encrypt:

Includes multiple encryption methods from simple to complex depending on libraries available on the server.
Focused on being a simple API that doesn't do much on its own.
Sub-module Field Encrypt let you use it to encrypt fields without coding (but beta only, no stable release of this one).
Uses CTools plugins for encryption methods and key providers.
Contains unit tests for all the features.
Stable Drupal 7 release, about 1400 installed sites.

AES:

Includes support for one encryption method (AES).
Built in functionality focused on two-way password encryption. Other uses requires coding by means of the API.
Requires use of the PHP extension mcrypt or the phpseclib (PHP Secure Communications Library) external library.
Has no built-in testing.
Stable Drupal 7 release, about 3000 installed sites.

You should be able to encrypt the entire site by using either of these modules and create a simple custom module that uses the hook system to encrypt content before it is stored in the datebase and decrypt as part of rendering content.

You may even do it without creating a custom module by means of Encrypt with sub-module Field Encrypt - if you find the beta-realese of the latter stable enough for your uses.

(PS: I can tell you how to restrict access as well, but that need to be a separate question).


How to use Rules to send an email to customers 1 month prior to license expiration date? I am using the Drupal Commerce module and I have a product type service for license to be sold on site. I have different licences (products) like 1 year license, 2 year license, 6 months license and many more.

I need to send an email to customers 1 month prior to their license expiration date. Like if customer purchased a license for 1 year, then the email should be sent 11 months after date of purchase. Similarly with other products like after 5 months if license is for 6 months.

How can I achieve this using the Rules module?

Answering my own question.

I have finally done this using hook_default_rules_configuration()
I have created a test rule with static values, then exported it and used the hook mentioned above to modify the values on run time.

This worked best for my requirements.


How to load an entity definition? I need to load an entity definition to add a constraint and test it, I found that this is possible with the following code:

$manager = \Drupal::entityDefinitionUpdateManager();
$entity_definition = $manager->getEntityType('node');
$entity_definition->addConstraint(‘name’);

But I wonder if this is the correct way or if exists another.

The only case where you want to work with entityDefinitionUpdateManager() in update and post update hooks, to update an entity type definition on existing installations to the one defined on the annotation.

To add a constraint to an entity type that's not yours use hook_entity_type_alter()


Exporting settings in a code with Features / Strongarm - how to detect right variables - config ones Many modules does not support Features, so I need Strongarm module to export config in the code. But in situation where i have many contrib modules, it seems tedious work. not all variables are named after module.

More important, how can I know which variables are used for settings, as I noticed some vars are not used for settings but may be user/module specific, and I need to aviod them.

I want to Strongarm only variables that have to do something with the config.

Is it done by researching modules one by one ? What are your experiences (It would be nice if I could filter variables that are used only in config :) )

Unfortunately, the Drupal variables table doesn't provide any distinction between variables used for configuration (e.g., whether anonymous pages should be cached) and variables used to store transient values (e.g., date cron was last run, which tabs are currently active in the UI), so there's no automatic way to do this.  (Fortunately, it looks like Drupal 8's configuration management system will handle this better.)

I typically export and update Features modules from the command line using Drush.  I've been using the following Unix shell script to list Features Components which haven't yet been exported to any feature — the script filters out Features Components I know I don't want in my Features modules:

drush fc % --not-exported \
    | grep -v '^ dependencies:' \
    | grep -v '^ user_permission:access devel information' \
    | grep -v '^ user_permission:execute php code' \
    | grep -v '^ user_permission:switch users' \
    | grep -v '^ uuid_node:' \
    | grep -v '^ variable:additional_settings__active_tab_' \
    | grep -v '^ variable:cron_key' \
    | grep -v '^ variable:cron_last' \
    | grep -v '^ variable:ctools_last_cron' \
    | grep -v '^ variable:date_api_version' \
    | grep -v '^ variable:dev_mem' \
    | grep -v '^ variable:dev_timer' \
    | grep -v '^ variable:devel_api_url' \
    | grep -v '^ variable:devel_error_handlers' \
    | grep -v '^ variable:devel_execution' \
    | grep -v '^ variable:devel_krumo_skin' \
    | grep -v '^ variable:devel_page_alter' \
    | grep -v '^ variable:devel_query_display' \
    | grep -v '^ variable:devel_query_sort' \
    | grep -v '^ variable:devel_raw_names' \
    | grep -v '^ variable:devel_rebuild_theme_registry' \
    | grep -v '^ variable:devel_redirect_page' \
    | grep -v '^ variable:devel_use_uncompressed_jquery' \
    | grep -v '^ variable:devel_xhprof_directory' \
    | grep -v '^ variable:devel_xhprof_enabled' \
    | grep -v '^ variable:devel_xhprof_url' \
    | grep -v '^ variable:drupal_css_cache_files' \
    | grep -v '^ variable:drupal_http_request_fails' \
    | grep -v '^ variable:drupal_js_cache_files' \
    | grep -v '^ variable:drupal_private_key' \
    | grep -v '^ variable:entityreference:base-tables' \
    | grep -v '^ variable:features_codecache' \
    | grep -v '^ variable:features_ignored_orphans' \
    | grep -v '^ variable:features_semaphore' \
    | grep -v '^ variable:install_profile' \
    | grep -v '^ variable:install_task' \
    | grep -v '^ variable:install_time' \
    | grep -v '^ variable:mimemail_key' \
    | grep -v '^ variable:prod_check_module_list_lastrun' \
    | grep -v '^ variable:simplenews_last_cron' \
    | grep -v '^ variable:simplenews_last_sent' \
    | grep -v '^ variable:simplenews_private_key' \
    | grep -v '^ variable:simplenews_source_cache' \
    | grep -v '^ variable:update_last_check' \
    | grep -v '^ variable:xmlsitemap_generated_last' \
    | grep -v '^ variable:xmlsitemap_rebuild_needed' \
    | grep -v '^ variable:xmlsitemap_regenerate_needed'


Drupal Commerce: How to make more than 50 types of a product variation? So I have an online printing shop, each of my products can have different variations which can adjust the price, such as "Print type", "Coating", "Round corners", "Size" & etc...

As far as I know for being able to make different variations of a product (let's say a business card), I have to add all the different type of variations as a product, then add it to my product display.

It works fine in this way but I have a lot of variations, Imagine if a customer wants a business card with no round corners with the rest as default options (1 product that I have to add), the next customer wants a rounded corner (second product) and the list goes on and in this situation I have to add more than 1000 product which is just a overkill.

I'd like to know if there's a better solution for product-variations and my issue.

Commerce Bulk Product Creation

Consider using the Commerce Bulk Product Creation module. Excerpt from its project page:

  ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

Attention: this module doesn't have an official release yet (only an RC6), though with over 1.600 reported installs, it seems it is pretty stable / trustworthy.

Commerce Backoffice

Another option to consider is using the Commerce Backoffice module, e.g. because of the auto creation of product display nodes. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

Commerce Backoffice Product (commerce_backoffice_product).
Commerce Backoffice Order (commerce_backoffice_order).
Commerce Backoffice Content (commerce_backoffice_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

Note: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).


How hook_form_alter() works in Drupal? How hook_form_alter() works in Drupal? It will work when the form is just loaded right ?  I need to modify the form variables before submission only  . Suppose i am modifying some form variables after rendering the form and the submitting it , where i can write the code for this ?

Take an example as I have a form  node_form() , and I am modifying the form variables in node_form_alter() and processing the submission in node_form_submit() function . Will node_form_alter work on pre submission too ? Or is there any workarounds ?

Yes, the code inside hook_form_alter() or hook_form_FORM_ID_alter() will be run when the $form array is being built, and before it is rendered.

All active modules that implement one of these two hooks will have their implementations called before the $form array is rendered. (They will be called in sequence according to their weights).

If you need to alter or manipulate the values being submitted by the form, you can use one of these two mentioned hooks to include in the $form array your custom #validate or #submit functions, where you can perform any kind of code processing you need.

A good source for finding examples of all these functionalities is the examples module, specifically around here.


pager_query() - How to fetch only 100 records with a pagination 10 items per page? $result = pager_query($query, 10, 0, NULL, $args);

Currently with above code , I am getting all results with 10 items per page. But I need to display only first 100 records , with 10 items per page. Is this possible with pager_query()  or any alternate solution using plain PHP and MySQL?

You can pass a $count_query argument to pager_query(), which you can use to control the overall count:

e.g.

$sql = 'SELECT * FROM my_table';
$count_sql = 'SELECT COUNT(id) FROM my_table LIMIT 100';

$result = pager_query($sql, 10, 0, $count_sql);


Contextual filter only working on one URL I've been going through posts such as View block not accepting contextual filter argument, Contextual filter on Views Block file not found, How do I get a block to use a URL to configure a contextual filter?, Contextual filters help, Contextual filter with a block view and more to find the solution or my issue with no luck.

In short my contextual filter only works on 1 of 5 pages I want it to work on (they other 4 pages doesn't return any results). The working page is label/artists

I've got a taxonomy vocabulary called site_sections and an artist content-type. I've got a View Block of artist teasers, that I want to filter contextually by a part of the url alias.

I've got a term reference on each artist node to the site_section terms which are

label
publicity
shop
management
wholesale

My view is a block showing artist teasers. The block is displayed on these URL aliases:

label/artists
publicity/artists
shop/artists
management/artists
wholesale/artists

My contextual filter:

Content: Site section (field_site_section)

WHEN THE FILTER VALUE IS NOT AVAILABLE

Provide default value: Raw value from URL
Path component: 1
Use path alias: Y

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED

Specify validation criteria: Taxonomy term (site section)
Filter value type: Term name converted to term ID
Transform dashes in URL to spaces in term name filter values: Y

OK, found my error.

On the artist block configuration I'd copy pasted urls except for the label, it said:

`label/artists shop/artists/ management/artists/ wholesale/artists/ publicity/artists/`

Removing the trailing slashes did the trick.


How to save node text and comment text to session or cookie while typing This site does a great job saving the text input even when a question or answer hasn't been posted.

Is there a similar feature available in Drupal?

There was by crell: module Autosave. Not ported to d7 though.
Here is a quote about it (from the module's project page):

...  automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
How often a form is autosaved as well as which content types to enable autosave for are admin configurable.


Allowed types for DataDefinition::create() I'm creating a new Field Type in Drupal 8. What types can I pass to DataDefinition::create()?

The types are defined as DataType plugins. You could also implement additional ones, but that's not necessary very often, since all the basic scalar data types exist already.


How to get the path to theme in Views for linking an Image When creating a view, I rewrote the output in "Rewrite Results". There I have an HTML with a link to an icon in the theme folder.

[field_output]

[field_text_output]

As you can see that I am hard-coding the path to my icons. This works if this View Page is accessed from home page. But when this View page is accessed from some 2nd or 3rd level page, the icons are not shown.

Is there any way I can get a relative path to my theme within Views?

Thanks.

I will encourage you to rethink your hardcoding approach and instead implement your icons as CSS background images, using views to apply the desired classes to your field elements. This approach will allow you to avoid the options I am about to suggest :)

Option 1: Copy one of the following files found in the views module theme folder into your theme's templates folder: views-view-field.tpl.php, views-view-fields.tpl.php and rename it according to your needs using the Views template files documentation - and in your case you may want to look at views-view-list.tpl.php. Then code your img tag into this field template logic, constructing your img src with PHP using the $base_url variable. Clear the cache.

Option 2: Install Views PHP and add a Global:PHP field and construct your img src with PHP using the $base_url variable.


With optimized js enabled, my javascript code not working I have a drop down list. On the change event of the drop down list I have written some javascript code. When I select an option from the drop down list a site opens in the new window.

So for this I wrote some javascript code on the change event of the drop down list.

But the problem is that when I enable the optimize js files then my drop down change event does not work and when I disable the optimize js files then the change event of the drop down works.

So what should I do for this to work in both condition?

UPDATED:

Drupal.behaviors.change = function (context) {

    $(".test").change(function(){
        var page = $(".test").val();
        window.open(''+page+'', '_blank');
    }) ;

};

The reason maybe is your custom script loads first before the Jquery script.

Try this:

(function($) {
  $(function() {
    //your script here
  });
})(jQuery);

or

Drupal.behaviors.somethingHere = function (context) {
  //your script here
}


View filtering all records with no argument, empty text with invalid argument I have a view with a block display that I need to filter by:

All records when no argument present e.g. /foo
All nodes with specified valid taxonomy term ID e.g. /foo/bar
Show empty text when taxonomy term ID is attached to no content e.g. /foo/baz

WHEN THE FILTER VALUE IS NOT AVAILABLE is set to Display all results for the specified field.
WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED is set to Specify validation criteria, Taxonomy Term.
Filter value type is set to term name converted to term ID.
Transform dashes in URL to spaces in term name filter values.
Action to take if filter value does not validate is set to Display contents of "No results found".

The view preview is working correctly, adding taxonomy_term_data_field_data_field_VOCAB.tid = 'xx' to the query but on the front-end it doesn't appear to be working at all.
I have Global: Null as the first entry under Contextual filters as the argument needed to filter is the second argument in the URL string.

All of the methods below will display:

Matching results on foo/bar (valid term name with matches)
Value of "No results found" on foo/norf (valid term name with no matches)
Value of "No results found" on foo/baz (invalid term name) (Page display) or 404 Page Not Found (Block display)**See note below.

The following methods will take different actions if a term is not present; e.g. foo/.

Method 1. Display NO results if term is not present

Contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available .. Provide default value
                                  Type .. Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

                 When the filter value
 IS available or a default is provided .. Specify validation criteria
                             Validator .. Taxonomy term
                          Vocabularies .. (select vocabularies)
                     Filter value type .. Term name converted to term ID
     Transform dashes in URL to spaces
            in term name filter values .. checked

   Action to take if filter value does
                          not validate .. Display contents of "No results found"

Method 2. Display ALL results if term is not present (using PHP filter module)

Note: For this method the core module PHP filter must be enabled.

Contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available .. Provide default value
                                  Type ..  Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

                 When the filter value
 IS available or a default is provided .. PHP code
                     PHP validate code .. (see below)

if ($argument) {
  $vocabulary = 'vocabulary_name'; // The machine name of the  vocabulary.
  $terms = taxonomy_get_term_by_name($argument, $vocabulary);
  if (!empty($terms)) {
    $term = array_shift($terms);
    $handler->argument = $term->tid;
    return TRUE;
  }
  else {
    return FALSE;
  }
}
else {
  $handler->argument = 'all';
  return TRUE;
}

   Action to take if filter value does
                          not validate .. Display contents of "No results found"

Method 3. Display ALL results if term is not present (using Views hook)

Contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available .. Provide default value
                                  Type ..  Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

                 When the filter value
 IS available or a default is provided .. Specify validation criteria
                             Validator .. Taxonomy term
                          Vocabularies .. [select]
                     Filter value type .. Term name converted to Term ID
   Action to take if filter value does
                          not validate .. Display contents of "No results found"

Add this function to a custom module and clear the caches:

function MODULENAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'view_name') { // You can optionally also check the display ID.
    if (!empty($args)) {
      $argument = $args[0];
      $vocabulary = 'vocabulary_name'; // The machine name of the  vocabulary.
      $terms = taxonomy_get_term_by_name($argument, $vocabulary);
      if (empty($terms)) {
        $args[0] = FALSE;
      }
    }
    else {
      $args[0] = 'all';
    }
  }
}

Method 4. Display ALL results if term is not present (no coding required!)

On your first block display, use the contextual filter in Method 1, then limit the block visibility*** to 'foo/*'. Create a new block display that outputs all results and limit the block visibility to 'foo'.

**There's an important caveat when using URL arguments with a block display: the URL must be a valid path. In other words, foo/bar must be an actual page or you will get a 404.

*** In the Pages fieldset on the block configuration form (Administration > Structure > Blocks), select "Only the listed pages", then enter the suggested values.


Drupal commenting system vs Disqus I like the multiple login possibility of Disqus. You can login with facebook or twitter or google etc.
 On the other hand, comments will exist on a 3rd party server and the package that includes the single login feature costs a lot (that mean that drupal site's users can comment without logging again at disqus system or another).

How I can simulate similar system on my site?
How can users sign in with facebook, twitter, google, openid at my site so that they comment?
Is there any other feature of disqus system apart from multiple login that can be accomplished with drupal modules?

[3. Does disqus makes site slower to load?
4. How can I move comments from Drupal to Disqus?
5. How can I move comments from Disqus to Drupal?]

Edit: I would like an answer possibly from someone that has used both systems as advantages and disadvantages appear in the long run, and it is not easy to decide just at a fast research. I have seen sites switching from one commenting system to another because they understood the disadvantages of their choice after some months.

Regarding question 1, there are several options to do that, for instance OpenID Selector.

Question 2: Yes. I don't know all of Discus' features so I cannot answer this for each and every one of them. However I do know that there are Drupal modules for comment notification, for instance Comment Notify.

Questions 3-5: those are quite specific, I think you'd better ask them in the issue queue of the Drupal Disqus module.


Embedded video thumb has been displayed on all overlay windows I have been created a block to display YouTube videos on my website ,When ever i tried to open admin windows that video thumbnail has been displaying on every overlay windows how can i disable that any suggestions ?

Screenshot :

You could try CSS z-index Property

  Definition and Usage

  The z-index property specifies the stack order of an element.

  An element with greater stack order is always in front of an element
  with a lower stack order.

  Note: z-index only works on positioned elements (position:absolute,
  position:relative, or position:fixed).

Try setting a higher value to the overlay or a lower value to the youtube player.


Refresh default migrations I done a migration of a website, but new content were created during I done that. So how can I refresh default migrations created by the drush command :

drush @alias  migrate-upgrade --legacy-db-url=mysql://user:pass@localhost/d6ce --legacy-root=http://d6-site.vmdev --configure-only

I know about the update option for drush mim "migration" but here, I need to recreate migration.
Perhaps I just need to re-run the original command ?

Thanks

EDIT:
the way seem to be:

- drush @alias mr "migration_name"(rollback migration)
 - drush @alias mrs "migration_name"(set to Idle)
 - drush @alias migrate-upgrade XXX (re-create migration)

EDIT2:
I get an error on a content type:

Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '591' for key 'node__vid': INSERT   [error]
INTO {node} (nid, vid, type, uuid, langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] => 494
    [:db_insert_placeholder_1] => 591
    [:db_insert_placeholder_2] => page_europe
    [:db_insert_placeholder_3] => 95cc248e-6c93-4cfa-ad29-b19db86425c5
    [:db_insert_placeholder_4] => fr
)
 in Drupal\Core\Database\Connection->handleQueryException() (line 683 of /var/www/drupal-8/core/lib/Drupal/Core/Database/Connection.php).
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '591' for key 'node__vid': INSERT INTO {node} (nid, vid, type, uuid, langcode) VALUES           [error]
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] => 494
    [:db_insert_placeholder_1] => 591
    [:db_insert_placeholder_2] => page_europe
    [:db_insert_placeholder_3] => 95cc248e-6c93-4cfa-ad29-b19db86425c5
    [:db_insert_placeholder_4] => fr
)
 (/var/www/drupal-8/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:783)
Processed 31 items (30 created, 0 updated, 1 failed, 0 ignored) - done with 'd6_node:page_europe'                                                                     [status]
d6_node:page_europe Migration - 1 failed.

With or without roolback...no issue on another content type.Related to taxonomy ? How can I fix that ?
I notify that if I just run: drush @alias ms I get this kind of infos:

upgrade_d6_file      Idle  1521   1497      21         2018-10-29 14:57:40

So new files are mentionned and would be able to be imported as is with --update option ,not ?

I needed something similar, I solved it by first making a rollback and then I launched the original command.

drush mr

You can find more information about the command on this link  https://drushcommands.com/drush-8x/migrate/migrate-rollback/


How to send a Group email based on date field using Rules? I'm using the Group module and I have a Group content type called Events with a date field. I am having trouble figuring out how use Rules to send an Email on the same day as the date field to all the members of the Group.

I've tried creating a rule but it's just wrong:

Event: runs on cron
Condition: group content, datefield equals, is node type Event
Action: get group members from group audience, loop group members, send email

Most of what keeps showing up in my searches to answer my question, are not for Group content.

Any help?

This is typically something you can get to work using the Rules module, together with Rules Scheduler (a sub-module of it), as explained in the steps below.

Step 1: Enable the Rules Scheduler

Enable the Rules Scheduler (a sub-module of Rules). And make sure your cron jobs are running (to ensure that scheduled rules actually start executing.

Step 2: Create a Rules "Component"

Create a Rules Component labeled something like Notify all members of a Group, which looks like so (in Rules export format):

{ "rules_notify_all_members_of_a_group" : {
    "LABEL" : "Notify all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "event_node" : { "label" : "Event node", "type" : "node" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail Id \u0022[member-of-group:user:mail]\u0022 is a member of the \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and group id \u0022[group:gid]\u0022, related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail as a friendly reminder related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date]).\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about this Rules Component:

The type of this Rules Component is an "Action Set" (no need for any conditions).
Action 1 is to build a list of all the members of the group. It uses "Fetch entity by property", with these additional specs:

Entity type value = Group Membership.
Property value = Group.
Value of the data selector = Group.
Limit result count = blank (we do not want to limit the nr of results).
Provided variables = "Group members" (variable label) and "group_members" (variable name).

Action 2 is to iterate (= loop) over each of the members of the group. It uses "Add a (Rules) loop", with these additional specs:

The list to loop over = group-members
Current list item = "Member of group" (variable label) and "member_of_group" (variable name).
Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with an appropriate message using various tokens which might be interesting.
Sub-action (ii) of this Action 2 is to actually send an eMail to the "member_of_group" being processed in the loop, using various tokens similar to those in Sub-action (i).

If you have the Rules UI enabled , as well as the Group module, you can simply import the above rule in your own site, no need to tweak anything in it. Though you may want to tune the Subject and Message content of the actual eMail (just remember the various tokens you may want to use), while you might also want to use some other From eMail ID. And after QA-testing it, you probably want to remove the Rules Action "Show a message on the site".

Step 3: Create a "Rule" using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):

{ "rules_schedule_group_notification" : {
    "LABEL" : "Schedule Group notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_event_date" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_notify_all_members_of_a_group",
          "task" : "[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_notify_all_members_of_a_group",
          "date" : [ "node:field-event-date" ],
          "identifier" : "[node:nid]",
          "param_group" : [ "node:group" ],
          "param_event_node" : [ "node" ]
        }
      }
    ]
  }
}

The above rule refers to the Rules Component from the previous step. And is based on these assumptions:

The content type of the event node is has machine name article (adapt prior to import to fit your case).
The field "Event date" has machine name field_event_date (adapt prior to import to fit your case).

The schedule_delete that is part of this rule is to ensure that previously "scheduled" notifications will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recently entered date).

Attention: whatever gets updated in such node, will each time trigger this rule. Even if the actual date itself is not updated. If that's not what you want, just add additional Rules Conditions so that the rules Actions are only performed if the date is updated.

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


How to disable form button on ajax callback? I have a button with ajax callback and I want to disable it on button click without page reload. Preferably inside ajax_function but it's not obligatory.

$form['my_button'] = [
  '#type' => 'button',
  '#ajax' => [
    'callback' => '::ajax_function',
    'wrapper' => 'my-button-wrapper',
  ],
  '#attributes' => array(
    'class' => array('glyphicon', 'glyphicon-shopping-cart'),
  ),
  '#submit' => ['::ajaxButtonSubmit'],
];

In your ajax callback function write the code to disable button. like:

public function ajax_function(array &$form, FormStateInterface $form_state) {
    $form['my_button']['#attributes']['disabled'] = true;
    return $form['my_button'];
}

Hope it helps!


How to add active class to title which is loaded via views in block I have created content type XXX, via views I collected all titles of XXX content. That all titles works as links, I want to add active class to title which was clicked in block. It should works as menu item.

If you are generating a menu structure, I would suggest the following:

Your view should use the HTML List format.  In the settings use the unordered list type.  You probably should add a list class setting like nav (or your theme's default class for nav elements).

The Format Show type should be Fields.  In the settings, uncheck the "Provide default field wrapper..." option.

The results should be a straight forward ul list with li wrapped anchors.  E.g.

     Node Title

// other titles below

Standard menu CSS should work on this,  e.g .nav > li > a to select anchors and the like.

If you still need a css class on the label, you can add a hidden path field above the title.  Remove the link to content option.  Then rewrite the title field with something like:

{{ title }}

To get an active class, you have several options.

If you are using a bootstrap based theme, you can just add the appropriate bootstrap classes to this since it's a simple ul structure.  See the bootstratp docs for more details.

It is easy to add a bit of jQuery script to do this.  See this for some sample code.

Or you can do it with the template_preprocess_views_view_field() hook.  Here's some sample code for that.  You will probably have to dump the output value to see how it is layed out.  Note that you will have to play some games with getting the current path into the same format, especially if you are using path aliases.  Some sample code.


db_select query for given sql query with equi join I'm trying to do a equi join but it isn't working.
I have 2 tables:
Table 1 - taxonomy_term_data with fields "tid,vid,name,description,format,weight etc"

Table -2 -taxonomy_term_hierarchy with fields "tid and parent"

I have sql query with me it is working fine. This is the query "select t1. *,t2.vid,t2.name from taxonomy_term_hierarchy t1, taxonomy_term_data t2 where t1.tid = t2.tid AND vid=2 limit 5;"

I just want to get tid,name,vid from taxonomy_term_data table and parent from taxonomy_hierarchy table in db_select query format

You can built any type of select query using db_select, you can see in detail on following url
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7.x


Send email on comment to users depending on Taxonomy term selection in node I need to send notification on new comment to users. But not based on node ownership, but based on what Taxonomy term is selected in node. It might be good task to accomplish with Rules module.

So i knwo to set event - after saving a new content
and Action - send e-mail

but for condition, i should somehow get the Commented node taxonomy term value.
But cannot find selector: Taxonomy term to do data comparison, or way to get taxonmy data for given commented node. Is this possible ?

Can the commented node object be checked - if custom PHP is selected for condition - so i can check selected taxonomy term value ?

Thanks!

You should Load the Entity (node) from the comment's data.

Then pass that node to a component rule, which actually checks the taxonomy of the node and sends the appropriate email.

Here's a step by step.

First create a component:
1) Go to Rules -> Components -> Add new component
2) Select Rule
3) Name and Tag the component
4) In variables select 'Entity Node' and give it a label and a machine name. Example 'comment_node'
5) Add your conditions. Probably good idea to check node type and of course the taxonomy term you were looking for.
6) Add an Action. Here you should send an email.

Now go to your rule:
1) In actions add 'Fetch entity by Id'. Select 'node'. Use data selector and put 'comment:node:nid' in the id.
2) Then add a Loop
3) In the loop add an action. That action should be your component you created previously.
4) Pass the fetched entity into the component and you should be done


Unable to add custom field to view I created a new content type called 'Newsletters' and created an image, text and link field.

I then created a view-block and when I try to insert my custom fields they do not show up in the fields list.  I checked my permissions of the modules and my folders so that should not be the problem and there are no errors in my logs.

It's a bit confusing.
Drupal 7.41
PHP 5.4.45
views 7.x-3.13

Any insight to why I can't insert my custom fields would be helpful.

So it appears that the machine names for my custom content types can not be longer than 24 characters.  As soon I shortened the names they inserted into the view as normal.

It's odd that I have never had that kind of problem before.  But so it is...

Thank you for your efforts!!  It is REALLY appreciated!


Display regions in user-profile.tpl.php I created a region into mytheme.info

regions[list_user_poke] = List User Poke

I put a block in it. Then I want to print this region user-profile.tpl.php.
I wrote this chode :

<div class="list-user">
   <?php print render($page['list_user_poke']); ?>
  </div>

But it does not appear.

Thanks for your help !

For anyone wondering about this, here's how to do it (code goes in your theme's template.php file):

function YOUR_THEME_preprocess_user_profile(&$variables) {
  $variables['YOUR_NODE_REGION'] = block_get_blocks_by_region('YOUR_NODE_REGION');
}

And then in your user-profile.tpl.php template:

<?php if ($YOUR_NODE_REGION): ?>
  <div class="custom-region">
    <?php print render($YOUR_NODE_REGION); ?>
  </div>
<?php endif; ?>


How to add a custom field to apache solr? How do you create your own solr field using Drupal 8's search api?

1) Copy /modules/contrib/search_api/src/Plugin/search_api/processor/AddURL.php into your own custom module at /src/Plugin/search_api/processor

2) Rename and rework (see below)

3) Add your extra field to the index at /admin/config/search/search-api/index/myindex/fields

4) Enable the processor on your search_api index

5) Reindex content and verify in solr that your new custom field is indexed.

http://127.0.0.1:8983/solr/#/mysolrcore/schema-browser?field=sm_mymodule_content_type, click on "Load Term Info" to see data loaded in.

Here's an example:

namespace Drupal\mymodule\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Adds a custom type filter to the indexed data.
 *
 * @SearchApiProcessor(
 *   id = "mycustom_field",
 *   label = @Translation("Custom Field"),
 *   description = @Translation("Add a custom field to search index"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class CustomField extends ProcessorPluginBase {

  /**
   * machine name of the processor.
   * @var string
   */
  protected $processor_id = 'mycustom_field';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = array();

    if (!$datasource) {
      $definition = array(
        'label' => $this->t('Custom Field'),
        'description' => $this->t('custom field'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      );
      $properties[$this->processor_id] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();

    $custom_field = '';

    // Use $entity to get custom field.

    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($item->getFields(), NULL, $this->processor_id);
    foreach ($fields as $field) {
      $field->addValue($custom_field);
    }

  }
}


What path to images to use with CKEditor to insert images in content? When putting images in content items, I have to put the full URL, otherwise images don't show up.

It works for this full path:

http://localhost/IT/sites/default/files/mypictures/apache_pb.png

But doesn't work for this path:

sites/default/files/mypictures/apache_pb.png

I know I must be missing something? A token? Variable to path?

You are missing the forward slash: /sites/default/files/mypictures/apache_pb.png

Incidentally, IMCE will make this easier for you.


How to prevent child element to move when parent dropdown? I have a div with height:20px with hover. When you put the cursor on it, a menu bar appears, this menu bar have height:50px.

After that i have a second div which is juste a yellow pannel with margin-top: 50px (so it's 50px from the parent who is the first div (that has : height : 20px)).

Now when the hover effect happend, the second div (the yellow pannel) moves down with the droping down effect.

How to make the second div do not have a margin top with the direct first div (his parent) ?

Thank you

In css you need to give your menu bar div an absolute position.

For Example: .menubar { position: absolute; } so that it overlays everything, so it won't affect anything else.

Then adjusted if needed

Example: .menubar { position: absolute; top: 0px; left: 20px; }

Also you will need to increase the yellow div from 50px to 70px

.yellow { margin-top: 70px; }


Programmatically create media file I'm trying to programmatically create a media file. Here's what I got so far:

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');

$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);

$media = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
]);

$media->setName('Hello')
  ->setPublished(TRUE)
  ->save();

Unfortunately this returns me the following error and the media file doesn't get saved:

  Error: Call to a member function getSource() on null in Drupal\media\Entity\Media->getSource() (line 138 of core/modules/media/src/Entity/Media.php).

What am I doing wrong? How can I fix this error?

uid shouldn't be 0, just change 'uid' => '0' by 'uid'=> \Drupal::currentUser()->id():

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');
$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);
$media = Media::create([
  'bundle'           => 'file',
  'uid'              => \Drupal::currentUser()->id(),
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
]);
$media->setName('Hello')->setPublished(TRUE)->save();


How to override "active configuration" when the theme is installing? I have a theme that imports configuration when is installed. The problem is when the configuration is already there and is active.

  Unable to install MYTHEME, field.field.user.user.user_picture,
  field.storage.node.body, field.storage.node.field_image,
  field.storage.user.user_picture, node.type.article,
  views.view.frontpage already exist in active configuration.

I know these errors are because the configuration is already on the site.

How can I override the configuration with a new configuration that is carried from my theme?

You cannot. You can provide only configuration for your module or create new configuration entities. You can "override" the default configuration only by profile, not module or theme.

But you can use hook_install to programmatically override whatever you want.

When it comes to themes, the only configuration that you should provide is block instances and your theme's settings. Of course if you have some advanced blocks you can also provide block types and field storage and instances for them.


Incomplete Object error when updating site (after Drupal timeout) I (foolishly) tried to enable an installed module whilst on my shared hosting. The site times out, which isn't all together unsurprising. However now I get this error message whenever I try and make any updates to the site (enable any modules, clear cache, run cron etc.)

Any thoughts as to the cause. Here is the error in full.

  Fatal error: views_plugin_display::destroy(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "metatag_views_plugin_display_extender_metatags" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in /home/xxxxx/public_html/sites/all/modules/views/plugins/views_plugin_display.inc on line 272

If it makes any difference it was the Metatag module I was trying to enable.

I had this error when running update after disabling Metatag and Metatag: Views. It went away when I re-enabled those two modules.

That also seems to have fixed some other issues I was having with the modules form; it would white screen on me after disabling (certain?) modules, although I could return to the Admin interface.


Bypass comment validation for SOME anonymous users, based on the provided email address? In the case of a low traffic blog (for instance), that only accepts anonymous comments (no user registration) and manually validates them before publishing them, would it be possible to have a sort of internal white list for trusted email addresses (in the comment "email" field)?

The idea would be that comments using one of those addresses would be published immediately, without requiring validation.

(Obviously the email addresses of the commenters are not visible to the visitors.)

Is there a module for that?

Make a rule with event after saving a new comment. Then make a view with the list of emails which should be bypassed. Compare this with the current email of the user, if there is a match publish the comment on the node.
The comparing can be done with views + vbo and the rules action: Load a list of entity objects from a VBO View.combined with a loop statement.


Print just field data from a view into a block? I'm trying to get a variable from a view to display on a block. For example "We have 200 blog posts" (200 being the variable).
Right now I'm using the views_embed_view method. The problem is the view includes a bunch of mark up I don't need/want (the container, theme, etc)

Is it possible to just call the field I want? I know I could create a whole custom theme for the view without markup but I'm hoping there is an easier way.

If what you're trying to get is the number of results returned from the view then your best bet might be to call views_get_view_result():

$result = views_get_view_result($name, $display_id);
$num_blogposts = count($result);

However, if that's what you're trying to achieve then it might be better from a performance point of view to bypass views entirely and get the count with an EntityFieldQuery.

-- EDIT --

Option 2:

You could override the various templates that make up the view, removing any unnecessary markup from each.

To do this, Click on "Theme: Information" in the "Advanced" section of the view edit page (bottom right) and you'll see a list of templates used.  Click each one in turn and create a new file in your theme folder and copy in the contents before removing any unnecessary markup.

What you name the file is important, back on the list of templates, note that each one has a large number of filename suggestions, ranging from very generic to very specific.  Choose the name with the the most appropriate degree of specificity and name your file that. note that for example calling your Display Output template file "views-view.tpl.php" will mean that your override will have effect on every single view across your site, so a more specific filename should lock it down to a specific view/display/etc.

Once you've done this, you'll need to flush the theme registry cache before you'll see the change.  The easiest way to do that is by clicking "Rescan template files" at the bottom of the theme information dialogue.

Finally note that these updates won't change what you see in the views preview unless you also make these changes for the admin theme.

note that if you are also rendering the view normally (in addition to the views_embed_view) where you want to see the original markup then you should probably use a new display of the view for this and make sure your template names only target the correct display.


How to get the Date, when particular field of a node is equal to some value? I have Content type called "Items", in that i have select list field for status referencing to Taxonomy terms(delivered,hold,dispatched etc.) .
 I want to store the date in some custom table when the item is "dispatched" and use that date in some other code.
 Which is function in which i can write logic to store date in table?  or any other way i can get dispatched date of the item?

You have to use one of the events described in Entity CRUD, editing, and view hooks.

One example from the documentation:

function hook_ENTITY_TYPE_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Update the entity's entry in a fictional table of this type of entity.
  db_update('example_entity')
    ->fields([
      'updated' => REQUEST_TIME,
    ])
    ->condition('id', $entity->id())
    ->execute();
}

You can get the original field values from $entity->original->status and check if the status has changed.


Access one Field from another field via field.tpl.php In Drupal 7, I have two fields field_cta_button and field_cta_text.

I am using field--field-cta-button.tpl.php to modify the outputs of the field.

I need the field_cta_button to change depending on the values of field_cta_text.

How can I access field_cta_text from field--field-cta-button.tpl.php?

If possible, I would like to do it without installing any extra modules.

Steps I have tired:

1) Node Load

I have used the following code from this page:

 <?php
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_cta_text');
$output = field_view_value('node', $node, 'field_ctac_text', $field[$delta]);
?>

However, it just outputs this error message:
Notice: Undefined variable: nid in include() (line 60 of /[SITE NAME]/sites/all/themes/legendary/[MY THEME]/field--field-call-to-action.tpl.php).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7562 of /[SITE NAME]/includes/common.inc).

2) Entity Field Query
I thought I might be able to use EntityFieldQuery(), but I'm not sure how to get it to load the current node.

You can access to the entity (node) to which the field is attached using $element['#object'] variable from the field template (or preprocess function).

For example, add this code in field--field-cta-button.tpl.php:

<?php
$field_cta_text = $element['#object']->field_cta_text;
echo $field_cta_text[LANGUAGE_NONE][0]['value'];
?>

If you installed devel module you can use dpm($element['#object']) function to inspect the entity variable.


How to alter storageSettingsForm in a custom Field Type definition, set default cardinality and not allow change Trying to set Allowed number of values always to be 1 and not allowing multiple values for a custom Drupal 8 field.
How to do that?
Do I need a form_ID_alter or a storageSettingsForm/defaultStorageSettings implementation?

I see this field is not included in the storageSettingsForm $form or parent::defaultStorageSettings()

Not sure if the best way is to set it as configuration or alter the form.
Is there an annotation for this or something?
Any example module that does this?

Thanks

Problem solved in 8.4.0 :)

Full list of changes


Ability to separate between levels in vocabulary hierarchy In the frontend visualisation of vocabularies, is One in Drupal able to specify from which level in the vocabulary hierarchy one should display terms from?

If yes, how do you do this?

Thanks,

Espen

Yes, you could use a module like taxonomy_menu to show a list of taxonomy terms.

Alternatively, you could use a code solution like taxonomy_get_tree that allows selecting terms by parent tid and depth.


How to open Bootstrap Photo Gallery on page load? I am using Bootstrap Photo Gallery, and would like to open the slideshow when the page loads.

Add your gallery into model window then used #modelid in then then gallery is automatically load when your page is loaded.

<script type="text/javascript">
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>


Load node based on a field name I have a content type that has a unique field.  How can I load a specific node based on this?  node_load() only takes the nid.  I am using Drupal 7.

There is indeed an API function: EntityFieldQuery, which has lots of example use cases scattered around this site.


Stuck in site maintanance mode I've been trying to update my drupal installation with the security patch from 7.20 to 7.26
using a patch file. Problem is I cannot get out of maintenance mode. I've tried everything indicated in other posts: http://example.com/index.php?q=user, http://example.com/user/login. Also tried to go the DB route, but that does not work either since the variable do not seem to contain anything with the "site_offline" name.
This is very frustrating. I've also backtracked on the changes by reinstalling the DB and site from backup, but unfortunately I had already put the site in maintenance mode when I took the backups. Grrr.
Any help greately appreciated.

The name entry in variable table is supposed to be maintenance_mode following updates in D7 after which site_offline and site_offline_message were replaced with maintenance_mode and maintenance_mode_message. Refer the inline comments in  update_fix_d7_requirements in update.inc

  // Rename 'site_offline_message' variable to 'maintenance_mode_message'
  // and 'site_offline' variable to 'maintenance_mode'.
  // Old variable is removed in update for system.module, see
  // system_update_7072().

Assuming you have access to the database or drush try updating the variable which is likely set as 1 to 0.

drush vset maintenance_mode 0

or

UPDATE variable SET value = 's:1:"0";' WHERE name= 'maintenance_mode';

You might also want to ensure that this value is not set as 1 with a $conf variable in your site's settings.php.
Many users with similar issue also suggest even clearing the cache table entries named variables for this to work after changing the variable value. If things go well this should bring your site back online.


How do I migrate user passwords? I have refactored an old Drupal 6 site to Drupal 8 and my only problem is, i migrated the users but the password is incorrect. i know that the password in Drupal 6 is a MD5 hash, but i cannot find a solution to convert this password, that Drupal 8 can read it.

Is there any solution for the password migration yet? can i give the MD5 hash a prefix inside of the database to make it readable?

Security wise it would make sense to import them in Drupal and then use the Mass Password Reset module to reset all passwords.


Drupal commerce price field settings? I've set GBP as my default and only enabled currency.

I have an exposed filter on my view so users can enter a maximum price. Say the user enters 300 the filter works and displays only items that go up to £300. The same for it the user entered 300.00 - it works.

However, when the user enters 300,000, i think Drupal is thinking of the comma as a decimal, so it thinks 300,000 and 300,00 means 300 and so my view shows results over 300 and up to 300 thousand.

Can I fix this, if so how?
Thanks for reading

'300,000' isn't a number, it's a string. If you run

print (int) '300,000';

You'll get "300" as the response. '300.00' is a number, which is why it's treated as one.

So your issue isn't with Drupal Commerce, rather PHP and your users' input.

You'll need to implement some validation to correct your users' input before Commerce uses it. You can either do this by adding an extra validation function to the form using hook_form_alter(), or with some simple Javascript attached to the input box(es).


How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php? Because my site requires user pictures to be approved, the default Drupal user picture is not suitable.

Instead, I want to show a picture from a field in each user's profile as the user's profile picture.

The field is "field_profile_picture".

The image style is "profile_picture".

Based on this tutorial, I put the following code in user-picture.tpl.php in my theme's templates folder:

if (!empty($user->field_profile_picture['und'][0]['filename'])) {
  echo theme('image_style', array('style_name' => 'profile_pic', 'path' => file_build_uri($user->field_profile_picture['und'][0]['filename'])));
}

This doesn't result in any PHP errors but no picture is displayed.  It appears that field_acc_profile_picture is evaluating as empty because even if I put a print "Hello world"; inside the {} it doesn't appear.  However, I am sure that the field has a value because I can see the picture displayed in views.

I don't think $user->field_profile_picture['und'][0]['filename'] would be set by default, you normally only get the fid column (this does vary depending on context, but you should always get the fid column either way).

This sort of code always works for me:

if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
}

If you're worried about the extra overhead involved with potentially loading the file twice, don't be, Drupal caches the object the first time round.

It the above doesn't work it's likely that the $user object is not fully loaded and so the fields haven't been attached. If that's the case, load the user like this:

$account = user_load($user->uid);

And then use the $account object to test for the field value.


Token access from module Hi I'm trying to replace a Webform email with a token which works from the tpl file like this:

$company_email = token_replace('[node:field-charter-company:field-company-email]', array('node' => $node));
echo $company_email;

This works fine but when I try to do it from a module it just outputs "[node:field-charter-company:field-company-email]" instead of the contents of the token.

function webform_node_token_form_alter(&$form, $form_state, $form_id, $node) {

        if ($form_id == 'webform_client_form_126') {
            $company_email = token_replace('[node:field-charter-company:field-company-email]', array('node' => $node));
            $form['submitted']['company_email']['#value'] = $company_email;
  }
}

I know I'm doing something wrong but kind of lost. Can anyone give me a pointer?

Extra arguments passed to the initial form function will not be passed to the alter - so the 4th parameter of $node in your form alter function isn't available. If you check your logs you'll probably find a related notice.

For any node form (including webform), you should be able to get the node object directly from the form:

$node = $form['#node'];


How to send Private Message using privatemsg_services module? I am using privatemsg services module to create REST API of privatemsg using Services Module in Drupal 7.

I need to know how to send message and how to reply to a message ? Please tell me URL where i should send POST request and the Body of request ?

Here you go

To send new  message

Endpoint: http://example.com/services/privatemsg

Content to Send (JSON Format) :

{
   "recipients": "xxx",
   "subject":"xxx",
   "body":"xxxx"
}

To reply a message for particular chat thread

Endpoint: http://example.com/services/privatemsg

{
"thread_id": "xxx",
"subject": "xxx",
"recipients":"xxx",
"body":"xxx"
}


Organic Groups (7.23) and D7 | drush or cmdline integration? Just wondering how to manage OG in D7 from command line oder drush. OG seems frequently used so I'm surprised not to see any method to manage OG from shell, e.g. like create, modify Ogroups... As far as I know there were some former OG-DRUSH integrations in D6 but not in D7. Someone pointed out that the 'feature' module might be a solution (as part of the installation?). Anybody there who's willing to share his knowledge or give some information?

I started, but never had time to finish Drush commands for og-6.x-1.x.  Please see https://drupal.org/node/1090438 for the preliminary implementation.  I don't know why no one else has picked this up; I agree it would be useful.

For og-7.x-2.x, I do some programmatic operations in my sandbox project https://drupal.org/sandbox/greg1anderson/2049677.  These are not broken out into direct og operations, but it might serve as a starting point for someone who wanted to pick up the task of adding Drush commands to organic groups.

Finally, for anyone who wants to quickly make a Drush command from a template, see https://drupal.org/project/drushify.


404 blog url's delivering 403 status I have a blog set up on my site, when I visit a page it delivers a 200 as it should, however when I visit a page that should not be there, it delivers a 403.

Example:

domain.com/blog/good-url/ = 200

domain.com/blog/bad-url/ = 403

The second example should be delivering a 404, any ideas where this could be coming from?

After looking at the source code of the blog module, it appears that the path /blog/<somestring> is sort of reserved for the blog module itself.

Problem:

The pattern based aliases created when creating a new blog node seem to take precedence over those internal paths so if your URL alias pattern is blog/[node:title], you are shown the expected blog node as long as it exists.

Once the blog node is deleted and the alias is deleted with it, /blog/<somestring> means "do whatever path <somestring> does in the blog module" which results in a 403 Forbidden error rather than the expected 404 Not Found error.

Solution:

The only solution I found is to use a different URL alias pattern such as blogs/[node:title] which avoids the problem.

Tip:

Use the Redirect module to let the Pathauto module create redirects when changing URL aliases. It also helps to keep track of those redirects so you can see which redirect URLs still receive traffic and which could be deleted.


Adding an information icon to a form element I currently have a number of form elements that I have added an image icon to, which users can click on or hover over for more information... which looks like this:

(The blue image icon is the one users hover over for more information)

When defining the component via render arrays like so:

$component[$this->componentName] = array(
  '#type' => 'textfield',
  '#title' => t('Project Name'),
  '#description' => t('Enter the name of the project'),
  '#description_display' => 'before',
  '#required' => 'True',
);

Is there away to get the image icon to sit along side the element (either the title or the description or the textfield), for example like this:

I am aware that there is the potential to use something like the #attributes tag to add tooltips too (as outlined below), but wondered whether there is scope to add the image icon as I am attempting?

'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  '#attributes' => array(
    'title' => t("Item's name, no longer than 45 characters."),
  )
),

You can use '#prefix' => 'Some title ' instead of '#title' => t('Name')

$component[$this->componentName] =  array(
                  '#prefix' => t('Some title*') .' ',
                  '#type' => 'textfield',
                  '#size' => 30,
                  '#maxlength' => 45,
                  '#default_value' => $item->Name,
                  '#attributes' => array(

                  );

You can add any markup to '#prefix' element of this array.

Or you can add markup even directly to title '#title' => t('Some title*') .'', but i think there can be some issues with asterisk when a field is required.


How can I edit a custom field with Rule and VBO of a NOT published node? I'm currently stuck in the creation of a custom rule.
I've created a content type "Avviso" with a publishing date field (start & end) and a custom field_stato with this values:

Not active
Active
Terminated
Archived

Now I would like to change the value of field_stato and publish all nodes with date_start < now < date_end. For that I've created a view with a VBO field, a Rule (triggered by the cron) and a component (of type rule) that do the job.

The problem is that the rule can see only node already published and -of course- cannot switch the node itself to "Published" state. With already published nodes the rule works fine.

Is there any restriction or permission with rules and unpublish content=?

(see images)

Cron runs as an anonymous user. Ensure that the view permissions allow an anonymous user to access. Set the access to role:

Then, set the role to anonymous:

That should allow you to bypass the regular permissions that would normally not allow you to see it.

Also, ensure that your rule includes a rule to save the entity. I'm not 100% sure that it will save the entities you reference automatically, but it is more clear.

Also also, you may need to check the permissions on your rules to ensure that they can be executed by anonymous as well:


Create a node's author by passing an argument...? I have a view in which I can see a list of all my users.

I would like to be able to click on one of the names in this list and create a node and have the user that I clicked on be the author of this new node.

Is it possible to do this by passing an argument in the URL, or perhaps there is an easier way to do this that I had not thought of.

Thanks.

Use views rewrite on username field to create a "create node" link and prepopulate module using tokens from the views. In this case the username token for the author field.


How to declare a custom theming function for block content? My goal is to render an array of values (body, date) using my own theming function.  I've read Using the theme layer, and checked out the example modules, and I can't see the reason why this isn't outputting the test string.

I've implemented registered my theme hook:

function mymod_theme() {
    $items = array(
        'mymod_items' => array(
            'variables' => array(
                'items'=>NULL
            ),
        ),
    );
    return $items;
}

I've implemented a theme function:

function theme_mymod_items($variables) {
    return 'I am themed output';
}

And I call this from my hook_block_view:

function mymod_block_view($delta = '') {
    switch($delta) {
        case 'mymod':
            $block['subject'] = t('My Module');
            $items = array(
                array('body'=>'body1','time'=>'time1'),
                array('body'=>'body2','time'=>'time2'),
                array('body'=>'body3','time'=>'time3'),
            );
            $block['content'] = theme('mymod_items',$items);
        break;
    }
    return $block;
}

This results in the block not displaying, and the following message turning up in the log:

  Theme key "mymod_items" not found.

Can someone please tell me what obviously essential step I've missed, or if I'm going in entirely the wrong direction?

It's an obvious answer, so sorry if you've tried it, but have you cleared your cache, specifically the theme registry?