Numeric field type in Form API I am trying to add a "number" field type to a form using FAPI:

$form['phone_number']['areacode'] = array(
  '#type' => 'textfield',
  '#title' => '---',
  '#width' => '30%',
  '#align' => 'center',
  '#required' => true,
  '#maxlength' => 3
);

I change the TYPE to "number" and the field doesn't get generated at all. The number module is enabled. I have implemented the following theme functions:

MYTHEME_form_element
MYTHEME_textfield
MYTHEME_container

What could be behind this field not showing up when I use #type = number or #type = number_integer, etc?

This might have something to do with it:

Creating Number fields (integer and decimal) manually in code for custom forms

However I actually want the type to render as "number" in HTML so smart phones show a numeric dialer

Any ideas?

$form['my_element'] = array(
    '#type' => 'textfield',
    '#attributes' => array(
        ' type' => 'number', // insert space before attribute name :)
    ),
    '#title' => 'My number',
    '#required' => true,
    '#maxlength' => 3
);


Strip html tags in preprocess hook We have a mytheme.theme file that has a mytheme_preprocess_node(&$variables) function. Within this preprocess hook, we would like to remove all HTML tags within a formatted (long) field. The goal is to do without using striptags within the node--page.html.twig template.

How can we do this securely without using striptags in a twig template?

Here is what we tried, but cannot find how to do it using mytheme_preprocess_node hook.

mytheme.theme

function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];
  $field_value = $node->get('body')->first()->getValue()['value'];
  ksm($field_value);
  // cannot find way to remove `html` tags

  $variables['field_value'] = $field_value;
}

node--page.html.twig

{{ field_value }}

output of ksm($field_value)

"& lt;p & gt;When looking at & lt;a href=&quot;https://www.example.com/some-path/&quot;& gt;article trends& lt;/a& gt; over time, attacks are cyclical in nature. Attackers develop new attack types and vectors, which are used to launch a new wave of attacks. As defenders become more proficient in stopping these new attacks, the attackers develop new types of attacks and the cycle repeats itself.&lt;/p& gt;

In order to properly display the output, I had to a space between & and lt characters above because StackExchange will convert those to proper tags. Within the ksm statement there is no space.

Additional item we tried within a twig template, but not sure if it is secure.

{% set body_processed = {
  '#type' : 'processed_text',
  '#text' : content.body.0,
  '#format' : content.body.format
} %}

Then better apply strip_tags() on the processed text $node->body->processed. You might also want to apply Html::decodeEntities(). Still take care you configure the text format restrictively, because outputting the text in a non standard way can be a security risk increasing with features you allow. And you don't get security updates for custom code.


Add Additional (Term Reference) Field to repeating Date & Time Field for Locations So I have a question that I am not quite sure how to handle in Drupal. (I come from a Wordpress background).

So I have an Event Content Type.
In this event CT I have a repeating Date/time field and I need each date/time field to be connected to its own Location. (All locations are stored in a Taxonomy called "Venues")

For Example, I could have 3 events on June 6th. Each at separate times but all three at different locations. So rather than create 3 Event nodes. I just want to set the three times and dates in one node.

Any idea's how to go about this? I was thinking I could do some type of field attach but I am not quite sure if that would be the way to go about it or to even start.

If i understand your question correctly, you could fix this quite easily by creating a field collection

The field collection would contain the repeating date field and the term reference field.

When you add the field collection to your event content type, you can select to allow an unlimited amount of values.

I hop this can get you started?

If you should have any problem, just let me know.
I will add some screenshots then. Im posting from mobile phone now...

Good luck!


Insert into table from Drupal 7 I am very new to Drupal.

I have a table called test with two fields: (int) id and (varchar) text
When a new user signs up I want to store data on the table test

I'd like to know how can I do that. I really don't know how to start researching about this.

I think the most approximately that I have found is Overriding user login. I presume that it does what I want but in the pre-process functions I have to insert into the database. Question here how do I insert into the database from Drupal?

Could anyone clear my thoughts or point me to any good reference.

Thanks.

You don't need to actually override the login process to do this; The user module provides a hook (hook_user_insert()) which gets invoked any time a new user is created.

As far as inserting into the database goes, the best place to look first is the Database abstraction layer documentation which goes into detail about the various database methods available.

In this specific case it's the db_insert() function you're looking for. Your code might look something like this:

function MYMODULE_user_insert(&$edit, $account, $category) {
  db_insert('custom_table_name')
    ->fields(array(
      'id' => $account->uid,
      'text' => 'some text'
    ))
    ->execute();
}

This code would go inside a custom module; if you're not familiar with creating one of those check out the Module developer's guide which will tell you everything you need to know.


Pathauto and taxonomy I use the default taxonomy view (with default path: /taxonomy/term/%) to display videos that have been categorized at the time of their upload. The viewer has access to an exposed filter that allows him to select like 10, 30 or 40 video thumbnails per page (default is 10.)

The Pathauto taxonomy pattern for all video paths is:
[term:vocabulary]/[term:name]
Token is enabled.

The url of the landing page is correctly displayed www.example.com/videos/sports when the vocabulary "videos" and the term "sports" are selected through a menu.

But if, on that same page, I select to view 30 video thumbnails per page instead of 10, the url changes to:

www.example.com/taxonomy/term/1989/0?items_per_page=30

This appears normal since the the view path is /taxonomy/term. The content displayed is correct, but the page theming is totally out of wack.

How do I keep the url at www.example.com/videos/sports/0?items_per_page=30 ?

Shouldn't Pathauto handle this?

Again, I will give my own answer here:

After reading about tokens, pathauto and views, it appears that exposed filters DO NOT work with path (dixit Merlinofchaos in https://drupal.org/node/1257952#comment-4898854 .) So what I am experiencing is normal.

However, views have a "Use Ajax" option that is specifically there for exposed filters. Enabling it solves the issue and keep the url clean (without the *0?items_per_page=30* part.)

It does so because ajax does not refresh the page, so the url remains the same (www.example.com/videos/sports in this case.)   :)


where is D6's statistics_counter in D7? I want show the number of  views count in node.tpl.php with Drupal 7, but I cant find  the Drupal 7 Equivalent of statistics_counter.

where can I find it?

The Statistics module shows you how often a given page is viewed, who
  viewed it, the previous page the user visited (referrer URL), and when
  it was viewed.

  In Drupal 7 configure statistics via configuration > statistics.

  To enable collection of statistics, the Enable access log checkbox on
  the Statistics settings page must be checked.

  Enable Count content views to turn on and off the node-counting
  functionality. If turned on, an extra database
  query is added for each node displayed, which increments a counter.

Make sure you set permissions for the module at admin/user/permissions and configure it.

Based on drupal.org and http://groups.drupal.org/node/147619


How to create a list of users who did not submit some webform? I have a webform expecting all users to record their data online.

I would like to list all users who did not submit the webform yet.
I have been trying to use Views, but I cannot find a way to do that.

To list users who have submitted is not a problem, just display the users submitting in Views table.

How can I list all users who did not submit the webform?

Step 1 - Introduce a webform submission flag

Install/enable the Flag module.
Navigate to /admin/structure/flags/add/node and create a flag (do not check the "global" checkbox). Let's assume you label it something like "Webform submission". For "Bundles" (on the same form), check "Webform".

Here is such Flag definition (in export format) you could use for it (just import it in your own site):

$flags = array();
// Exported flag: "Webform submission".
$flags['webform_submission'] = array (
  'entity_type' => 'node',
  'title' => 'Webform submission',
  'global' => '0',
  'types' =>
  array (
    0 => 'webform',
  ),
  'flag_short' => 'Webform submitted',
  'flag_long' => 'Indication that the Webform was submitted already',
  'flag_message' => 'Webform submission recorded',
  'unflag_short' => 'Webform NOT submitted',
  'unflag_long' => 'Indication that the Webform is not yet submitted',
  'unflag_message' => 'Webform submission recording removed',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 0,
    'teaser' => 0,
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

Step 2 - Register webform submissions

Install/enable the Rules module and create a Rule to flag the webform when it is submitted (by the user who submitted the webform and using the flag "Webform submission" (from Step 1).

Here is such Rule definition (in export format) you could use for it (just import it in your own site, which you can do if you have the 'Rules UI' enabled):

{ "rules_flag_a_submitted_webform" : {
    "LABEL" : "Flag a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "node:nid" ], "value" : "5" } },
      { "user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "webform_submission",
          "node" : [ "node" ],
          "flagging_user" : [ "user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 3 - List the webform submissions

Create a view (using the Views module), to list the user who have yes or no flagged the webform with the "Webform submission"-flag from Step 1).

Here is such Views definition (in export format) you could use for it (just import it in your own site, which you can do if you have the 'Views UI' enabled):

$view = new view();
$view->name = 'webform_submissions_by_users';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Webform submissions by users';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Webform submissions by users';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Flags: User's flaggings */
$handler->display->display_options['relationships']['flag_user_content_rel']['id'] = 'flag_user_content_rel';
$handler->display->display_options['relationships']['flag_user_content_rel']['table'] = 'users';
$handler->display->display_options['relationships']['flag_user_content_rel']['field'] = 'flag_user_content_rel';
$handler->display->display_options['relationships']['flag_user_content_rel']['required'] = 0;
$handler->display->display_options['relationships']['flag_user_content_rel']['flag'] = 'webform_submission';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: Flags: User uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'flagging';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'flag_user_content_rel';
/* Field: Flags: Flagged time */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'flagging';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['relationship'] = 'flag_user_content_rel';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'long';
$handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
/* Sort criterion: User: Uid */
$handler->display->display_options['sorts']['uid']['id'] = 'uid';
$handler->display->display_options['sorts']['uid']['table'] = 'users';
$handler->display->display_options['sorts']['uid']['field'] = 'uid';
/* Filter criterion: Flags: User uid */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'flagging';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['relationship'] = 'flag_user_content_rel';
$handler->display->display_options['filters']['uid']['value'] = '';
$handler->display->display_options['filters']['uid']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator_id'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['label'] = 'User uid';
$handler->display->display_options['filters']['uid']['expose']['use_operator'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
$handler->display->display_options['filters']['uid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'webform-submissions-by-users';

Fruit of your labor

If you import the above definitions of the flag, the rule and the view, and you have a few users submit the webform (= record their data), you can visit the relative path in your own site, which should then display a table that looks similar to this example:

Name            User uid   Flagged time
--------------+----------+--------------------------------
Demo.User     !          !
Famous.Dries  ! 8        ! Wednesday, May 11, 2016 - 19:13
Pierre.Vriens ! 19       ! Wednesday, May 11, 2016 - 18:07

For the above example, user "Demo.User" had not yet submitted the webform. The view contains an exposed filter so that you can limit the display to only those who submitted the form, or those who did not yet submit the form.

Start nagging users

If you would enhance your view from Step 3 with the Views Bulk Operations module, and you'd create a Rules Component (using the Rules module) to send an eMail, you could use it to eMail all those users in that view with some type of nagging eMail like "Please record your data...".

What's next?

The above doesn't take into account any webform submissions from before the above logic is implement. However it should be pretty forward to use a mixture of the above (4) modules, including VBO, to perform such one time only update (to also flag the users who already submitted the webform in the past). Anybody interested in knowing about that: Ask (a followup) Question ...


How to map uid in users table data to the entityid in feild table to retrieve data of the users in drupal7 I would like to retrieve data related to users with the uid in users table.

But the uid is not mapped in the feild_data tables which has entity_id and entity_type.

How are these two ids mapped in drupal database 7

For the field_data_* tables, when the entity_type is node, the entity_id & revision_id are the foreign keys into the node table. You can use this to JOIN into the users table.

  //@TODO: Replace field_data_* with the field table in question
  $fields = db_select('field_data_*', 'f');
  $fields->join('node', 'n', "n.nid = f.entity_id AND n.vid = f.revision_id AND f.entity_type = 'node'");
  $fields->join('users', 'u', "u.uid = n.uid");
  $new = $fields
    ->fields('f')
    ->fields('u',array('uid'))
    ->execute()->fetchAll();


Migrating Only DRUPAL7 DATABASE from Microsoft SQL to MYSQL I have Drupal7 site which is running on Microsoft database,

My current requirement is to migrate from microsoft database to mysql database.

if we can migrate will there be no breakage in the present working site,

Any help on this?

A possible approach for this is to use the Drupal-to-Drupal data migration module (aka "migrate_d2d") for this. Quote from its project page:

  ... provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed.


How to add unique classes to FlexSlider slides? (default behavior in v 7.1.x - not in v 7.2.x) I just upgraded the flexslider module from 7.1.x to 7.2.x and it broke my styling because the old version gave unique classes to each slide (also odd and even row classes to every other slide), but the new version gives each slide the same classes.

I really need to style each slide differently so I was using these unique classes.

This "feature request" is in the module's issue queue but it hasn't been touched in a long time and I lack the skills to fix it myself.

Does anyone know how I can give each Flexslider slide a unique class, either using jQuery, PHP or maybe some other module?

OK - I was over thinking this. This script will add id 1, 2, 3 etc to my slides. The slides are just list items - I was all intimidated because only one li is visible at a time, but jQuery doesn't care...

/*Script for assigning each flexslider slide a unique class*/
(function($){
$(document).ready(function(){
    $('.slides li').each(function(i,el){
        el.id = i+1;
        });
    });
})(jQuery);


Behaviors are only called the first time a view is loaded On a Drupal 8 site I have a world map where the user can click on a country; a view with content is then loaded with AJAX using a custom module and the following JavaScript.

(function($, Drupal, drupalSettings, window, document) {
  Drupal.behaviors.worldmap = {
    attach(context, settings) {
      console.log('behaviors called');
      $('#map-container', context).once('addmap').each( () => {
        let map = new InteractiveMap('.interactive-map', (country) => {
          let id = settings.worldmap.yearsnids[country];
          if(!id) {
            id = 0;
          }
          console.log('id');
          let ajax_settings = {
            url: '/my_module/ajax/expand/' +
                  settings.worldmap.ctype + "-infobox/" + id,
          };
          Drupal.ajax(ajax_settings).execute();
        });
        map.init();
      });
...

I have a custom template for the view where I add a ajax link.

See the project

Clicking that link loads another view with more content.
So basically a preview is loaded when the user clicks on a country, and a link in the preview then loads the full content if clicked.

Both the preview and the content (also a view), is loaded from my_module with an AjaxResponse:

namespace Drupal\my_module\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;

class my_moduleController extends ControllerBase {
  public function loadContent($method, $action, $type, $nid) {
    $response = new AjaxResponse();
    // logic to determine which action and type we want to load
     ...
    $build['view'] = [
      '#type' => 'view',
      '#name' => $viewname,
      '#display_id' => $did,
      '#arguments' => [$nid],
    ];
    $response->addCommand(new ReplaceCommand($replaceClass,
                          $build, ['fadeIn']));
    return $response;
  }
}

This all works, but the link in the preview only works for the first preview loaded. In every other preview loaded, clicking the link sends the user to the actual ajax-path (eg. mysite.com/my_module/ajax/expand/my_ctype-infobox/the_actual_id), and the content that should have been rendered to the page are displayed like json in a textbox:

[{"command":"settings","settings":{"pluralDelimiter":"\u0003","ajaxPageState":
...

When the page with the map is loaded, and first time the preview is loaded, 'behaviors called' prints to the console - the link to load the full content works. On subsequent times, clicking on a country loads the preview, but behaviors aren't called at all. 'id' gets printed to the console every time I click.

This is the HTML structure:

The preview is loaded into the info-box__content div, which is outside the #map-container.

Your "once()" function is called on an element with an ID. If your HTML is valid there can be only one such element in the DOM.

What happens with the once() function is that it adds a class to the element which marks it as processed. If the once() function is called again on the same element, it will do nothing. So looking at your code, it does indeed seem it will call the each() function just once on first loading, then never again.

It is right to use the once() function in this situation but you probably want to use a selector representing the children that can be dynamically created. I can't really advise what that should be without seeing the actual HTML.


Prevent Redis Cache from clearing ALL keys We are using the Redis module and Redis Database as cache with the following setup:

$conf['redis_client_interface'] = 'PhpRedis';
$conf['redis_client_host']      = 'redis.internal';
$conf['lock_inc']               = 'sites/all/modules/contrib/redis/redis.lock.inc';
$conf['cache_backends'][]       = 'sites/all/modules/contrib/redis/redis.autoload.inc';
$conf['cache_default_class']    = 'Redis_Cache';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

Also we have our custom module that writes some keys to the database as well.

The problem is that periodically entire redis cache is cleared out ( flushed ) together with our custom keys...

How do we prevent that ?

Can Redis Cache just handle its own keys ?

You can set your default Drupal key up (in settings.php) then have your custom keys set to not expire or last longer.

$conf['cache_prefix'] = array('default' => 'your-redis-key');

See Redis config file for documentation on how to setup max memory and such: https://raw.githubusercontent.com/antirez/redis/2.8/redis.conf

By doing this you would be setting up the policies that Redis will use to clear the cache out and what to clear. It has to clear eventually or it will become unstable, it's just cache after all :) I wouldn't be depending on it to stay that's for sure.


Where do I put image style definition in a module? I'm writing a custom node formatter that needs to use a certain image style. Since I don't want to rely on that image style being defined by the admin, and I want to be sure the style is not deleted, I am going to provide the style definition in code.

Should MYMODULE_image_default_styles go into the .install or .module file?

I think its better to use features and export it, then in your .info file add dependency to it.

other solution is what you say, put it inside MYMODULE_image_default_styles in your .module and re-install your module to make it locked in admin


How does Drupal handle update of multiple module bundles of features without breaking stuff? Let's say I have modules A, B and C.

I create a feature and it makes them into a single module.

Then one day, an update makes A, B and C not compatible, or maybe one deprecated or something.

Then my feature is broken...

Drush installs fresh modules of the newest version automatically, is there a way to do a drush command that bundles the modules inside the feature module?

How does Drupal handle update of multiple module bundles of features without breaking stuff?

It doesn't - that job falls to the developer.

Drupal/Drush doesn't know which versions of unrelated modules work with each other; I imagine that would probably be quite complicated to describe generically.

One method Drupal offers to handle this scenario is using advanced dependencies in your module .info file. For example, when you know that the current versions of A, B and C you have installed work with one another, then lock them down in your feature module's .info:

dependencies[] = A (1.x)
dependencies[] = B (>7.x-1.5)
dependencies[] = C (>1.0, <=3.2)

That way a Drush (or other) updates won't interfere, you'll always have versions that you've manually verified are compatible.

When you're ready to think about updating those modules, download them to your dev version of the site, run all the updates, and all of your tests, and see where you're at. If things work, great, update your .info file with the new dependency versions, release the code, and you're good to go.

If not, then you need to look into whether it's something that you need to fix yourself, whether it's a known bug with the new version and has a patch, a known incompatibility between the two modules, and so on. Beyond writing an excellent test suite that you can trust, I doubt there's an automated or shortcut method for doing this.


How to index content from the Feed Aggregator? I use the Feed Aggregator to create this list of titles and snippets of articles from The Economist. http://www.smagula.org/?q=aggregator/sources/1

I would like to be able to search for a term like "Morality and the brain" and see the recent Economist article appear in the results.

I have dug around on Drupal.org, and have found several others who are seeking the answer to this question here http://drupal.org/node/872686, but no answers or hints.

Is it just a matter of configuring the script which indexes content to go to the right directory? If so, where would I find that script?

The core aggregator module doesn't implement hook_update_index(), so your options here are to either do a bit of coding in a custom module to expose the contents of the aggregated feeds to the search module, or, to use the Feeds module.

I would recommend using the Feeds module, as this allows you to store imported feeds as nodes, which are then automatically included in the search index.


Is it possible to bypass one specific view for authentic users? I have a specific view. This is running well under admin rights but not with specific other roles which do not have the permission “Bypass content access control”

Debugging with devel tools and related blocks as well as change permissions setttings in the role is not solving the problem :-(

Is there a easy way to create the possibility to give this specific view a "Bypass this view only for authentic users" ?

Under Advanced>Other>Query Settings, try checking Disable SQL rewriting.


Change URL to meaningful name when I use hyperlink target Scenario:

Book

When I click book, it will scroll down to the block and url will be www.example.com/#block-block-1. Is there anyway to change url to something meaningful like www.example.com/#book?

I've tried suggestions from How to give meaningful id names to blocks?, but it is not really what I want.

The Block Attributes module will let you add a meaningful id attribute to any Drupal block.

  The Block Attributes module allows users to specify additional HTML
  attributes for blocks, through the block's configuration interface,
  such as class, id, style, title and more.


Facing this error while Acquia Drupal set up Parse error: syntax error, unexpected '[' in
  /Users/***/Sites/devdesktop/acquia-drupal-7.41.47.6289/profiles/acquia/modules/sqlsrv/sqlsrv.install
  on line 10

What can I do to fix this error?

Not much info so this is a bit of a guess...

Acquia support PHP versions:

  5.3.29, 5.4.45, 5.5.30 (default), 5.6.14, 7.0.0 RC2

The error message you're seeing suggests short array syntax isn't understood by the version of PHP that's running, which in turn suggests you're running the 5.3.29 option.

Short array syntax was added in PHP5.4, so in theory to fix you just need to install the software with that version instead of 5.3.


Create a custom area plugin I'm looking to add a plugin for Views to provide some custom functionality in the footer of a view.

First, I created the following in my_module/src/Plugin/views/area/MyPlugin.php:

namespace Drupal\my_module\Plugin\views\area;

use Drupal\views\Plugin\views\area\AreaPluginBase;

/**
 * Defines a views area plugin.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("my_plugin")
 */
class MyPlugin extends AreaPluginBase {

  /**
   * {@inheritdoc}
   */
  public function render($empty = FALSE) {
    if (!$empty || !empty($this->options['empty'])) {
      return array(
        '#markup' => 'test footer content',
      );
    }

    return array();
  }
}

When that didn't work on its own, I realized I needed to declare the plugin in my_module.views.inc:

/**
 * Implements hook_views_data().
 */
function my_module_views_data() {
  $data['views']['my_plugin'] = array(
    'title' => t('My Plugin'),
    'help' => t('My plugin description.'),
    'area' => array(
      'id' => 'my_plugin',
    ),
  );
  return $data;
}

With that added, I can get as far as seeing the plugin available for selection in an area under the Views admin screen. However, when I select the checkbox for it and click Apply, the button text changes to "Add and configure footer" but it doesn't move to the next step in the process.

I've had this happen when writing custom block plugins; the system don't let me place a block when the plugin has something wrong with it. Any thoughts as to what I have here that is wrong?

There was a typo in my plugin filename. :-/


How to get current product id from custom block? I've problem to get current product id from custom block displayed on product page. Here my code :

class TestBlock extends BlockBase {

  public function build() {

$product = \Drupal::routeMatch()->getParameter('node');

$productid = $product->product_id();

return array(
 '#markup' => $this->t('Product ID : ') . '<h2>' . $productid . '</h2>',

    );
  }

}

Do you have any idea to get the current ID from product ?

Thank you for your help.

Use this below code to get product ID

$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id();

and then return the value in custom block,

return [
      '#product_id' =>  $product_id,
    ];


How should I modify a contrib module? I have to modify a contrib module with a custom function. In my case I can't use hooks to extend it.

Is there a best practice, for example renaming the module and placing in sites/default/modules?

If your addition is general and not specific to your site, you could create an issue and post a patch there.

And even if you have a site specific extension, maybe it can be solved in a way that just requires an additional hook to the contrib module itself which could be useful for other use cases as well. Then you could again create an issue for that.


How to load the images in views using ajax? There is a website with rich content (high resolution images).

I wish to load that view block contents (3 view blocks), but not the image, during the page load. Image should load in AJAX after the page load, without any external DOM element trigger. How can I achieve that?

Note

The whole point is increasing the performance without giving up on the functionality.

Check out Image Lazy loader module

  This is a small helper module which will automatically lazyload all
  images for sites with multiple images, which will make the site load
  faster.

  All images will only load when it's visible to the browser window.


I have some difficulties with page.tpl.php I've created a page.tpl.php for my website. it must only contain some blocks not the the $content. that's why I created a few blocks attached them to their region and embedded their corresponding views using print views_embed_view("VIEW_NAME","DISPLAY"); this page.tpl.php works but it has some problems.

when I create a node, after redirecting to its page it only displays this page.tpl.php while the address bar is node address, I mean page.tpl.php overrides node pages. the same problem persists for page display of views. I set a path for page display of views but by going there it again displays page.tpl.php . what is wrong with it?

I mean page.tpl.php overrides node pages

That isn't true, I just think you haven't quite understood how templates work in Drupal. The hierarchy for templates is:

html.tpl.php
  page.tpl.php
    Everything else (including node.tpl.php)

So as you can see, node.tpl.php is inside page.tpl.php, it's not a replacement for it, nor does it override it. But since you're not outputting the main content block in that template file, it stands to reason that the page content will be empty. Unless otherwise specified by perprocessing/template suggestions, page.tpl.php will be used for every single page.

You also need to know that everything (including the main content) is a block, which must be put in a region in page.tpl.php to be displayed. You would typically find the main_content block in the content (or similarly named) region.

To fix your problem, you need to add the main content region back into page.tpl.php.


Change no results behavior of the result of a link generated from a view I created a view that displays links to all of the terms in one of my vocabularies, which was easy enough, but now I am having trouble with what happens when one of those links is clicked.  By default, it will show all content tagged with those terms, which is right, but I want to change the no results behavior when there is not content tagged with a term.

I'm confused as to where I would change the no results behavior for this, do I have to create a separate view, or is this to be done in the view of listing taxonomy terms?

OK!  So after hours of research and playing around in my views, I figured out that the problem was I was having the individual links go to the Taxonomy page for that term.  I turned that off and re-wrote the results of each link to be the term: Name instead of that term's url alias.  I got rid of all my URL aliases for the terms.  I also added a second view that used the term and node relationship and a term: Name contextual filter, and added the custom no results behavior I wanted on that view.

In the end my URLs are not as clean since spaces and ampersands are converted to html escape characters, like "%26", but at least I have a no results behavior I want.


Content not showing when logged out! I don't know why this is happening, but none of my content are displayed when logged out. All the content in views, blocks, everything disappear upon logout. As far as I can remember, I haven't touched any permission. In fact I created this project only a few days ago.

I have two jCarousel slideshows and a few views connected with nodequeues on my site among other things; all of them disappear upon logging out. I have already checked all permissions on views, blocks, and everything I could find.

What can I do to resolve the issue?

As an experiment I searched for a content through the search bar, and the page returned said access denied.

EDIT: Problem solved. The solution has been posted in this thread.

Go in admin/user/permissions and check if the "access content" [and "search content"] is checked for the    anonymous user


How to update non-property value with entity_metadata_wrapper? I wish to update values in commerce_payment_transaction entity. I am using such code:

<?php
$transaction = commerce_payment_transaction_load(58);
 $digests = array(
'DIGEST' => '456',
'DIGEST2' => '478'
);

$transaction_wrapper = entity_metadata_wrapper('commerce_payment_transaction', $transaction);
$transaction_wrapper->payload->set($digests);
$transaction_wrapper->field_my_custom_field->set(1458);
$transaction_wrapper->save();

The problem is, that such code throws me error, that payload is not property of commerce_payment_transaction entity. Although "payload" is column in database table of this entity type. But it is not set as property.

When I don't use entity_metadata_wrapper, this code works for me:

<?php
$transaction = commerce_payment_transaction_load(58);
$digests = array(
'DIGEST' => '456',
'DIGEST2' => '478'
);
$transaction->payload = $digests;
commerce_payment_transaction_save($transaction);
?>

But is it possible to use also entity_metadata_wrapper to update data of entity, that are neither properties nor fields, like payload in commerce_payment_transaction?

The payload column is a property of the commerce payment transaction type already (property is a Drupal core term for any base fields on an entity), but for whatever reason the authors of the module have chosen not to expose it to the Entity API module through commerce_payment_entity_property_info().

Fortunately you can just use hook_entity_property_info_alter() in a custom module to provide the metadata on its behalf. See hook_entity_property_info() for details of the options available.


Second Product variant image in fb share is not coming I am using [node:field-product:0:field_images] metatag image.
With which I am getting top level variant image always. How can I get my second product variant image in facebook share, when I select second product variant from the variant selection dropdown on product display page.

[node:field-product:1:field_images]

You'd add that in your metatag image field together with the first token that you mentioned, separated by comma.

If fb is still not picking it up, after your fetch new scrape info, try adding :file:url to your tokens.

[node:field-product:0:field_images:file:url],[node:field-product:1:field_images:file:url]


How do I display a content author's userpoints next to the author's name on posts? I have set up the User Points module and want to show authors' points next to their name.

What is the simplest way to do this?

The API function to get the points is userpoints_get_current_points() *. Just call that function with the uid of the author and display the returned result.

* Note that my API documentation page only lists the Drupal 7 versions, this function works the same way in Drupal 6 and 7 but others might not.


Creating a file object from a file already in public:// (drupal 7) I am currently writing a module that will unzip a .zip file after it has been uploaded.  Once this file is unzipped I want to search through it and find certain types of files and create content types that have file or image fields that reference these files, but in order to populate the image and file fields I need to create a file object.  How could I do this without having to duplicate the files that have already been uploaded and unzipped?

I think the easiest way would be to create a file object manually, populate it with the file details, and save it using file_save():

global $user;
$uri = 'public://path/to/file.txt';
$filename = 'file.txt';

$file = new stdClass;
$file->uid = $user->uid;
$file->filename = $filename;
$file->uri = $uri;
$file->filemime = 'text/plain';
$file->filesize = filesize($uri);
$file->status = 1;

file_save($file);

After you've done that you'll probably also want to use the file_usage_add() function to declare a vested interest in the file, so that it doesn't get deleted by any other system process:

$type = 'some_type'; // A string used by your module to identify this type of file entry
$id = 'some_id'; // An identifier used by your module to identify this particular file

file_usage_add($file, 'MYMODULE', $type, $id);


How can I add a class to a label? I need to add a class name to certain labels created by Drupal's form API like this:

$form['name'] => array(
  '#type' => 'textfield',
  '#title' => 'Prénom'
);

If I use the following, the <textarea> gets a class, but not the label.

$form['name']['#attributes']['class'] = array('myClass');

I'm looking for something similar that will add a class to the <label>.

This post on StackOverflow says that the Drupal Form API does not support adding classes to labels, but it does contain a decent workaround:

  Instead, you could target it using the wrapper class for the field and label:

.form-item-field-foo label {
  /* CSS here */
}

The API documentation for theme_form_element_label() shows why labels aren't possible (at least not out-of-the-box): the attributes array is initialized in the theme function and populated with just two optional classes ('option' and 'element-invisible').

So, is it completely impossible? In fact, I think it can be done, but I must add that I haven't tried this myself. You could try to:

Add a new #label_attributes property to some (or all) form elements using hook_element_info_alter() in a custom module;
Override theme_form_element_label() and make it merge the $attributes array with the value of $element['#label_attributes'].

If you're going to give this a try, please let us know if it worked.


Exposed filters of a view printed in different places How can I get a view to expose filters that are drunk rendering separately.

Have three filters exposed but I do not know how to get it to fit the layout correctly.

Is it possible to achieve this type of layout with drupal 7?

I have an image that explains:

Thanks.

My first instinct would be to create a custom template for that specific View. However, based on the screenshot, it looks like you only want to move 2 of the 3 exposed filters to the side.

Had you wanted to move all of the exposed filters to the side, it likely could have been done with a custom views-view.tpl.php file.

Perhaps give the  Better Exposed Filters a try!

I haven't personally tested this module, but a Google search lead me to this. Hope this helps.


How to display block using hook_block on specific pages only I am creating the block using the following code , but i need to dsiplay this block only in specific pages only . How can i achieve this ?

function mailusers_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('User Management block'),
      'weight' => 0,
      'status' => 1,
      'region' => 'left',
    );

    return $blocks;
  }

  else if ($op == 'save' && $delta == 0) {
    variable_set('test_block_items', $edit['items']);
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        // Your module will need to define this function to render the block.
        $block = array(
          'subject' => t('User Group Management'),
          'content' => mailuser_block_conent(),
        );
        break;
    }
    return $block;
  }
}

function mailuser_block_conent(){
    //create menu links
     $ret = '<a href="'.$base_url.'/mailusers/adduser">Add User </a>';
     return $ret;
}

You need to add 'visibility' option that is equal to 1 and  'pages' option that should be a string that contains one or more page paths separated by '\n', '\r', or '\r\n' for your block information

 $blocks[0] = array(
  'info' => t('User Management block'),
  'weight' => 0,
  'status' => 1,
  'region' => 'left',
  'visibility' => 1,
  'pages' => 'node/1'
);


Views query building internals I have looked at the source code, briefly, and the problem is that the module is a complex "beast" that relies heavily on the core's API which I am not currently familiar with.

I have a kind of pieced together on how Drupal assembles a completed node object by traversing the various tables (node, node_type, field_config, field_config_instance, etc).

What confuses me is the data abstraction layer. field_config has a storage_type which appears to indicate whether a field is stored in SQL or not.

From what I have read and interpreted, Drupal is flexible enough to have a system which is data store agnostic, so if I had a products content type and capacity out-grew what MySQL was capable of, I could (in theory) switch to MongoDB or similar DBMS which allows better scaling.

So, how would I attach a field to a content type, which let's say was stored in Mongo, but the remaining fields stayed in SQL?
More interesting, how does VIEWS deal with this disconnection in data storage? If I store some fields for a given type in MongoDB and some in SQL how does VIEWS handle the JOINS and filtering capability?

As it currently stands it is not possible for Drupal to run a pure MongoDB installation with Drupal. Drupal has made a lot of progress towards abstracting out database connectivity into a central model layer with Drupal 7 and Drupal 8 promises even more. However it is still a work in progress and while a majority of the functionality is available as MongoDB backend, as it stands today a few of the components remain dependant on SQL.

As most of the work to port Drupal to MongoDB has been towards scalability and performance, it is possible to have a site where public page views are 100% on MongoDB. Performance benchmarks on a MongoDB backed Drupal instance are quite impressive.


Create block in template.php I have the feeling that I'm doing something stupid or missing something obvious...
I want to create a block in template.php in my custom template but it is not showing in admin/structure/block
The code i use is simple:

/**
 * Implements hook_block_info().
 */
function MYTHEMENAME_block_info() {
  $blocks = array();
  $blocks['eeeeeeee'] = array(
    // The name that will appear in the block list.
    'info' => t('eeeeeeeeeee'),
  );
  return $blocks;
}

Then i created a custom module, to see if a have a typo,  with the same code. Just changed MYTHEMENAME with MYMODULENAME and I can see it in admin/structure/block

I tried changing MYTHEMENAME to phptemplate
Cleared the cache many times

Is it even possible to create a block in template.php?

I'm not sure this is possible. You would create the custom block in a module, add content to it there as well. Then you can theme it or call it in various places inside your theme as well as theme the actual block. That is the usual use scenario for blocks. I will try to add some links in just a bit with more explanation.


Acquia installation is up-to-date but requests update and reports errors I have installed Acquia Dev Desktop in order to have a local Drupal development environment. My computer is running Windows 7. The prototype site provided with the installation appears to run fine, but there are two problems in the dashboard.

(1)
Under "Reports > Status report", the section on "Drupal core update status" is in red and says, "See the available updates page for more information and to install your missing updates." The words, "available updates" in that are linked. When I click that, I get "All of your projects are up to date" plus a link for "Check manually". When I click that, it works for a while and then says, "Checked available update data for 5 projects. ... All of your projects are up to date."

So Drupal both reports being up-to-date and says that there are "missing updates."

(2)
Under "Reports > Available updates", there is a red box at the top of the page with four bullets:
• Notice: Undefined index: reason in theme_update_report() (line 86 of C:...\local\DrupalDev\DrupalTest\modules\update\update.report.inc).
• Notice: Undefined index: in theme_update_report() (line 137 of C:...\local\DrupalDev\DrupalTest\modules\update\update.report.inc).
• Warning: date_timezone_set() expects parameter 1 to be DateTime, boolean given in format_date() (line 2040 of C:...\local\DrupalDev\DrupalTest\includes\common.inc).
• Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in format_date() (line 2050 of C:...\local\DrupalDev\DrupalTest\includes\common.inc).

Below that, under the heading, "Drupal core", there is a yellow text box. In the top right corner is a warning icon (dark yellow triangle with exclamation mark) and the box has the following text:
"Acquia Drupal 7.34.40 (Drupal 7.34 core)
Recommended version: ()
Includes: Acquia Connector, Bartik, Block, Color, Comment, Contextual links, Dashboard, Database logging, Drupal 7 driver for SQL Server and SQL Azure, Field, Field SQL storage, Field UI, File, Filter, Help, Image, List, Menu, Node, Number, Options, Overlay, Path, Pathauto, RDF, Search, Seven, Shortcut, System, Taxonomy, Text, Toolbar, Update manager, User"

===================

I found the recommendation to use Acquia Dev Desktop in three places:

www.drupal.org/node/1248034

www.drupal.org/node/263

www.drupal.org/node/1065212

which are the links in the first, second, and sixth bullets in "Local server setup" at www.drupal.org/node/157602 .

So it comes highly recommended. But the above behavior looks pretty flaky. Have I done something wrong with the installation?

Thanks for your help.

For the errors, I think you could continue developing your Drupal site with it but for me I wouldn't like those in my site. I myself don't know the cause of it thought but I found a recent issue in the Acquia forum: Errors on Clean Acquia Drupal Install which still has no reply on a fix.

Option 1: Use Acquia

Try uninstalling and reinstalling the whole Acquia Dev software and see if the issue still persists.

Option 2: Use XAMPP(I use)/WAMPP

I've been using this since I started web and its straight forward. You don't need to change any settings too. What you need to do is:

Download the .exe from the XAMPP page
Install the application
Download Drupal Core that can be downloaded here
Extract Drupal Core into C:/xampp/htdocs/[your drupal root folder] (if you just chose the default settings of XAMPP on installation)
Go to http://localhost/phpmyadmin and create your database there, just use the defaults too
Start the installation of your Drupal site by going to http://localhost/your-drupal-root-folder-name]


Where are functions being called from when errors are vague? I have the following errors which show up randomly when browsing the site. It's hard to reproduce, but also hard to debug. I was able to get it in the error state and have it stay during a reload in order for me to debug it.

I tried going to the code in question which resides in includes/theme.inc But when going to that line 1525. It doesn't really tell me much. The error states that its missing a tpl file, but doesn't say which one as I'm assuming its due to the $template_file  variable being blank.

How can I trace where is this function being called in order to find the module that is the culprit of this error?

I don't have xdebug installed as I know that can be used to do the tracing. I also don't have experience with it neither as I've mainly solved most of my php issues just by doing a print_r() 99% of the time and I'm able to find where the issue lies, but this time its different.

What methods are there to debug it and find the source of the problem?

The Devel module can be extremely helpful in cases like this.
Once installed, go to the admin/config/development/devel path, and you will see an option for additional error handlers:

If you select the Krumo backtrace option(s), Devel will register itself as the PHP error handler, and it can then show error messages with the full backtrace!


Images are not showing in localhost I have taken a clone of my site, downloaded the files folder and the database to my local system.

I am using Xampp server in my local system and I have kept the site image ‘files’ folder in the sites/default/files directory.

The problem is that in my local system 30% of the images are not displaying in the local site. The images are available in the files/images folder,
but in local site the images are not showing.

I tried all the process and i also updated the base url in my setting.php file but the issue is not yet fixed.

According to my understanding the issue is related to the image path. In site those images we are calling through css is not taking the site base url. For example:

Current path:
http://www.localhost/sites/default/files/images/mobile-block-img-new.png

Correct path: http://www.localhost/repliconwebsite/sites/default/files/images/mobile-block-img-new.png

Please suggest if you get the solution.

As you are using subdirectory structure at localhost and previous drupal installation was at root directory, the base url will not change for database entries.

Use Pathologic module to change base url of urls coming from database

or

search n replace them in .sql file, then import the database.

search: src="/sites/default/files/images

replace: src="/repliconwebsite/sites/default/files/images


how separate Entity Reference in view? I have two content type, content type A and content type B , I used Entity Reference field in content type B to reference content type A.

I created view with field Entity Reference ,In Entity Reference there are more field included how can i separate this all field in view ?

Add a "Relationship" to your view:

And then select "Entity Reference" in the "Filters" select list. You can choose whether is a content entity that is referenced, or referencing.


Mucho Menu is Not Displaying D7 I am using Drupal-7. I am trying to build a Fly out menu that have images, content blocks.

I am using the MuchoMenu to create top menu into my site.

I wanted to create Flyout menu same like displayed in Mucho Menu with image block.

I have created Main MuchoMenu, Mini Panels, Content Types to display images and content blocks.

But, my Menu Items are not displaying into my website. Do I have to add anything into my page.tpl.php or page--front.tpl.php pages? I have added Main MuchoMenu block into "Main Menu" Region.

In both page.tpl.php and page--front.tpl.php files, I have added this into menu section:

        <?php if ($main_menu): ?>

            <?php print theme('links__system_main_menu', array(
              'links' => $main_menu,
              'attributes' => array(
                'id' => 'main-menu-links',
                'class' => array('links', 'clearfix'),
              ),
              'heading' => array(
                'text' => t(''),
                'level' => 'h2',
                'class' => array('element-invisible'),
              ),
            )); ?>

        <?php endif; ?>

    <?php if ($secondary_menu): ?>

        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t(''),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>

    <?php endif; ?>

Please let me know as I am new to Drupal.

Thanks!

Thanks for editing @Krishna Mohan.

I have changed module from MuchoMenu to "TB Mega Menu". TB Mega Menu allows us to create block into drop down menu.

And, I think "to display custom menu" need to print block into that region.

So, Define region into .info file
and print that block into page.tpl.php file.

So, in page.tpl.php replace code with this:

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

I am new to drupal, so I might be wrong.

Thanks!


Delete a custom content type When my module is uninstalled, I want to delete the custom content type created by config files on module installation. On Drupal 7 there was a node_type_delete(node_machine_name). What is the equivalent method/function, in Drupal 8?

See How to delete a content type, programmatically? for the easiest way for your use case. This works for any config entity that doesn't already explicitly depend on your module (those are uninstalled anyway).

The nice thing about that approach is that the user will be informed on the uninstall confirm age that this stuff will be deleted.

To delete using the API, node types are entities, so you delete them like all others: NodeType::load('id')->delete()


How do I get the roles of the currently logged-in user? In Drupal 8 I would use the following code.
$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();

What is the equivalent code I should use in Drupal 7?

You can access the current user in D7 via the global $user object
global $user;
$roles = $user->roles;


Unable to migrate users I have been using the migrate module to migrate users from Drupal 7.59 to Drupal 7.59. I encounter the following error.

Migration for NonDomainUserMigration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054     [error]
Unknown column &#039;pgid&#039; in &#039;on clause&#039;, in /app/includes/database/database.inc:2227

What could be the issue? I can't find any pgid column in the drupal database.

the following is my User migration code

<?php
abstract class NonDomainBaseMigration extends Migration {

  // A Migration constructor takes an array of arguments as its first parameter.
  // The arguments must be passed through to the parent constructor.
  public function __construct($arguments) {
    parent::__construct($arguments);

    // With migrate_ui enabled, migration pages will indicate people involved in
    // the particular migration, with their role and contact info. We default the
    // list in the shared class; it can be overridden for specific migrations.
    $this->team = array(
      new MigrateTeamMember('Moses Liao', 'moseslgz@sph.com.sg',
        t('Tech Lead')),
    );

    Database::addConnectionInfo('legacy', 'default', array(
      'driver' => 'mysql',
      'database' => 'zaobao_drupal',
      'username' => 'root',
      'password' => 'password',
      'host' => 'mysqldb',
      'prefix' => '',
    ));
  }
}

class NonDomainUserMigration extends NonDomainBaseMigration {
  public function __construct($arguments) {

    parent::__construct($arguments);
    $this->description = t('Legacy Zaobao Drupal 7 system Users');

    $query = Database::getConnection('default', 'legacy')
    ->select('users', 'u')
    ->fields('u');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationUser();

    $source_key = array(
      'pgid' => array('type' => 'int',
                      'unsigned' => TRUE,
                      'not null' => TRUE,
                      'description' => t('Source ID'),
                     )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key,
      MigrateDestinationNode::getKeySchema(), 'legacy', array('track_last_imported' => TRUE));

    $this->addSimpleMappings(
      array(
        'uid',
        'name',
        'pass',
        'mail',
        'theme',
        'signature',
        'signature_format',
        'created',
        'access',
        'login',
        'status',
        'timezone',
        'language',
        'picture',
        'init',
        'data',
      )
    );
  }
}

its seems to me that pgid is wrong. Should be uid for users


Content Types in Select list using views How do I put all my content types into a select list so when users select a content type, they are taking to a page which makes them add new node to the content type?

I think You can create exposed filter Content: Type which will give users  the ability to select content type.

Then in Fields section add field Content: Type, select "Output this field as a link" and type: node/add/[type].

If You want to display only one "add" link per content type select "Exclude from display", go to Format settings and select "Content: Type" from Grouping field Nr.1's options.


How can I load a view inpage using AJAX when a node is flagged? I have a view that gives the users the option to flag nodes.  Below this view I need another view listing the results of flagged nodes to show up without the page needing a reload.  My skills are limited to Front end development so I'm unsure how I can do this via AJAX.

I did find this module:
https://drupal.org/project/jquery_ajax_load

I'm not sure how to implement this module since I need this view to commence upon the first flag event(?)

Would someone be able to help me find a solution?

Cheers!

This is actually a pretty common functionality and there is a module for it, Views Flag Refresh:

  Views Flag Refresh allows site administrators to configure which views are refreshed automatically via AJAX when certain flags are selected. This is useful when you have a view that filters by flagged content and you want the view to be refreshed automatically when content is flagged or unflagged elsewhere on the page.

If this doesn't fit your exact needs, there are lots of code snippets in the Flag Javascript API Documentation that might set you in the right direction.


Do blocks replace custom content panes? In Drupal 7 I use the ctools_custom_content (Custom content panes) module to create exportable panel panes to drop into my panel pages. This module doesn't exist for Drupal 8, nor do I see any other way to create panes with the Panels, Page Manager and ctools modules installed.

Have blocks, which are now entities, effectively replaced custom content panes in Drupal 8? Or is there a different core feature or contributed module that I should look to for similar functionality?

There are 3 different things called "block" in Drupal 8. plugins, config entities and content blocks. See Adding custom block problems for an explanation.

But yes, to answer your question, content blocks are exposed as block plugins and can then be used not only for placing blocks in regions but also with page_manager/panels. You don't need anything else.

One limitation is that they can't be exported easily into config, since they are content. If you don't need extensible structure but only a text or a reference, then you could build your own block plugin or wait for a contrib module to do that (I recently saw a module that did basically that in 7.x with its own plugin system, would be very easy to make the same for 8.x as core provides 90% of what's needed. Can't remember the name right now.)


Compound field that includes a file field I'm trying to figure out how to create a custom compound field, but I'm not quite sure how to add a file field to it.  There are plenty of tuts on creating compound fields that are comprised of text fields, but I can't find any that talk about combining text and file fields.  I guess the main problem is that I don't understand how the 'schema' function would work, since it refers to Drupal data types, but the data uploaded via the file field won't be stored in the Drupal database, but rather stored on disk, as any other uploaded file would be.

Can someone point me in the right direction?

A file field is an entity reference field pointing to the File entity (or in D8.4 to the Media entity). To build such a file field extend FileItem (which parent is EntityReferenceItem). An example for this would be the image field ImageItem, which is a compound field adding properties like title, alt, height and width:

ImageItem::propertyDefinitions()

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    unset($properties['display']);
    unset($properties['description']);

    $properties['alt'] = DataDefinition::create('string')
      ->setLabel(t('Alternative text'))
      ->setDescription(t("Alternative image text, for the image's 'alt' attribute."));

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t("Image title text, for the image's 'title' attribute."));

    $properties['width'] = DataDefinition::create('integer')
      ->setLabel(t('Width'))
      ->setDescription(t('The width of the image in pixels.'));

    $properties['height'] = DataDefinition::create('integer')
      ->setLabel(t('Height'))
      ->setDescription(t('The height of the image in pixels.'));

    return $properties;
  }

The properties for the referencing part are inherited from the parent.


From where does variable_get() get the first parameter? function variable_get($name, $default = NULL) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

From where does variable_get() get the first parameter?

I think you're referring to the $conf variable?

It's set in sites/default/settings.php (or sites/SITENAME/settings.php if you have a multi-site installation), and that file is included in Drupal's page build.


Price formatter for range of variation products Is there a way to write a price formatter to display the lowest and highest price of a collection of product variations? My reason for thinking it might not work is the scope of the product variation vs. it's "parent" product display.

If not, is there some way to build a view that will query to max ( and another for the min ) price of a collection of variations under one product display?

For Example:

I have a product display with 4 variations. Each variation has a different size lets say, and therefore each variation has a different price. I'm looking for a way for my product display to show the price of the cheapest variation and the highest priced variation as a range. As opposed to the first variation price that is shown now

Commerce Pricing Attributes

  This module provides some enhancements to the Commerce Product Option
  and Commerce Product Attributes handling by applying pricing rules to
  custom product attributes. So, you can add attributes to products that
  affect the final product price.

Dynamic price calculation based on selected operators.
Cart combination based on product attributes.
Support for multi currency.
Multilingual attributes.
Different attributes and settings per product.
Price adjustments either per item or per order.
Rules integration.
Easy UI for editing and reordering attributes


How to change the user-profile.tpl.php file to a customized outline like Linkedin for Drupal 7? I'm using Drupal 7.9 for an internal website. I'm trying to customize the "user-profile.tpl.php" file so it shows the fields that I've customized in the "admin/config/people/accounts/fields" to be shown below:

<<>>image block on the left<<>>

"Full Name
Job Title/Position

Your Organization Name Here, INC
1234 Your Address Here
Long City Name, ST 12345

(P) 555-123-1234
(E) emailaddress@somecompany.com"

But I'm having an issue writing the PHP in the "user-profile.tpl.php" file (I didn't touch the user-profile-category.tpl.php or the user-profile-item.tpl.php files)

This is what I've coded, which obviously is printing everything out wrong.

    <?php if ($user_picture): ?>

        <?php print $user_picture; ?>

    <?php endif; ?>

<?php print render($user_profile['field_profile_full_name']) ?>

<?php print render($user_profile['field_profile_job_title']) ?>

<?php print render($user_profile['field_profile_organization']) ?>

<?php print render($user_profile['field_profile_address']) ?>

<?php print render($user_profile['field_profile_city']) ?>, <?php print render($user_profile['field_profile_state']) ?> <?php print render($user_profile['field_profile_zip_code']) ?>

(P)<?php print render($user_profile['field_profile_business_phone']) ?>

(E)<?php print render($user_profile['field_profile_e_mail_address']) ?>

When it prints on the page, everything still has a bunch of page breaks and space in between the info. And the address line isn't included in one block, it puts it on a new line each item.

How do I write the code so I can get the format outlined above?

You can utilize views module to achieve what are you looking for, with some CSS styles.

While using views you have two options view user information:

Option 1:

Create block view (Users)
Select user fields you want to display
Then add Contextual filters (User: Uid)
From the configuration page make sure to select Provide default value
Then from Type drop down menu select User ID from logged in user.
Then apply changes.
Save view.
Under Structure -> Blocks locate the new created view in content region
Configure the block to appear only on the user account page user and users/*
Then you need to clear the original drupal content in the user view account page by apply this custom module.

Code:

function mymodule_menu_alter(&$items){
  $items['user/%user']['page callback'] = 'mymodule_user_view_page';
}

function mymodule_user_view_page() {
  return array();
}

Option 2:

Create page view (Users)
Apply steps 2-6 as Option 1
Add Path user/%user under Page Settings
Save view.


Hook to get details of taxonomy term page I wrote a module to store taxonomy page details to DB. My requirement is to store tid, term name, vid and UNIX timestamp to DB table on every load of taxonomy term page. Here is my code:

function reporting_api_taxonomy_term_load($terms) {
  $tid = $terms[arg(2)]->tid;
  $vid = $terms[arg(2)]->vid;
  $term = taxonomy_term_load($tid);
  $name = $term->name;
  db_insert('reporting_api')
    ->fields(array(
      'tid' => $tid,
      'name' => $name,
      'vid' => $vid,
      'timestamp' => REQUEST_TIME,
    ))
    ->execute();
}

But it creates unwanted rows with timestamp only. Can any one help to fix this. Is hook_taxonomy_term_load is the correct hook.

Taxonomy terms can also be loaded when you're not on a taxonomy page, so arg(2) will be empty, hence empty records.

To fix:

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  db_insert('reporting_api')
    ->fields(array(
      'tid' => $term->tid,
      'name' => $term->name,
      'vid' => $term->vid,
      'timestamp' => REQUEST_TIME,
    ))
    ->execute();
}


How can I enable moderator role's ability to administer users only apply to certain user roles? I am making a Drupal (v7.8) website with several user roles, including Super User, Admin, Moderator, Editor, and Reviewer. I want the Moderator role to be able to use the privileges that Administrate Users gives, but only for roles "below" Moderator (i.e. Editor and Reviewer).

I haven't been able to find a module or documentation on how to do this.

Thanks!

There is quite a new contrib module called "Permissions subset" for D7 you could test if it meets your requirements.


How to convert an order price to a different currency in Commerce 2? The Stripe payment gateway only accepts JCB and Diners Club transactions in US dollars (no international currencies).

Most of the transactions on my site are in Japanese yen.

In fact, I would prefer to have everything in yen, but I want to try to handle JCB (major credit card in Japan) by somehow converting the JPY prices to USD and then billing in USD (of course, I will notify the user I am doing this).

Ideally, the flow looks like this:

User browses my store where prices are shown in JPY.
User adds a product to the cart.
User goes to checkout and chooses a payment method (if user chooses "Pay with Mastercard/Visa" (standard Stripe payment gateway), transaction proceeds as normal.
If the user chooses "JCB", price is converted to USD and then billed in USD.

How might I begin to implement this kind of conversion?  Or, is there a better approach/flow for converting the order price from one currency to another?

This is what I've done for now.

Add the currencies you will use in the UI. /admin/commerce/config/currencies
Add a "currency" product attribute in the UI. /admin/commerce/product-attributes
On the product edit page for the product you want, add variations with the currencies and set the prices.

This lets the user choose the currency he/she likes. So you can just put a message "If you're using JCB, you must pay with JCB."  It's not perfect but it's a decent solution.


use content type field value as css class in views I have a content type article with a field called 'type'. Based on the value of this field I want to display my content type differently in a view that I created with the Views module. In order to do that I would like to add the value of the type field as a css class to each item in that view.

The easiest way to achieve this was actually use the views module itself. The value of the type field can be easily used as a row class. Thanks for the other suggestions, but in the end this was all I needed.


How to get the first non-empty field value of a referenced entity in views? The website has two content types:
Magazine and issue.
I'm using the Entity Reference module to create a magazine archive website.

I have a views that list all magazines. Each magazine is with an image of issue that related to this magazine. There is a relationship (entity reference: referencing entity) and the aggregation setting is active (use aggregation).
Everything is OK but there is a problem I couldn't solve.
The image for each magazine is the image of the first issue of this magazine. But not every "first issue" has an image and it shows the default image.
What I want to do is to show the first issue's image that's image field is non-empty or show any related issue's image on this views. How can I do that?
Note: Some magazine's any issues doesn't have any image and if I filter out these issues, then the related magazine will not be shown. I think what I want to do is if any of the issue has an image show it or show the default image.

From Everything is OK but there is a problem I couldn't solve I supposed you successfully create a view of issues and their related magazine and I focus on the problem.

There are two cases,

at least one of the issues has an image
non of them has an image

In order to create a view for case 1, you need to modify your existing view to have sort criteria on image_field:fid (Issue image field, using relationships you can have this)

and sort it descending

and set the Pager to:

Use pager:
Display a specified number of items| 1 item

in this way, if there is any issue with an image, the first one that has image is displayed.

Lets handle the case where there is no issue with image. The image field is displayed in here, it can be in a

, but it is empty. We have to insert a default image in it. Simply add css like this to your theme

.views-field-field-image{
       width: ...px;// you standard display of width
       height: ...px;// you standard display of height
       display: inline-block;
       background-image: url('');

Now if there is an image, the

 layer will go behind the image and it will not be shown and if there is no image, we have set the
 dimension and also an image for it to be displayed.


Search Solr View with exposed filter fullsearch return no results I setup a Solr search index (Solr 7.7.1 and Search API Solr 3.2) with custom entities. I have several fields indexed and 2 of them are fulltext. Additionally :

I setup the view with an exposed filter in a block (page view)
No Ajax option is set
I have a filter Search enabled : Fulltext Search with following options :

Expose this filter to visitors
Signle filter
Contains any of these words
Allow multiple selections
Parse mode : direct query
All Fulltextfields selected

Exposed form settings

Exposed form in block : YES
Exposed for style : basic

I also setup some facets on other fields

When I come to the page, all results are displayed by default. When searching for any term(s) via the Full-text textfield, I am getting blank results. Instead if I select some facet options, results do show up accordingly to the facets.

How can I get the Fulltext search to work?

After several hours, I discovered that search_api_solr 8.x-3.7 was the issue. I downgraded using composer to the latest v2.7 and it works fine.


Is there is a module like, "dbcm"? Is there is a module like dbcm in Drupal 7?

I want to know changes happen in database, so I can update my production sites with all configuration changes: new block, new views, new (CCK) fields.

I have tried the feature module to export my changes, but it doesn't export everything I need. There are also some configuration changes missed after exporting.

Is there a module that store in the database such configuration changes?

Configuration management is a major initiative in the upcoming Drupal 8. Here's Dries talking about it.

In D7, you'll need cTools and Features and Strongarm. And here's a comparison of staging/deployment tools.


Issue in posting a comment When I post a comment, I get the following error on Drupal 7:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'comment-28-0-0-und' for key 'PRIMARY': INSERT INTO {field_data_comment_body} (entity_type, entity_id, revision_id, bundle, delta, language, comment_body_value, comment_body_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => comment [:db_insert_placeholder_1] => 28 [:db_insert_placeholder_2] => 28 [:db_insert_placeholder_3] => comment_node_multi_discussion_theme [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => test [:db_insert_placeholder_7] => ) in field_sql_storage_field_storage_write() (line 451 of /ftphome/dev_itf_events/modules/field/modules/field_sql_storage/field_sql_storage.module).

What could be the cause?

Hi you have to remove the row from field_data_comment_body table where entity id is 28 ..


php and html tag problem when customizing menu items I was trying to print the menu item description under the menu name.

I add this into the menu.inc under bootstrap theme, where the function bootstrap_menu_link(array $variables) is:

if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $element['#title'] .="
 " . $element['#localized_options']['attributes']['title'];
  }

my interface then showed something like product
LED Drivers as the menu item - the
 tag is printed out directly. I looked at the source code, that area shows: &lt;br&gt; , so I then tried using &lt;br&gt; in the php string, but the source code showed &amp;lt;br&amp;gt; this time. How can I correctly insert html tag into $element['#title']?

You could check if where the call to the l() function is created (in the function mentioned: bootstrap_menu_link), the third parameter contains the following element in the array:

'html' => TRUE

This tells drupal to output the title of the link as html and not run it trough check_plain().

Also, I would create a custom theme based on the bootstrap theme and add my customization there.


Show profile field on profile page I created user-login.tpl.php file in my custom theme.

Then I add this code :

<div class="profile"<?php print $attributes; ?>>

<?php print ($user_profile['field_nom']);  ?>

    <?php print_r($user_profile); ?>

It display my name correctly but, when I inspect in the browser its look like this ...

My name:&nbsp;

Branquet

I just want to have the text, not a bunch of unless divs

One option is you can user php function in tpl file before print.

strip_tags($user_profile['field_nom']);

Refer http://php.net/manual/en/function.strip-tags.php


how to check if javascript is enabled in a module drupal7 I'm building a simple module that shows a jQuery UI dialog.
I have some HTML in my code but I only want to show this to users that have javascript enabled.

to give you an example here are the contents of my .module file:

function popover_init() {
    drupal_add_library('system', 'ui.dialog');
    drupal_add_js(drupal_get_path('module','popover') . '/popover.js', 'file');
}
?>
<div id="dialog" title="D7 jQuery dialog">
    <p> bla bla bla </p>
</div>

How do I check the drupal way that javascript is enabled so I can stop my module from loading unnecessary stuff ?

I don't think there is a way. Because your module runs on the server and it cannot interact with the client's browser in any way.

Here's an answer on stackoverflow: Check if JavaScript is enabled with PHP


Cannot add a file with Search API Attachments I'm using Search API with Solr and Tika under D8 to build a search engine on my website.

I could not find any tutorial under D8 for that, so I followed one I've found on D7. However, when I try to add a field "file" to my index, it appears in a section called "Skipped fields" with the following message :

  The following fields cannot be indexed since there is no type mapping
  for them:

  Source » File (type "entity:file")

  If you think one of these fields should be available for indexing,
  please report this in the module's issue queue. (Make sure to first
  search for an existing issue for this field.) Please note that
  entity-valued fields generally can be indexed by either indexing their
  parent reference field, or their child entity ID field.

Has anyone managed to index files using Search API Attachments ? I cannot understand how to fix this message.

Also, it does not make sense to me to "index their parent reference field" because this will put an ID in Solr, and not a real text file metadata ..

there are some steps to follow in the module README.txt file :

https://cgit.drupalcode.org/search_api_attachments/tree/README.txt?h=8.x-1.x#n81


Can drush make fetch dependencies for a newly added module, without using it to build the whole site? If a module includes a drush make file to fetch its dependencies, is it possible to run that make file by itself somehow against a pre-existing site's codebase? In other words, I didn't use drush make to build the site, but I'd like to use it just to fetch the new module's dependencies. Is that possible?

Yes, it is possible. Just run the makefile on the current codebase, and specify --no-core option from the drupal root:

$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example

Here's the log of a test I did:

$ drush dl drupal
$ cd drupal-7.28/
$ drush dl mailchimp
  Project mailchimp (7.x-3.1) downloaded to /tmp/drupal-7.28/sites/all/modules/mailchimp.

$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example
  Make new site in the current directory? (y/n): y
  Beginning to build sites/all/modules/mailchimp/mailchimp.make.example.
  libraries-7.x-2.2 downloaded.
  mailchimp downloaded from https://bitbucket.org/mailchimp/mailchimp-api-php/get/2.0.4.zip.

$ ls sites/all/libraries/
  mailchimp
$ ls sites/all/modules/
  libraries  mailchimp  README.txt

If any of the projects/libraries declared in the makefile already exists, it will be overwritten.


What could be causing drupal to want to reinstall itself after I clear cache? I am trying to update Drupal from 7.17 to 7.18. I uploaded a copy of my site from a test server to my production server. Everything installs fine, I actually see the site working, and I can navigate it. Then, as soon as I perform updates on modules and core, I run database updates, and then the site automatically navigates me back to install.php to reinstall the site from scratch. I have tried to reinstall the site several times from scratch, manually and using Drush.

What is the mechanism that determines to redirect to install.php? How can I determine how and why this is happening?

Even though the install.php page is showing up in the browser, drush status shows that the site is up, running, successfully connected to the database with correct theme. According to Drush, everything is working properly.

That occurs because Drupal can't connect to its database

Ensure you have:

settings.php

in your Drupal /sites/default folder.

settings.php must be readable by the webserver user and contain valid database connection string credentials for that server. Make sure the base_url is either default commented out or valid for that domain.

See _drupal_bootstrap_database for the place where the install.php redirect occurs.

Also, make sure you've run update.php and do clear all caches if possible.


An entity autocomplete widget with opportunity to save its text content There is the standard insert or edit node form with an entity_reference field and the EntityReferenceAutocomplete widget.

The client needs to save string values inputed to the widget in case of entity wasn't selected from the autocomplete list. That is, client needs to have possibility to select entity from the autocomplete list or input string value if, for example, entity is absent in the list. And new entity shouldn't be created in this case.

I'm thinking how to create this opportunity the best way. And I'm little bit confused.

Is it possible to perform it with alter hooks only and without creating new field widget ?

Or otherwise is it possible to do it creating a new field widget having inherited it from the class EntityReferenceAutocompleteWidget ?

Or maybe the single solution for it is creating a custom widget based on TextField with including autocomplete function manually ?

Has anyone encountered with a simular task ?

There is no need to create a custom table or a second field. While editing your entity reference field, in the "Reference type" section, you could check the "Create referenced entities if they don't already exist" option. If for instance, your field is referencing taxonomy terms, a new term for the referenced vocabulaty will be created. I hope that this helps.


Restrict user access to several actions in function I have a function, that returns statistics for the user:

function module_menu() {
  $items = array();
  $items["statistics"] = array(
    'page callback' => 'module_statistics',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function module_statistics($group_id, $user_id = NULL) {
  global $user;
  if ($user_id == NULL) {
    $user_id = $user->uid;
  }
  $result = module_statistics_table($group_id, $user_id);
  print $result;
}

I want only the administrator to have access to this function with $user_id != NULL. So the user will be unable to watch someone elses statistics. I have an access argument 'admin tasks' for the admin. How to do the else statement:

if ($user_id == NULL) {
  $user_id = $user->uid;
}
else {
  if($user has no access to 'admin tasks') {
    return HTTP 403 Forbidden status code;
    exit from function;
  }
}

In your hook_menu call you can use different access arguments, to make sure only administrators access the callback function. For example,

'access arguments' => array('administer users'), // usually Administrators have this permissions

If users with some other roles try to access the menu, they'll get the Access Denied message by default.

If you want your users to access the function and restrict only certain part, you can check the user role in that case:

if ($user_id == NULL) {
  $user_id = $user->uid;
}
else {
  if(in_array('administrator', array_values($user->roles))) {
    //apply your exit function logic here
  }
}


hook_page_attachments() not called from mytheme.theme file I am trying to load an asset library in my Drupal 8 custom theme. I have created the library and can load it via mytheme.info.yml file.  However, if I try the load it using hook_page_attachments() in the mytheme.theme file, then the function is not called.

I did a search for this function in the Drupal 8 standard installation and it only ever seems to be called from modules.  Can hook_page_attachments only be called from modules? Any suggestions on why this is not working.

mytheme.theme file content:

function mytheme_page_attachments(array &$attachments) {
  $attachments ['#attached']['library'][] = 'mytheme/general-js';
}

It appears that this function is only callable from a module, as it is listed in  Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module but not listed as a valid method in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

It should be noted that the related function hook_page_attachments_alter() can be called from the theme layer (i.e. can be called from mytheme.theme file).

function mytheme_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'mytheme/general-js';
}

Alternatively one can attach libraries to a page from within hook_preprocess_page()

function mytheme_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
}

The advantage of these two methods is that it enables one to utilize logic/code to determine whether or not to attach a library to a page.


Currently logged in user's roles How to get the currently logged in user's roles in Drupal 8 ?

For example in D7 we have $GLOBALS['user']->roles;

Something like:

$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();

will return an array like:

Array
(
  [0] => authenticated
  [1] => administrator
  [2] => some_other_role
)

where the array values are role IDs (equivalent to the machine name of the role in Drupal 7).  In OO code, use the appropriate mechanism get the current user from the container, eg

$current_user = $container->get('current_user');


Need a hand altering a theme I'm using a theme called Danland, and I want to change the Recent Posts block to show only post title and publication date. As it stands it shows 3 columns, one of which is post title, and the last two of which are blank when you are not logged in and say "edit" and "delete" when you are logged in. I also want to kill the table border.

I can't find the right css file to edit. Using firebug to ID the td and other tags to kill to get rid of the extra columns, but I can't find them in the theme files. Firebug IDs them as being in style.css, but there's nothing there. Where does this code live?

Please go to views admin interface and check the views name as Recent post(display type block), views gives  you flexibility for adding any number of fields your content type has, also it will allow you to have custom classes to fields that you will be needing to theme.About classes and ids already there, they are coming from views theming you do not have to touch there all you have to do is add fields you want, while adding it will allow you to style it by adding wrapper divs or other html element.Once you finish with editing the view,check the block in firebug you will see your calsses and ids working there, then add css for it in your Danland theme .css file.

Key Points which may help you:

how to add/remove fields from view
how to add custom classes to the fields in views
Once done style it using your theme css file.


Is there way to rearrange node on front page? I tried use weight module but it arrange node only on admin interface. Is there way set weight to node on front page?

You can create views with weight sorting nodes and set it as front page


Multi-site installation with shared database but different user table I need to install drupal multi-site with shared database but just need to create some tables specific to that site like, users table should be different for sub-sites.

I know about full sharing or full different database for different sites, but I need partial different database. I searched for it on google but didn't get exact solution so posting it here if anybody has clue about?

You can try editing you sub-sites settings.php file and you just need to provide different prefix for user table (as you need only this table different).

I am providing sample here so that you can implement and see if it works.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
           'users'     => 'abcsite_',
      ),
    ),
  ),
);

The above code will tell your installation to use abcsite_users (you need to create table first with same structure as of default users table) for entering user details.


Trying to use Panelizer for a node content type with a panels layout I've got a zen theme, with a sub theme, with a plugins folder enabled in which I have a custom layout.
I've got panelizer enabled on a content type and I am trying to make that content type use my custom layout, however, when I select the layout for that content type it doesn't seem to use it. Usually devel_themer it looks like the page is still using node.tpl.php, I want to override the whole page with my custom layout.
Are their any things I should bear in mind using panelizer - stuff I need to disable  /enable.

Panelizer 7.3.1 Panelized content shows in preview, but when I view the live page, it looked like a regular, un-panelized node.

Turned on and off everything I could think of...

Finally, I looked at the Display tab of my content type, and clicked open the Custom Display Settings. I turned OFF "use custom display settings for view modes: Full Content and Teaser". Suddenly my nodes were panelized. Click back on "Full Content", and panels disappear.


Is there a replacement for comment driven? The comment driven module and similarly the comment alter module are dead or dieing and have no ports to drupal 7. Anyone know if there is a module that could replace either of these?

I have found a replacement for my uses of comment driven. Its called Node Changes, and allows changes to nodes to be recorded as comments.

  This module stores the changes of a node into a field attached to comments allowing to display a kind-of activity stream on the node much like on drupal.org issues just with a lot less custom code.


Programmatically translate taxonomy terms I have a vocabulary of taxonomy terms I get through taxonomy_term_load($tid); and displays in views page. How do I get and display the terms depending on the user's language?

Basing on Using the i18n API from other modules, the code should be the following one.

$term = taxonomy_term_load($tid);
$translated = i18n_string_translate("taxonomy:term:$tid:name", $term->name);


Several fields in view I've got content-type includes 'field1' and 'field2'. These fields are integer value.
Thanks to Views module I created page 'Page1' with contents. In main menu I've got search whit some filters. After filling filters and entering, we can see appropriate contents in 'Page1'. I'd like to create filters or fields in search to allow user to fill in 'min' and 'max' values. After it I want to choose a content only if 'field1' and 'field2' of that content is beetwen 'min' and 'max'.
How can I do it?

Make use of the contextual range filter module to create a filter range on your field 1 and field 2 and expose the filter

is a simple plugin for Views that adds the option to contextually
filter, not just by a single value, but also by range.
Numeric, alphabetical (string) and list ranges are all supported. Node
ids, user ids and even taxonomy term ids are all special cases of
numbers so will work also. Range-filtering on the "created" (posted)
and "updated" (last modified) node properties is also supported,
provided you use the correct format as dictated by Views. So, YYYYMMDD
for full dates or one of the shorter year+month, year-only,
month-only, week-only and day-only formats.

UPDATE:
Once you have installed the modules. Go to the views display you are working on, and under the filter category, select add.
Choose the field1 you created with an integer field and click add to display

Check the box expose filter to visitors. In the operator drop down, select is between and two text box should appear(min and max). Click on apply and you should see the form on top of your display. Do the same for field 2


INVALID_SERVICE Error Code on CAS forced login page i have configured a forced login for the /intranet page

/fr/admin/config/people/cas

I have created a menu link to that page /intranet

when clicking on it , the cas creadential are asked and it returns an

  INVALID_SERVICE
   error

http://mywebsitedomainfr/casservice?q=fr%2Fcasservice&returnto=http%3A%2F%mywebsitedomain%2Ffr%2Fintranet%3Fq%3Dfr%252Fintranet&ticket=ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserver||0||Validation response received from CAS server: #012#012#012#012#011#012#011#011Le ticket &#039;ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserver&#039; ne correspond pas au service demandé. Le service original était &#039;http://mywebsitedomain/fr/casservice?returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet&#039; et le service demandé était &#039;http://mywebsitedomain/fr/casservice?q=fr/casservice&amp;returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet&#039;.
Error when validating ticket: Error Code INVALID_SERVICE: Le ticket 'ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserveur ne correspond pas au service demandé. Le service original était 'http://mywebsitedomain/fr/casservice?returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet' et le service demandé était 'http://mywebsitedomain/fr/casservice?q=fr/casservice&returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet'.
http://mywebsitedoamin/fr/casservice?q=fr%2Fcasservice&returnto=http%3A%2F%2Fmywebsitedomain %2Ffr%2Fintranet%3Fq%3Dfr%252Fintranet&ticket=ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserverdomain||0||Converting query parameter 'returnto' to 'destination'.
http://mywebsite domain/fr/intranet?q=fr%2Fintranet&q=fr%2Fintranet||0||Temp disable flag set, skipping CAS subscriber.

this happened to be a nginx misconfiguration