How to print paragraphs in twig template? I have a content type, basic, where i have added a Paragraph field field_pr that has two fields: field_text, field_color. I have a twig template node--basic--full.html.twig where I want to print the value of the paragraph field node.field_pr.

node.field_pr can have between one and ten paragraph values.

When I print the array for content.field_pr, I get a huge array. However, I only want the values from the field_pr.field_text and field_pr.field_color. How would I be able to do this from the node twig template?

I have tried the following but cannot seem to access the values. What am I missing?

{% for field in content.field_pr %}
   {{ field[loop.index0].entity.field_text.value }}
   {{ field[loop.index0].entity.field_color.value }}
{% endfor %}

{% for field in content.field_pr %}
   {{ field[loop.index0]['#paragraph'].field_text.value }}
   {{ field[loop.index0]['#paragraph'].field_color.value }}
{% endfor %}

Here is an image of the array that is printed for the node.field_pr field.

Not sure if it's possible with your current approach. Here is how I would approach this.

In your node template file just do a {{ content.field_pr }}

Create a template file for your paragraph.

  paragraph__[view_mode] (e.g. paragraph--default.html.twig)

  paragraph__[type] (e.g. paragraph--image.html.twig)

  paragraph__[type]__[view_mode] (e.g.
  paragraph--image--default.html.twig)

  source: Theming in Paragraphs for Drupal 8

In paragraph--[type].html.twig you do {{ content.field_text }} and {{ content.field_color }}

In twig templates where I am pulling in content from an array of fields, I have found this works: {{ content.field_paragraphs.0 }} using 0 for the first item and going from there.


How to create an Audio playlist Are there any opportunities to create "classic" playlists with Audio or any other similar modules? I primarily would like to let mp3-files be played, but in a way that it cannot be easily directly downloaded (considering the fact that as it's written on Audio module's admin interface, "You should be aware that even when audio is not marked as downloadable, clever users can still download it, this just makes the work harder.")

After uploading some separate Audio nodes, Audio players can be displayed via Views module like this (with some randomly uploaded tracks):

But this is NOT a good solution for me as it's not like a normal playlist, as these are separate audio players...
There is support in Audio module for the little bit ugly-looking XSPF Web Music Player - Extended, but I didn't find any opportunities to create a playlist with it either.

Any suggestions with Audio or any other suitable modules?
Thanks!

The http://drupal.org/project/jplayer module allows for playlists and so forth, but unless you are up for some obfuscated javascript and a whole bunch of other coding (that in the end is nevertheless subvertible [sp?]) the mp3s will still be downloadable by most advanced users.  (Or perhaps investigate the private file serving methods drupal offers, but then you have to balance the overhead there)

We have done this here with CCK and AudioField. We are using views to show the list of the individual nodes. Every entry with it's own player. You can even start them in parallel :-).

Originally we were using the audio module. But we had all sorts of problems with this module. Since development has been stopped 2 years ago we went for the CCK & AudioField solution which works great.


Why do I get an error about the modules/custom directory not existing? I have installed Drupal 8 on Ubuntu. All works well, but I cannot create a new module using Drupal Console.

When I run drupal generate:module, I get the following error message.

  [InvalidArgumentException]
  Module path "/var/www/html/maryem/modules/custom" is invalid. You need to provide a valid path.

Why? How can I avoid that error message?

There is no such thing as modules/contrib or modules/custom with the vanilla download of Drupal.

It is a convention you can use for organization. Create the folders yourself. Drupal will still find the modules in either one. The same principle applies to the themes folder. Some modules that say "download the JS plugin to /libraries" - you would have to create this folder too.

Drush, Drupal Console, and Composer all understand this, as well. If you are using Composer, you just need to inform it in your root composer.json, example:

    "installer-paths": {
        "docroot/core": [
            "type:drupal-core"
        ],
        "docroot/modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "docroot/modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "docroot/profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "docroot/profiles/custom/{$name}": [
            "type:drupal-custom-profile"
        ],
        "docroot/themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "docroot/themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ],
        "docroot/libraries": [
            "type:drupal-library"
        ],
        "drush/contrib/{$name}": [
            "type:drupal-drush"
        ]
    }

When requiring modules, profiles, or themes, Composer will then place them in the appropriate directory.

Old issue still the answer is missing. The path needs to exist before running the console command. The error message means that "/var/www/html/maryem/modules/custom" does not exist. Options:

Provide the correct path when the folder does exist
Create all the directories in the path in /var/www/html/maryem/modules/custom For instance when custom is missing it should be created in /var/www/html/maryem/modules before I run de console command.

In my case I provided --module-path=/modules/custom which expects to find it in the root of the server. Since I was running the console command in the web server document root of Drupal, I should have used a relative path like this --module-path=modules/custom or a correct absolute path like you did in your example.


How to make exposed timestamp filter accept human readable date I'm using Drupal 8. I created a new content type (title, body, image, date).
The date is a timestamp field.

I used the devel module and the Realistic Dummy Content module to generate a test content for my view test.

I created my test view and chose the date as an exposed filter.

Here is my configuration:

And this is my view:

When I apply my filter, I want to say all contents having a date greater than my input:

If I test with 01/31/2018 - 02:54, nothing was changed!

But If I test with the unix value: 1538323253, my filter works well!

Any idea please to make the filter with human readable value?

I ran into this issue on D7. I enabled the views query and noticed that the values were being passed as human date to the query rather than timestamp.

So what I did was use hook_views_query_alter and converted them to timestamp.

Example code (D7 code)

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'list_employers') {
    foreach ($query->where[1]['conditions'] as $con_key => $con_val) {
      if ((strpos($con_val['field'], 'node.created = ') !== FALSE) &&
        empty($con_val['value'])) {
        $date = $con_val['field'];
        $date = str_replace('node.created = ', '', $date);
        $date = date('m/d/Y', $date);
        $start = strtotime($date . ' 12:00 AM'); // convert to timestamp
        $end = strtotime($date . ' 11:59 PM'); // convert to timestamp
        unset($query->where[1]['conditions'][$con_key]['value']); // remove default condition
        $query->where[1]['conditions'][$con_key]['field'] = 'node.created';
        $query->where[1]['conditions'][$con_key]['value'][0] = $start;
        $query->where[1]['conditions'][$con_key]['value'][1] = $end;
        $query->where[1]['conditions'][$con_key]['operator'] = 'BETWEEN';
      }
    }
  }
}

https://www.drupal.org/project/date_popup

This will add the native HTML 5 date popup widget to all date fields in views filters.

But this module won't work with timestamp fields.


Set default language for domain I have one site with 2 domains one example.de and one example.com its a multilanguage site, so i have urls like this example.de/de/content and example.de/en/content etc, and same on com domain.

Default language is de for this two domains, but for example.com i need english to be default language.

i thought i can change it in settings.php with $conf['language_default'] like this:

$conf['language_default'] = (object) array(
  'language' => 'en', 'name' => 'English', 'native' => 'English',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

its working but for both domains... . also i managed to redirect users to en on example.com (my home page is a node with nid 89)

function MYMODULE_node_view($node) {

        if ($node->nid == 89) {
            if ($_SERVER['SERVER_NAME'] == 'www.example.com') {
             header('Location: http://www.example.com/en');
            }
        }

    }

but its not an option

Is there any solution to change default language for my example.com domain?

Though I'm surprised if there's not an option in the user interface, according to language_default, it appears you could set the default language as a $conf variable in the shared settings.php file.

Something like

settings.php:

switch($_SERVER['SERVER_NAME']){

  case 'www.example.com':

    $conf['language_default'] = (object) array(
      'language' => 'en', 'name' => 'English', 'native' => 'English',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Example per-domain cache prefix if using memcache
    $conf['memcache_key_prefix'] = 'en_';

  break;
  case 'www.example.de':

    $conf['language_default'] = (object) array(
      'language' => 'de', 'name' => 'German', 'native' => 'German',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.de', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Ensures cache varies by domain
    $conf['memcache_key_prefix'] = 'de_';

  break;

}

Update: Added example memcache cache key prefix setting - to ensure cache varies per domain, if required.

in your template.php use the following code. :

function THEME_preprocess_page(&$vars) {
   global $language;
   if ($_SERVER['SERVER_NAME'] == 'www.example.com' && $language->language != 'de') {
       header('Location: http://www.example.com/en');
   }
}


How do I prevent Drupal raising a segmentation fault when using a Node.js theming workflow? Symptoms:
Some drush commands fail; Some Drupal pages are blank.
The failing drush commands report "Segmentation fault: 11"
The Apache log (e.g. php-error.log in MAMP) also shows the same error.
Background:
If you use a gulp or grunt workflow - to compile your theme's SASS etc. - you may run into a problem where drush commands throw a segmentation fault 11 as does Apache whilst serving Drupal pages as blanks (WSDs).
Probable cause
This is because files from your grunt or gulp workflow environment in  node_modules are erroneously being registered by Drupal itself as a bi-product of drush cache-clear all for example. There are dozens of these .js files and Drupal can't handle them ... it's possibly a PCRE regex that is the root cause as this is known elsewhere. Anyway ...
It doesn't always happen
It's not clear whether some modules (like Browser Sync for example) induce this error as a node.js style (i.e. gulp or grunt) workflow can work perfectly before failing in this way.

Here is the solution you're looking for. Much more elegant and less work:

"scripts": {
  "postinstall": "find node_modules/ -name '*.info' -type f -delete"
}

Just a slight alteration on @iamcarico's answer above.

note: you may need a .npmrc with just the following content:

unsafe-perm = true

my solution was in the past to move the node stuff inside of a hidden folder like ".npm" for example.


Dynamic select list in the form API (dependent dropdown list)? First I want to select State (like Tamil Nadu, Sikkim, Kerala) after selecting state, depended city list will be display another dropdown list ( for example Tamil Nadu -> Chennai, Salem, Karur and Kerala -> Trivandrum, Kochin etc)

Please help me please how to make it, here i have tried some coding but does not work, Please help me

Sstate - Table

$query_state = db_select('state', 's');
$query_state->fields('s',array('State_code','State_name'));
$query_state->orderBy('State_name','ASC');
$state_results = $query_state->execute();
$options_state = array();

foreach($state_results as $state_record) {
  $options_state[$state_record->State_code]=t($state_record->State_name);
}

$form['state'] = array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' => $options_state,
  '#required' => TRUE,
);

City - Table

$query_city=db_select('city', 'c');
$query_city->fields('c',array('District_Code','District_Name'));
$query_city->condition('State_Code','$state_record->State_code','=');
$query_city->orderBy('District_Name','ASC');
$city_results = $query_city->execute();
$options_city = array();

foreach($city_results as $city_record) {
  $options_city[$city_record->District_code]  =t($city_record->District_Name);
}

$form['city'] = array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#required' => TRUE,
  '#states' => array(
    'visible' => array(
      ':input[name="state"]' => array('value' => $options_state)
    )
  )
);

Basically, in your form declaration, you have to add

In your form['state'] :

'#ajax' => array(
  'callback' => '_ajaxfunction',
  'wrapper' => 'divaroundseconddropdown'
);

Then in your form['town'] :

'#prefix' => '
',
'#suffix' => '
',

Now in your _ajaxfunction :

function _ajaxfunction($form, $form_state) {
  return $form['city'];
}

Now, back to your form['town'], you simply have to build your $options with the $form_state['values']['state'] variable, which will contain what has been filled in the first dropdown.

Everything is documented here.

[EDIT]

First replace $state_record in your $query_city by $form_state['values']['state']; *You can check if the value is formatted the right by dpm($form_state); in your _ajaxfunction.

Then :

$form['state']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '
',
  '#suffix' => '
',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state"]' => array(
        'value'=>$options_state))));

Close your function, open a new one :

function _ajaxfunction($form, $form_state) { return $form['city']; }

You can try the following,

$form['state'] = array(
    '#type' => "select",
    '#options' => $category,
    '#name' => "category",
    '#attributes' => array(
        'onchange' => 'getCategory(this);',
     ),
    '#id'   => "state",
    '#default_value'=> $cat_default,
    '#prefix' => '',
);
$form['city'] = array(
    '#type' => "select",
    '#options' => $skillset,
    '#name' => "skillset",
    '#id'   => "city",
    '#default_value'=> $skil_default,
    '#prefix' => '',
);

Using the onclick getCategory(this) function you can fetch the city corresponding to the state using AJAX and add to the second field i.e. city  using javascipt

document.getElementById("city").innerHTML = result;


jQuery ajax request breaks drupal behaviours In the Drupal commerce checkout I want to fill in the billing information automatically. I do that by attaching a javascript to that form and retrieving the information that is stored in the line item. That works great except for only one thing. The first time I click “continue on the next step” nothing happens and the page refreshes. But the second time the button does work and goes to the next pane.

It has the same strange behaviour when I load the page once, go to another page and go back. Then it works from the first time.

My javascript is rather basic and does work, but for some reason it breaks my form.

(function($) {
Drupal.behaviors.mymodule = {
    attach : function(context, settings) {

         var txtFullname = jQuery('input[id^=my_dynamic_id]');

        // do ajax request
        jQuery.ajax({
            type : "POST",
            url : 'http://example.com/retrieve_information',
            data : {
                'order' : settings.order_id
            },
            dataType : "json",
            success : function(data) {
                txtFullname.val(data.fullname);
            }
        });

    }
};
}(jQuery));

One thing I really have a hard time grasping (but then again I'm a Drupal beginner) is how a DOM operation can break the whole thing, especially when the only thing I'm doing is filling a simple textfield.

Is there a way in jQuery to trigger drupal to rebuild a form, because I have the gut feeling that this is the reason why it works the second time.

EDIT: It doesn't seem to have anything to do with jQuery as I have rewritten that part to use the Drupal ajax framework.

From the moment the billing information is filled in - i'm setting the values of the field  in hook_form - the submit button doesn't seem to work for the first time.

I presume you need to add that code with in document ready. Some thing like give

// Code that uses jQuery's $ can follow here.

(function($) {
Drupal.behaviors.mymodule = {
    attach : function(context, settings) {
      jQuery(document).ready(function($) {
         var txtFullname = jQuery('input[id^=my_dynamic_id]');

         // do ajax request
         jQuery.ajax({
            type : "POST",
            url : 'http://example.com/retrieve_information',
            data : {
                'order' : settings.order_id
            },
            dataType : "json",
            success : function(data) {
                txtFullname.val(data.fullname);
            }
        });
      });
    }
};
}(jQuery));


How do you modify the form after it validates and show's errors I have built a form using CCK in Drupal 6. I have two fields, one which is called health plans and the other is called terms. If I select a health plan I update the terms via AJAX (both are select lists).

So for example: (health_plan_field)Plan A -> (terms_field)(1, 3, 6, 12)

I submit the form and serialize the terms inside a session so that I can keep them.

My problem is that if the form has errors, the terms field is blank because it starts empty until a health plan is selected. So if I have already selected a plan and terms, when the form returns after errors I have nothing.

I have tried to use form_alter (have used this before) by recursively walking down the cck fields on $form to modify the term_field options based on what I have in the session. This does nothing on return.

My code is as follows (called from hook form alter):

function acg_pportal_new_service_order_form_cck_walkerTerms(&$array, &$cck_fields) {

$terms = unserialize($_SESSION['termDataFromForm']);
if (!empty($terms)){
    foreach($array as $key => &$value) {
        if (in_array($key, $cck_fields)) {
        unset($value['value']['#options']);
        $first = "";
        foreach($terms as $key2 => $value2){
            if (empty($first)){
                $first = $key2;
            }
            $value['value']['#options'][$key2] = $value2;
        }
            $value['value']['#default_value'] = $first;
            $value['value']['#value'] = $first;
        }

    }
    }
}

Is there anything that you know that will help me in this case.

You need to set the form to rebuild on validation fail.

$form['#rebuild'] = TRUE;   // cause form rebuild after validation failed

Then you can use your $form_state['values'] inside your hook_form_alter().

OR

You can create a custom function and use the #after_build property.

hook_form_alter() gets called whenever a form is build or rebuilt, meaning it'll get called again when the form fails validation. At this point you can look at the $form_state variable to see the current state of the form and do whatever you need to do.


Can't click link added to header of a block In Drupal 7 I created a views page, and I want users to have the option to view the results either as a list, or with thumbnails (like on a lot of websites). The only way I can think of doing that is creating one page with the results as a list, and having a link to another page with the results that have thumbnails.

But my question is, how do I add just a random link to the top of my block page that will direct users to the 'thumbnail' page?

I tried to use 'unfiltered text' in the header and put the html for a link in there, and when I went to the page it looked like a link, but I couldn't click it. Any suggestions?

If I understand the question correctly, this can easily be done using Views alone with a nice tabbed menu:

Create your view page as normal, with the default information provided, except for the url - set that to whatever you want, in my example /tabs
change the Display name under Page details to: Base (just to make things easier to read later on)

Add a Page
Change the Display name to the format type of the default page, presumably 'List View'
set up the format, show, fields, filter, sort, etc. how you want the list view to be displayed - be sure to change the 'For' drop down from All displays to 'This page (override)' - or the changes you make will be set for all the pages, but you want different settings for each page
set Path: tabs/list
set Menu: Default menu tab, Title: View as List, Parent: already exists

Add a Page
Change the Display name to the format type of the second page, presumably 'Thumbnail View'
set up the format, show, fields, filter, sort, etc. how you want the thumbnail view to be displayed - be sure to change the 'For' drop down from All displays to 'This page (override)' - or the changes you make will be set for all the pages, but you want different settings for each page
set Path: tabs/thumbnail
set Menu: menu tab, Title: View as Thumbnails, Menu: Navigation

This should create a tabbed menu at the top of your view for easy navigation by users:

You can remove title by setting it to <none> or leaving it empty. Then other block can be used to look like title with links on it.


How do I get line breaks when using Plain Text format? I feel like this should be reaaaaaally simple, but it's driving me crazy.

I have 'plain text' selected for all my Body elements. I don't want anyone to be able to put in any html at all when filling out forms.

However, I do want the line breaks preserved.  On the configuration page for plain there there is indeed a 'check this box to to turn line breaks into br and p, but no matter what I check or how I rearrange the weight of the filters, I cannot get it to preserve the breaks.

What is the correct configuration to get this to work so that I can preserve returns in the texts?

This seems like a Drupal 7.x bug.
Changing the order of filters doesn't work in my case.

My short term solution was to throw this inside my theme's template.php (ref):

<?php
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$vars, $hook) {
  // Add line breaks to plain text textareas.
  if (
    // Make sure this is a text_long field type.
    $vars['element']['#field_type'] == 'text_long'
    // Check that the field's format is set to null, which equates to plain_text.
    && $vars['element']['#items'][0]['format'] == null
  ) {
    $vars['items'][0]['#markup'] = nl2br($vars['items'][0]['#markup']);
  }
}
?>

For fields in views, it's needed to set this option separately in the "Rewrite Results" section of the field settings.

This great module can help you
https://drupal.org/project/wysiwyg_linebreaks

  Wysiwyg Linebreaks allows users of wysiwyg editors to save and open
  markup from their website with linebreaks instead of <p> and <br />
  tags.


How to access weight of a paragraph in twig? I use paragraphs with my content type. I need to show weight (order) value of each paragraph in my twig template. I can change weight with select box when I edit the node, but I can't figure out how to get it in twig.

I thought it would be something like this:

function ws_preprocess_paragraph(&$variables)
{
    $par = $variables['paragraph'];
    $myweight = $par->weight;
}

Please help)

The weight of a paragraph is not stored in the paragraph itself, but in the host field.
So if you need to get the weight of a paragraph from within the paragraph (e.g. from  within hook_preprocess_paragraph()), you have to go upwards to the parent entity and find your the weight there:
function MYMODULE_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $parent = $paragraph->getParentEntity();
  // get all paragraph IDs sorted by weight
  $weights = array_map( function($a) {return $a['target_id'];}, $parent->get($paragraph->get('parent_field_name')->value)->getValue());
  // find the weight of my paragraph ID
  $weight = array_search($paragraph->id(), $weights);
  // ...do stuff with $weight... e.g. assign it to a Twig variable
  // $variables['weight'] = $weight;
}

Please note that the weight is easier to get if you use the paragraph host field template instead (see @4k4's comment below the original question):

Use {{ loop.index0 }} in a field template like
field--field-paragraph.html.twig

You'll find it here for its fields:

$variables['content']['FIELD_NAME']['#weight'];

and then again in every item of a field:

$variables['content']['FIELD_NAME'][0]['#weight'];
$variables['content']['FIELD_NAME'][1]['#weight'];
$variables['content']['FIELD_NAME'][2]['#weight'];
$variables['content']['FIELD_NAME'][..]['#weight'];


No Breadcrumb settings in Bartik theme? The breadcrumbs in my Bartik theme work perfectly. However, in my Zen subtheme are skipping a level!

I just noticed that there is no Breadcrumb settings section in the Settings for the Bartik theme.

I am using the Menu Breadcrumbs module for both sites...

Try using Custom Breadcrumbs instead.

  Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.


How can I use one of the pre-set email texts for user registration in a custom module At /admin/config/people/accounts, there are several stock email messages set.
How can I use one of these when I am sending emails from a custom module?
The text that's being used in "Welcome (new user created by administrator)" is all that I need, plus there's the bonus that our client can edit this email in the future if they want to.
I can send the message easily enough using:
$params = [
   'title' => "My Title",
   'subject' => "An Account Has Been Created for you",
   'message' => Html::escape("Some text here")
 ];

$result = $mailManager->mail($module, $key, $to, $language_code, $params, NULL, true);

Is there a variable somewhere to get the pre-entered text?

I guess this should be possible via configuration API. Look for the suitable entry where the message body is saved, call it via the service to put it into a variable. Then you can do additional coding with the string variable.
More information you can find here:
Configuration override system in the docs

Thanks for the guidance on this @dercheffe. I found what I needed in the config file user.mail.yml and was able to pull the strings outs as an array with :
$config_txt = \Drupal::config('user.mail')->get('register_admin_created');
However, I had the problem of how to replace the user and site variables in the strings from the config file.
Long story short, I didn't even need that config information.
The answer was to just use the Drupal function
 _user_mail_notify('register_admin_created', $newuser);
The email is sent out based on the text in the configuration to our new user.


How to include CSS for a custom admin theme? I want to include my custom style.css in admin pages in Custom Admin theme I have been create.
I am including CSS in .info file as follows

name = Example Module
description = Custom Example Module
core = 7.x
configure = admin/config/example-module/settings
permissions = admin/people/permissions#module-example-module
stylesheets[all][] = css/style.css

and I used mymodule_preprocess_page(&vars) , but I didn't see any result.

You can add yourstyl.css in admin theme's .info file.
Just goto your active admin theme, find and open its .info file and place a simple line here; stylesheets[ ] = css/yourstyle.css . It works like a charm.

Try drupal_add_css() function in your template file.


How to show summary in node view? While adding article, I am having an option to enter summary for article. But this summary is not displaying in node view. I wanted summary to be displayed in full node view.

Any ideas how can I show summary in full node view?

-- Many thanks for your time.

Solved it by overriding node template for my content type.

1) Copied node.tpl.php of my theme and renamed it to
node--content_type.tpl.php.

2) Put the following code at desired place:

<div class="fullmode_summary">
    <?php if ($view_mode == 'full'): ?>
      <?php print render($node->body[$node->language][0]['safe_summary']);  ?>
    <?php endif; ?>
</div>

May help someone having same issue.

Use 'display suite'.

enable display suite extras
map the summary field.

In addition to display suite, this requires the token module.

Map by, adding a custom field via the tabs on the bottom left of manage display

List item
Then add a code field
Add a label
Bind it to Node
Enter the text [node:summary]
Check the Token box

You can then add the field you just created to your display.


How to get the language code when a language name is given? We are creating nodes programmatically on submitting a form. The language of a node is an input value in the form.
How can I get the langcode, when I have the Language name?

For example, user may type English. So i should convert it to "en"

If there an in-built function for that?

You can do it with this code.

// Language to search.
$find = 'French';

// Getting all the available languages.
$languages = \Drupal::service('language_manager')->getStandardLanguageList();

$key = key(array_filter($languages, function ($array) use ($find) {
  if (array_search($find, $array) === FALSE) {
    return FALSE;
  }
  return TRUE;
}));

// If you have the devel module installed you can use the dpm function.
dpm($key);

Drupal 8 has a built-in function that lists all the language codes: LanguageManager::getStandardLanguageList(). My suggestion is to give the users a dropdown list of languages.

use Drupal\Core\Language\LanguageManager;
$standard_languages = LanguageManager::getStandardLanguageList();

foreach($standard_languages as $key => $val){
    if($val[0] == "English"){
        echo $key; //write your code

    }
}


Views to display nodes based on ACL permission I'm trying to use Flexiaccess with ACL to build a view based on node that the user has access granted by Flexiaccess.

I found this on Drupal.org, it's the same use case, but is not working for me maybe because is for Drupal 6. (http://drupal.org/node/549412):

    Here's how to do it:

  Under Arguments, create a new argument: "Node: Nid"

  Under "Action to take if argument is not present", select "Provide
  default argument"

  Set the "Default argument type" to "PHP Code", and enter the
  following:

  global $user; return db_result(db_query("SELECT
  GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au
  INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view
  = 1 AND au.uid = %d", $user->uid));

  Then check "Allow multiple terms per argument", and click "Update".

I follow those steps but my view shows nothing.

Any help is really appreciated.

According to: https://www.drupal.org/node/1255426, Drupal 7 does not have db_result function. You have to replace it with db_query().

Code which worked in my special case:

<?php
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));
$result = $query->fetchObject();
return reset($result);
?>

Use Contextual Filters instead of arguments in Drupal 7 and check "Provide default value" and in PHP code insert like this.

global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));

$result = $query->fetchObject();
 return reset($result);

You can also get users allowed to view against each node like this by adding field for "views PHP" with this code

$query = db_query("SELECT GROUP_CONCAT(CAST(au.uid AS CHAR) SEPARATOR ',') FROM acl_user as au INNER JOIN acl_node as an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND an.nid =$row->nid ");
$result = $query->fetchObject();
$res = reset($result);

$myArray = explode(',', $res);
//print_r($myArray);
foreach($myArray as $key=>$value){
                     $user_id = $value;
                     $query_user = db_query("SELECT name FROM users WHERE uid = $user_id");
                    $result_u = $query_user->fetchObject();
                    print "<span>" .$result_u->name. "  </span>";

          }


How to set number of articles per page on the Blog module? I came across a 6.15 drupal site that I had to modify one simple thing:
put instead of 3 articles per page , 5
on the front page the blog resume is shown, and it seem that the blog module doesn't have any setting to do that..
It isn't made with views, nor is it a block.. I don't even know how they get to the front page (probably by being promoted..)

here a snapshot of what I see on the front page...

how can I set the number of articles?
I can't find it anywhere...
I was thinking of defining a view or something and renounce of this built-in functionality...

Looking at blog_page_last and node_page_default, I see that both use the persistent variable called "default_nodes_main" (which defaults to 10) for the number of nodes per page. That variable can be set on the form at /admin/content/node-settings, under "Number of posts on main page".

The above means that both the /node and /blog pages use the same value. If you want different values for both pages, you probably need to rebuild one (or both) of them as a view.

I hope that answers your question.

in blog.pages.inc,under blog_page_last() function,replace

->limit(variable_get('default_nodes_main', 10)) to ->limit('YOUR CUSTOM VALUE').

i think it will help you.


User Registration to appear in a block I want the user registration to appear in a block in some other page than home, let's say a page called "Sign up." What I want to achieve is the following.

Well there is Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Download and install the module.
Navigate to admin/structure/block You can see Registration form as a block there.

It is pretty simple to handle this. I fixed this on Drupal 7 like below

Create block say 'User register form' in content top.
Put this code in its body
<?php print drupal_render(drupal_get_form('user_register_form')); ?>
In text format select PHP code
In visibility settings, under roles select 'Anonymous user' or who ever who wants to see the form.


Bootstrap dropdown parent link not clickable This is the first drupal project i'm working on and i'm having the following problem.
I have my dropdown menu set up as followed:

The problem is that the parent link "Materialen" is not clickable while the children are.
What should i change to be able to click the parent link?

A nice way that work with Drupal 8 would be to override in your subtheme:

menu--main.html.twig

And remove

 data-toggle="dropdown"

Cheers

Just add "disabled" as a class with dropdown-toggle class on Anchor tag


Adding a custom Token so i can use in Webforms I am having the smart-ip module installed. It allows me to get User country, city etc very easily like this:

echo $_SESSION['smart_ip']['location']['country_code'];

I want to use this as a token replacement in webforms field. But I have no idea how to do it.
Got confused after googling. I should do the hooking in template.php? How do i do it? :/

Create your own tokens!

You could create a small module that implements the token hooks (D6, but D7 should be similar), like so:

function YOURMODULE_token_list($type = 'all') {
  $list = array();

  $list['smart-ip']['smart-ip-country-code'] = t("The Country code");
  // ...etc

  return $list;
}

function YOURMODULE_token_values($type, $object = NULL, $options = array()) {
  $tokens = array();

  $tokens['smart-ip-country-code'] = $_SESSION['smart_ip']['location']['country_code'];
  // ...etc

  return $tokens;
}

Or, even better, add these hooks to the smart_ip.module file and submit a patch to the module maintainer :-). Tokens are really great, and it would certainly be a good addition to the smart_ip module.

install a module called webform_tokens

and what u can do after that is adding your custom token to the module by altering it.


How do I use hook_preprocess_page_title() on a Bootstrap subtheme? I've just discovered that Drupal 8 Bootstrap theme doesn't implement all existent hooks.
So, for example, hook_theme_suggestions_page_alter() works, but
hook_theme_suggestions_node_alter() doesn't work.

I'm interested on hook_preprocess_page_title(&$variables) and I wonder if it's possible to incorporate this hook into my custom Bootstrap sub-theme. I have created the page-title.html.twig template and cleared the cache.

I saw https://drupal-bootstrap.org/api/bootstrap/docs!plugins!Preprocess.md/group/plugins_preprocess/8.x-3.x but it seems this is for extending an already existent hook in Bootstrap theme, not for adding a new one.

How do I add hook_preprocess_page_title() in a Bootstrap theme?

How do I add hook_preprocess_page_title() in a Bootstrap theme?

In your sub-theme's .theme file you add:

/*
 * Implements hook_preprocess_page_title()
 */
SUB_THEME_NAME_preprocess_page_title(&$variables) {
  // your logic goes here
}


What's the best practice to show a node's fields in different regions? In D7 we used to create a view for nodes, with each field having an own display. Each display creates a block to place in any region of the site. But of course, Views are SQL-heavy.

Now, Drupal 8 is all fancy. What's the Drupal 8 way of showing a node's fields in different regions of the page?

Edit: my current attempt is to create a custom module which provides a block for each specified field.

Not exactly sure why you want to have every single field as a separate block? That's pretty inefficient, if nothing else.

To have one or two additional blocks, you can use an Entity view block provided by ctools module. It will take the current node and display it in a certain view mode. Of course that will be painful to maintain if every field is separate, but I don't really see why you would want to do that?

In Drupal 7 I used to do exactly the same as Alex: Create views to place content in blocks. I found this thread looking for a way to make QuickEdit work.
Display Suite and ViewModes seems to be the answer.

This seems like the cleanest way to me: Using the Drupal 8 version of Display Suite, you can add fields from nodes to blocks.
Full instructions are on https://www.drupal.org/node/2754967.
This method saves creating a bunch of views, and allows inline editing.


Change max length of link field link text In order to modify the length of a file field description field I put the following line in settings.php:

$config['file.settings']['description']['length'] = 512;

Now I want to do the same for the link field. How can I change the max length of the link text (without patching the module)?

I think the problem is that FileWidget.php gets the length from the configuration

'#maxlength' => $config->get('description.length')

whereas it is hardcoded in LinkWidget.php:

'#maxlength' => 255

If you go for module then you can check Maxlength module.

  Maxlength allows you to set maximum length of any field on any form
  making use of the form API. This includes fields created using the UI.
  (Example: any text field on a node)

function your_module_field_widget_form_alter(&$element, FormStateInterface
$form_state, $context) {
if($element['uri']['#title']=='URL' && $element['title']['#title']=='Link
 text'){
$element['title']['#maxlength']=20;
 }

}


Displaying users who click the button I have 2 user roles in my Drupal 7 site 'A' and 'B' respectively:

users of role 'A' can create and publish content.
users of role 'A' can see content they created on their profile page. (For this purpose I created a block to display content and put it on user's page.)
users of role 'B' can not create content but they can view all published content.

Content in my case is an invitation to some event (ie "Who wants to play football on Friday?")

Each content has 'Participate' button which users of role 'B' can submit.

How can I display in 'A' users pages the names of 'B' users who want to participate in their event?
How can an 'A' user confirm participation of some 'B' users and dismiss the rest?

This is quite a complex task your planning – and it's hard to answer in just a few lines of text. I can basically just recommend you have a closer look at the mighty Rules module in combination with the Flag and the Entity reference module.

Here's just a vague suggestion / outline of how this could probably be done by combining the above modules:

Put a flag 'participate' on content type event users of role 'B' can use
Define a new content type 'participation' with checkbox/flag 'confirmed / dismissed' and reference the event and the user to it, editable by 'A' users
Make a rule that generates a new node of content type 'participation' and alerts users of role 'A' of a new request
Extend your profile pages' view with the referenced items of content type 'participation'

There is probably different ways to do this – most likely also easier ways than the one described above. And then there is also a more specific module 'Rules link event' that might fit your demands.


How can I change theme? I tried drush disable theme-name and afterwards drush enable theme-name, but it didn't work.

How do you change theme with Drush?

For Drush 9.5.2 and Drupal 8.6.5 I use the following:

drush theme:uninstall THEME_MACHINE_NAME
drush theme:enable THEME_MACHINE_NAME
drush config-set system.theme default THEME_MACHINE_NAME

drush dis and drush disable aren't anymore valid, in Drupal 8. Their Drupal 8 equivalent are the following commands.
drush pm-uninstall THEME_MACHINE_NAME
drush pm-uninstall MODULE_MACHINE_NAME


How can i sell files using ubercart I want to sell files as product using ubercart.

How to add files using product content type?

I want user to pay for the file first and then get file downloaded.

Is it possbile?Then how ??

Also i want each role called 'vendor' to have there own payment details and get paid from buyers. Is that possbile?

Thanks.

There is already module File downloads in the ubercart which allow user to sell file with the product.

Install the module File downloads from the module list.

Assigning directory to file donwload:

Go to Administration -> Store -> Configuration -> Product
In the File download settings section, set the path of the directory of the files and save the form.

Uploading files:
- Go to Administration -> Store -> Products -> View file downloads
- Upload files into directory (which you have configured in above step) using upload file action.

Adding files to product:

Edit your product and you will get the feature link in top of page. click on this link.
In feature form, you can add file download feature to the product and it will redirect you to form to assign file to product.
Select file name in File download text field. This is autocomplete field, so you need to configure correct files and save form.

When the user purchase product and pay the amount, it will send a link to user in his mail to download the files.

Regarding your second question, there is module Ubercart Marketplace.

  Ubercart Marketplace adds multiple seller support to the Ubercart
  module. It includes a series of modules that limit the access to
  Ubercart functions for sellers. Additional functionality is added to
  support this from both a marketplace seller's point of view and the
  store administrator's view. Sellers (with the proper access
  permissions) gain the ability to view their products, track and
  fulfill their orders, and monitor their sales reports. Store
  administrators can view seller reports based on seller order statuses
  and seller sales. Support is included for Paypal Mass Payments, with
  which an administrator can automatically pay his/her sellers for
  custom periods.

Kindly see that Ubercart marketplace is still in development version for Drupal 7, so may be there could be some issue in this module.

There are so many tutorials available, i found it by Googling

  Many stores online deal in digital goods. Known Ubercart sites are
  already selling music, photos, movies, and more using the core file
  download system. Large sites like Riff Trax and corporations like AOL
  are using this system to sell and distribute files. Props go to early
  community member CpILL for getting the ball rolling and torgosPizza
  for his extensive testing and use of the system. Its creation was and
  its improvement continues to be a community effort.

https://www.google.co.in/search?q=ubercart+file+downloads+&oq=ubercart+file+downloads

Selling Files

Setting Up Ubercart File Downloads


Form Rebuild by Ajax Call I have a form which is built using some data which is partially random. Unfortunately, at the first AJAX call (nothing has been submitted yet, neither AJAX, nor in the normal way) the form will be rebuilt so that all random inputs are lost. Is there any way to avoid it?

class AjaxTestForm extends FormBase {

  public function getFormId() {
    return 'ajax_text_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = $this->_getOptions();
    $form['select'] = [
      '#type' => 'select',
      '#title' => 'Select',
      '#options' => $options,
      '#ajax' => [
        'callback' => [$this, 'ajaxCallback'],
      ],
      '#empty_option' => 'Please select',
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Save',
    ];
    $form_state->set('ajaxoptions', $options);
    return $form;
  }

  private function _getOptions()
  {
    // Actually data from an external Controller
    // But those, too, are random
    $options = [
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
    ];
    return $options;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Do nothing
  }

  public function ajaxCallback($form, $form_state)
  {
    print_r($form_state->getValue('select'));
    echo "\n";
    print_r($form['select']['#options']);
    print_r($form_state->get('ajaxoptions'));
  }

}

When the user selects an option, in the Ajax callback (or Ajax submit, if I had one) I can't know which options were originally in the select box available.
Is there any way to preserve that information?

Get the value from:

$_temp_var_ = $form_state->getUserInput('_field_name_');

Use getUserInput() instead of getValue().

And then set the value to:

$form['_field_name_'] = $_temp_var_;


How do I add a link to a table row in a custom module? I am making a sortable table in a custom module. If I put the whole link as part of the row information, the URL does not come out right.

I tried the following code.

  array(
    'data'=>array(
      '#title' => $entry['name'],
      '#type' => 'link',
      '#url' => $entry['link_url'],
    )
  )

I also tried what suggested on https://www.drupal.org/node/745272,  which describes how to do it for Drupal 7.

I also tried this code.

 $rows[] = array(
   array(
     'data' => array(
       'name' => new FormattableMarkup('@name', [':link' => $entry['link_url'], '@name' => $entry['name']])
     )
   )
 );

Neither displays anything.

How do I achieve this for Drupal 8?

This worked for me

use Drupal\Component\Render\FormattableMarkup;
  $rows[] = array(

      array('data' => new FormattableMarkup('@name',
        [':link' => $entry['link_url'],
        '@name' => $entry['name']])
      ),

Take a look at the core Url class. Include it in your custom class:

use Drupal\Core\Url;

And then use something like this for your table data link:

'#url' => Url::fromUri($entry['link_url']),

There are a number of options for fromUrl() you may want to look at, and depending on the nature of your link_url values, there are other Url class methods that may be more appropriate.


Need module for notifications like privatemsg I am using Drupal7 and notification module. Now i want the notification like Private Message module. When any comment occurs or any post occurs at that time i want notification like "Private Message" module i.e. just like "3 new messages" i want same like this "3 new comments" etc..

Can you please inform me if there is any module exists or not

There is messaging_simple  table which stores message values.

See the column timeread this provides time when the message is read. The entries which have 0 value shows unread message.

You can apply sql query to find out rows with timeread 0 for logged in user and can get the count of unread messages.


Changing Column width of a table view (Drupal 7 Views 3) I have a view with 4 columns.  The first column, which contains a majority of the text is taking about about 80% of the width of the form and forcing the 2nd, 3rd, and 4th rows to wrap.  Problem is those columns have content that should not really be wrapped
for exmaple Tues 3pm - 5pm ends up looking like

Tues

3pm -

5pm

So rather than the columns adjust based on content, I'd like to manually set the width of the first column so that it leaves enough space for the others.  Or if need be manually set all the column widths.

Please understand I am totally lost in drupal and only have a small amount of css/php knowledge so please be as absolutely descriptive as possible.  I've found a bunch of examples in other areas but people have left out huge chunks of the code, or where it's supposed to go etc.  One place kept says "make changes to the css", not sure if it's normal but I have about 25 different css files in my drupal install, I had no idea WHAT css to make the change in.

Thanks in advance for any help!  This is a great community and I'm happy I went with Drupal because of it.

A more general approach than useful answers from @Michael Greisman @Neograph734 is to create some utility CSS classes that can be deployed on any View. That means if this requirement comes up when creating a new View, you already have a solution ready to deploy.

This is something that has been really helpful on a site where I have configuration responsibility but all template / CSS work is done by a contracted developer (who suggested this approach).

Create some CSS classes that can be used to fix column widths. In our case, using % values worked best, but do whatever makes sense for your site. Example:

.fix-width-20 {
width: 20%;
}
.fix-width-40 {
width: 40%;
}
.fix-width-50 {
width: 50%;
}

On a view with the table format, go to the 'Style settings' for the Field that is populating the column (or columns) where you want precise control of column width. Add the name of the CSS class that fixes the width. Example:

Simple solution;

go to your CSS folder located under your subthemme
find a file called  tables.css
locate code table.cols-4 {.....   width: 200px; }
CHANGE width: 200px; for width: 100%;
flush css caches.


How do I get the taxonomy term name of the current taxonomy term page.tpl.php? Im on d7. Im trying to get the taxonomy term name of the the taxonomy page that I am on. Since Im not on a "node" page, I can't get it by the $node->tid. What should I do?
Thanks.

Try..

http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_term_load/7

$term = taxonomy_term_load(arg(2));
$title = $term->name;

arg(2) should return the tid of the taxonomy page (taxonomy/term/tid).

Instead of using taxonomy_term_load() which is not working well every time, you can call:

function get_tag_name($tid) {
    $query = db_select('taxonomy_term_data', 't');
    $query
            ->condition('t.tid', $tid, '=')
            ->fields('t', array('tid', 'name'));
    $result = $query->execute();

    foreach ($result as $row) {
        return $row->name;
    }
}


Custom formatter for a multi-valued field I have a multi-valued image field and I'd like to use its delta value with the Custom Formatters module. What I want to do would be really simple with html+tokens if it were to work:

However, I don't see the option for the delta value available in the list of tokens available, and using that code would just end up with [node:field_image:0] and [node:field_image:1] being replaced as src=""

Could you please advice me on how to do this? I think I need to use php but I don't know how. Thank you very much!

here a sample for rendering (image) fields but you can easily access to other fields of entity:

$output = '';
foreach ($variables['#items'] as $item) {
  $output .= theme('file_link', array('file' => (object) $item));
}
return $output;

Another line example for manual image rendering:

$output .= '<img typeof="foaf:Image" src="'.image_style_url('YOUR_IMAGE_STYLE', $your_entity->your_field['und'][0]['uri']).'" alt="'.$your_entity->your_field['und'][0]['alt'].'"/>';


How can I programmatically display a block? I'm developing a site using Drupal 8 beta-14. I've created a view block of different terms and now I want to display it using code. How can I display it programatically?
I used to do it in Drupal 7 using this code but I'm confused about Drupal 8.

$block = module_invoke('block', 'block_view', '4');
$text_block = render($block['content']);

There are two types of blocks, and the method for rendering the two is a bit different:
Content Blocks
Content blocks are blocks that you create in the interface. They are much like nodes configurable data structures, with fields etc. If you want to render one of these, you can do what you would normally do with entities, load them and render them with the view builder:
$bid = ??? // Get the block id through config, SQL or some other means
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->
  getViewBuilder('block_content')->view($block);
return $render;

Plugin blocks
Blocks can also be plugin, defined in various modules. An example could be the breadcrumb block. If you want to render these, you will need to use the block plugin manager.
$block_manager = \Drupal::service('plugin.manager.block');
// You can hard code configuration or you load from settings.
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// Some blocks might implement access check.
$access_result = $plugin_block->access(\Drupal::currentUser());
// Return empty render array if user doesn't have access.
// $access_result can be boolean or an AccessResult class
if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
  // You might need to add some cache tags/contexts.
  return [];
}
$render = $plugin_block->build();
// In some cases, you need to add the cache tags/context depending on
// the block implemention. As it's possible to add the cache tags and
// contexts in the render method and in ::getCacheTags and
// ::getCacheContexts methods.
return $render;

Config entities
Shared for the two types are blocks, are that once you insert them into a region, you will create a config entity that has all of the settings for the block. In some cases it will be more useful handling config entities. Since the same block can be place in multiple regions with and with different configuration, it can get more tricky using the block config entities. The nice thing is that you might want to render a block with specific configuration, the bad thing is that config ids can change by messing with the interface, so the code might end up not working after letting users use the block interface.
$block = \Drupal\block\Entity\Block::load('config.id');
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);
return $render;

Based on my research, you could base the code from How to render a block programmatically in drupal 8. You could also change

return array('#markup' => \Drupal::service('renderer')->renderRoot($block_content));

into something as simple as:

$output .= \Drupal::service('renderer')->renderRoot($block_content);

to attach it for example into a page's return variable.


How can I use a token to display the node body summary? I'm trying to use a token to show the body summary of a node on Drupal 7.

The Replacement Patterns area gives the following information:

Body
[node:body:?]
The main body text of the node. The following properties may be appended to the token: value (Text), summary (Summary), format (Text format)

However, I don't understand what "append" means in this context.  I tried [node:body:summary] and [node:body:?summary], but neither works.  What am I supposed to do to get the summary?

Correct tokens are [node:body] and [node:summary].
Yoy should probably check http://drupal.org/node/1295524 if you experience problems with summary tag

If using a view you can format the body field using the formatter.


Adding class to form-item I've been trying to add a custom classname to a form-item to use as a 'marker' for theming with my css file.

I've been on stackexchange/overflow and several other sites and forums, including the Drupal documentation, but found no reason why it shouldn't work.

Official documentation state the use of the attribute tag like so:

'#attributes' => array('class' => 'myclass'),

But as seen in my example below, this doesn't work or give me errors.

Am I doing something wrong?

#attributes is not supported by item form elements.

  item

  Description: Generate a display-only form element allowing for an optional title and description.

  Note: since this is a read-only field, setting the #required property will do nothing except theme the form element to look as if it were actually required (i.e. by placing a red star next to the #title).

  Properties: #access, #after_build, #description, #element_validate, #parents, #post_render, #prefix, #pre_render, #required, #suffix, #theme, #title, #tree, #type, #value, #weight

You would then need to add a custom theme call such as:

function MYTHEME_preprocess_form_element(&$vars) {
  $vars['#attributes']['class'][] = 'another-class';
}

for the future, if you use the #attributes, wrap the class name(s) in an array like this:

'#attributes' => array('class' => array('myclass', 'otherclass')),


Show total amount of results for an exposed filter Found this answer, show amount of results for exposed filter and this answer.

However, my issue is that i'm trying find the total number of results after executing an exposed filter.

Views calc looks like it only returns the count of results from a single result not an exposed filter result. Or if i'm wrong please correct me.

Anyways, the question: How do you find the total number of results from an exposed filter?

Desired result:

Complete an exposed result form
return "x number of results found" as a block

I'm using Views 3.7 in Drupal 7 right now and finally found out you simply can add a result summary Global: Result summary to the header/footer.

By using the below code, you can do that, It will display like this Showing 1-10 of 130 results. on your result page.

Put this code in the Header and set the input filter as PHP code in your view.

<?php
global $pager_page_array, $pager_total_items, $pager_total;
$my_view = views_get_current_view();
$items_per_page = $my_view->pager['items_per_page'];
if ($pager_total[0] == 1) {
  echo t('Showing !pager_total_items results',
    array('!pager_total_items' => $pager_total_items[0])
  );
} else {
  $start = 1 + ($pager_page_array[0] * $items_per_page);
  $end = (1 + $pager_page_array[0]) * $items_per_page;
  if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
  echo t('Showing !start-!end of !pager_total_items results',
    array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0])
  );
}
?>


Know field type usage I need to know if a field type is used on a website in a content type. How can I know that with Drush or Drupal BO?

This should give you a list of the fields and types on your site.

drush field-info fields

Should output something like this

 Field name               Field type            Field bundle
 body                     text_with_summary     page,article
 field_image              image                 article
 field_category           entityreference       article
 field_name               text                  article


How do I include a term's additional fields on node display? With Drupal 6 there was Taxonomy Image to do this, but with the field goodness of Drupal 7 we can just add an imagefield to a certain vocabulary. This works quite well to output stuff with views, but I can't seem to find a way to show up the additional field on the node display.

In my case I simply have a vocabulary called countries that has an additional imagefield to hold the country's flag. When viewing a node that has assigned a country term I need the flag of the country to show up instead of its name.

Regards,
Daniel

I've not played with semantic fields before, but I can tell you that configuring a term's display is the same as configuring a nodes display. The administration for a vocabularies display can be found at Structure --> Taxonomy --> VOCAB_NAME --> Manage Display or the path

admin/structure/taxonomy/VOCAB_NAME/display

Again, same as nodes you can configure the labeling & formatting options from this area. However, the location to configure a node's display is Structure --> Content Types --> YOUR_TYPE --> Manage Display

These settings are used for Drupal's native output. Using views can bypass these settings depending on the view (fields) or can work together (full, default, teaser).


How do I get the translated node type of a node? I am trying to use the node type name in page.tpl.php for certain content types.
Actually, we have modified the article type and renamed it as News. It's name is News in all languages but in Spanish, where it is Noticias.

The translations are defined under Structure>Content Type>Article.

I tried to use this code :

if(!empty($node) && $node->type == 'article'):
  print node_type_get_name($node);
endif;

but the node type is always printed as News, even on Spanish pages.

I tried wrapping this in a t() , but no change.
Am I doing something wrong here ?
Thanks for your help !

I have edited html.tpl.php

I have added this code before starting the body tag in order to replace body css classes with translated

<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>

after this modification, you can search css class name in translate page and put a suitable translation for it.

so final html.tpl.php is

<?php

/**
 * @file
 * Default theme implementation to display the basic html structure of a single
 * Drupal page.
 *
 * Variables:
 * - $css: An array of CSS files for the current page.
 * - $language: (object) The language the site is being displayed in.
 *   $language->language contains its textual representation.
 *   $language->dir contains the language direction. It will either be 'ltr' or 'rtl'.
 * - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
 * - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
 * - $head_title: A modified version of the page title, for use in the TITLE
 *   tag.
 * - $head_title_array: (array) An associative array containing the string parts
 *   that were used to generate the $head_title variable, already prepared to be
 *   output as TITLE tag. The key/value pairs may contain one or more of the
 *   following, depending on conditions:
 *   - title: The title of the current page, if any.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site, if any, and if there is no title.
 * - $head: Markup for the HEAD section (including meta tags, keyword tags, and
 *   so on).
 * - $styles: Style tags necessary to import all CSS files for the page.
 * - $scripts: Script tags necessary to load the JavaScript files and settings
 *   for the page.
 * - $page_top: Initial markup from any modules that have altered the
 *   page. This variable should always be output first, before all other dynamic
 *   content.
 * - $page: The rendered page content.
 * - $page_bottom: Final closing markup from any modules that have altered the
 *   page. This variable should always be output last, after all other dynamic
 *   content.
 * - $classes String of classes that can be used to style contextually through
 *   CSS.
 *
 * @see template_preprocess()
 * @see template_preprocess_html()
 * @see template_process()
 *
 * @ingroup themeable
 */
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

I hope my post can help you.


What is the best way to write a cron that deletes a very large number old nodes and comments? I am writing a module the preferably implements a cron job, and possibly a queue, to run sql queries to delete old nodes and their comment. Approximately 20 Million nodes, and about 40 mil comments. I want to run pure mysql queries and bypass the drupal api (as much as I can), for performance reasons. I have already developed the relevant queries and would like to know what would be the best way I could implement this so it does not user Drupal api? This is on drupal 7 by the way.

I would never think running raw SQL queries is a good idea because that can mess up a lot of things such as site maps, search index, caches, etc.

it's just a node_delete() and shouldn't be much slower that deleting a bunch of rows in multiple tables.

Whatever that is, you will need to implement hook_cron and retrive nodes to be deleted from 'node' table.

If you run a node_delete you won't need to delete comments.

You can limit the number of nodes to delete in a single cron run using LIMIT  keyword.

Update:
You might want to have a look at Delete All module. and there is a patch (which I submitted) to use the Batch API to do the job. From my experience I know even the Batch API can't handle it (or you have to wait several days with the browser open).

You can just use hook_cron to load a bunch of nodes to be deleted, and then delete them in your preferred way (node_delete or raw SQL). Let the cron finish, and in the next run, it will grab some other nodes.
Just get your nodes from node table and limit it with a LIMIT.

If it were me, I'd create a menu callback function that does a db_query on your nodes.  Then write a cron job on your server that calls that URL.


Adding a reference to a bundle in a node I would appreciate suggestion for this common scenario in Drupal 8, which may be different to how I do it in Drupal 6. I don't want to do any programming.

I have two content types: (1) Articles (title, author, body) (2) Authors (First name, Surname, Biography).
Authors are not users.

When adding a new article, I want the option to select either (a) An existing author from a list, or (b) Add a new author to the list, and select it.

When displaying the article, I want to see the author's First Name and Surname, and optionally a Biography teaser, and then the body of the article.

Enable the Entity Reference module that is the part of drupal 8 core.
Create the two content types.

I have two content types: (1) Articles (title, author, body) (2)
Authors (First name, Surname, Biography). Authors are not users.
When adding a new article, I want the option to select either (a) An
existing author from a list, or (b) Add a new author to the list, and
select it.

Add a entity reference field in the Articles content type.
Go to Home Administration Structure(admin/structure/types) click on Manage fields in front of Article content type.Add a new field(Authors) and choose its field type to be Entity reference and after save, The field configuration screen will open.Choose "Type of item to reference" to Content. Then on the next screen choose the reference type(authors content type).

When displaying the article, I want to see the author's First Name and
Surname, and optionally a Biography teaser, and then the body of the
article.

There are several options to do so :
1)Load the authors entity in articles template and display its result like that.
2)Use the Display suite module which is still has alpha available.
3)Create the view block which displays the author information like you want to show.and embed this view in your node article template.
4)Go to Manage Display of that content type(admin/structure/types/manage/article/display) and use a separate display mode to do so.
5)etc....
I would suggest to use the Display suite because I love to use it as it made my life easier at many places.

This module: https://www.drupal.org/project/entityreference is the way to go in D7. D8 has only a dev release: https://www.drupal.org/node/1246440/release?api_version%5B%5D=7234, so it might be buggy.

For displaying the correct content of the author, you should use Display Suite: https://www.drupal.org/project/ds. Again, be carefull, D8 modules might be buggy.


Reducing Number of Fields in Content Type Context:

I have a product content type on Drupal 7 with >100 fields, and there are >7000 products, all with several revisions. Our client keeps requesting that we add and remove fields, which is quite painful and takes several tries to successfully complete due to mysql having a conniption.

The go-to strategy has been to increase the RAM on the server, but we are hitting a cost wall and this bothers me as a developer since we are just deferring dealing with the problem.

Comedy Option:

The majority of these fields are specifications which are never related, filtered or displayed outside of the detail view. Could I reasonably create a JSON product_spec field that contains all of these spec fields and write custom modules to display them on the detail/spec screens, allow editing through the API, and allow editing them on the admin interface?

Is there an existing module that does something similar? Would entitycache be a much more practical option?

This is really interesting and, whereas the suggestions in the other question are really good as pointed out by the comment above, I don't really think it's practical to give up on the Field UI for this (like mentioned in the other question).

Let me explain:

Creating a custom field is really easy, there's a good example in Panopoly Widgets for the dashboard widget, which has a custom field for the Spotlight widget.
Creating a custom entity isn't so bad either but creating every single field using Form API should be out of the question

The only plausible solution that I can think of would be to implement hook_field_storage_info() and create a new Field API storage backend that uses a better table configuration.

If you look at field_sql_storage.module in core, it's a pretty concise module that provides the one field per table storage backend, I'm sure with some hacking around you could create a new backend that uses one table per entity and stores each field in a new column there (kinda like D6 CCK with cardinality 1 fields).

You would have to be constantly altering the table schema whenever new fields are added (which should be fine). This might be the place to do it: hook_field_storage_create_field().

It's pretty theoretical but I think it'll work... the beauty of this approach is that you can still use Field UI for everything as usual.

Caveat: You're gonna have to figure out how to handle complex fields or multiple cardinality (hint: more columns?)

PS - Knowing of the frequent schema changes, you wanna make sure you have backups/concurrency for peace of mind.

Good luck and if you get this working I'd like to see it! :)

I would give the Dynamic Properties module a try.


Insert block above comments in node How to display block in node above comments. What i have tried is:
create region - regions[above_comments] = Above comments after in template.php i have added this to THEME_preprocess_node

$variables['above_comments'] = theme('blocks', 'above_comments');

and in my node.tpl.php i have added this below print render($content);

<?php if ($above_comments): ?>
   <?php print $above_comments; ?>
<?php endif ?>

Added my content to this region, but its still empty, dpm($variables['above_comments']) - - is empty.
What is wrong?

theme_blocks() was only available for Drupal 5 & 6, which is why your code isn't working.

The D7 equivalent is block_get_blocks_by_region(), e.g.:

$variables['above_comments'] = drupal_render(block_get_blocks_by_region('above_comments'));

See node.tpl.php

Check where it prints <?php print render($content['comments']); ?>

Just render your region before <?php print render($content['comments']); ?>


How can I stop Drupal from sending e-mails of any kind? I have a dev, staging, and live server workflow set up on Pantheon.  My site has a lot of rules that cause members to be e-mailed for various reasons.  I sometimes need to work on these on my dev/staging sites but I've realized that, since they have the live data, sometimes users will receive additional or duplicate e-mails when I'm working on something.

Is there any easy way to turn off all e-mailing capability (preferably automatically to prevent me from forgetting) on a dev/staging server?  Ideally, I'd like to disable e-mail via a custom module, since I already have steps in place for making sure a custom module is enabled on dev/staging.

As another, quicker, option, you can add the following lines to your site's settings.php file (if you have the Devel module installed, which you certainly should if this is a dev site).

$conf['mail_system'] = array(
  'default-system' => 'DevelMailLog',
);

That will replace the default mail system with Devel's development mail system, which writes emails to a file log rather than sending them to a recipient. By default the files are stored in temporary://devel-mails, but you can alter that by setting another variable, eg.

$conf['devel_debug_mail_directory'] = '/path/to/folder';

Enable SMTP Authentication Support module and you can directly turn off your SMTP Mail Server at admin/config/system/smtp.


Adding a background image for Omega subtheme I've created a custom sub-theme for Omega and I want to change the background of the body to a specific image. I've edited the global.css file in the css folder of my subtheme.

body {
    background-image:url("images/starbkg.png") repeat;
     }

I've also made sure that global.css was enabled.  If I add background-color:black to the code the background does change color but I haven't been able to change the background image. I figured just by editing the global.css file I should be able to change the background image. No matter how many times I've flushed the cache and reloaded the page, the background image still won't show up. I've even tried creating a preprocess file. In the preprocess folder of my theme.

<?php
/**
* Preprocess HTML.
*
* Implements hook_alpha_preprocess_html().
*/
function myth_preprocess_html(&$variables) {

  $variables['classes_array'][] = 'body';
}
?>

(myth is the name of my theme)

I don't need the background to re-size or change, I just want something that sits behind all the other areas on the page and is persistent across all the content.
When I inspect the page I find that

<body class="html front not-logged-in page-node omega-mediaqueries-processed alpha-  debug-processed responsive-layout-wide">

hasn't changed to indicate a background.
I've looked into various modules that I would like to avoid and I was hoping to find something relatively simple. I have managed to change the background on non-Omega based themes so I suspect there is something that Omega does that I'm missing.

Thanks in advance for your assistance.

You shouldn't need to do any of the preprocess stuff.  We recently had some problems getting things to apply via the global.css file - but we figured them out.

Here is the trick of it.  Even though you apply X in the global.css file, if Y is applied in one of the stock css files, and you don't turn off Y (via css in your global.css) - and Y in some way impacts X - X won't be active.

I recommend either Firefox and Firebug - or Chrome and "right click -> inspect" - and really scrutinize the DOM.

Also - regarding your image file - you might try specifying a full path.  We have had issues with relative paths.

I hope this helps.

Try this:

body {
  background-image:url("images/starbkg.png") !important;
}


What is the difference between the Workbench and Workflow modules? I use the Revisioning module to manage revisions of nodes on my Drupal 7 site.  I had been updating the site by myself, so Revisioning was sufficient; now, however, I will be adding some content editors to the project so I need to set up a more complex workflow.

I used to use the Workflow module on Drupal 6 and the Drupal 7 version has integration with Revisioning.  However, Workbench has been getting a lot of good press recently.

What are the significant differences between these two modules, Workbench and Workflow?

Workbench gives you an intuitive and friendly user interface to control content (nodes)transitions on a previously defined states on a role based access control means that every transition to the node from a state to a state for the role authorized to perform that transition, with the ability to create new transitions and states.

You won't get that feature unless you enabled the workbench moderation module.

Workbench access module allows you set sections, editors, roles (defined using a menu items or taxonomy terms) to work on the description above based upon the permission given for the role to work on workbench functionality which gives you a generic out of the box role based access control to previously define workflow to manage content publishing process.

Workbench media provides integration between media and the Workbench suite. It simplifies the pages content administrators need to visit in order to add media which makes workbench files
module useless and becomes depricated.

Workflow seems to be more powerful and provides you with one form to create and define workflows and manage states, transitions, assign roles, set labels for transitions and how states will be listed and logged read that awesome article

Besides have integration with many helpful modules may be used in your project in the future like og, rules, views and search_api due to the dependency on drupal entity system allows to set workflows defined to other entity types not limited to nodes.

Actions on each transition could be tied and notification created for users in concern like group members and admins or high level managers.

At the end each of the two modules have very good functionality that deserves showing respect to maintainers, Workbench focus on content closely to E-magazines and online news portals or forums, Workflow pay attention on the process thinking of workflows as business rules required and may be helpful in ERP, CRM and E-commerce like systems some how.

Finally close to scope of that question I found a very simple module provides ability to add custom publishing states with integration to rules and views, specify defined roles to transition nodes between states.

I hope that review helps you determine what is the best module for your project.

The Workbench module can achieve what the Workflow module does; plus it has a very powerful backend. I think this is the main difference.

If you need a complete backend for a workflow administration, it is better to use the Workbench module; if you need just a workflow use the Workflow module.


How to remove welcome to message? I changed the:

configuration: Site Name --> 'my site name'

But it shows in title bar like this:

  Welcome to 'my site name'

So, how can I remove the "Welcome to" in the title bar, so that the result would be just:

'my site name'

When I inspected the html I found like this:

Welcome to my stie name | my site name

But I wanted to be :

my site name

And I'm using zen base theme and zenophile sub-theme.

Try Page Title module and configure the Page title for Front Page.

Download & enable https://drupal.org/project/page_title module.
Configure Page Title from admin/config/search/page-title And change
the Frontpage.

if you want to remove for all your project so you can comment this line in node module.
in this address : Drupal core/modules/node/node.module
and comment line for default message.


I can see the changes I made (as an administrator) but as an anonymous user, I can't Have you had any problems like this before? I appreciate your help.

When I'm an admin and update a node (custom module), I can see the changes I made (as an administrator). However, when I'm an anonymous user, just to check the data, I can't see the changes I made. (note: I have flushed the site, it will work, but only when I run flush)

I thought it was something related with the permission, from a Custom module I created, but I'm not sure of that. I included a permission.yml file and gave full access. It didn't work.

find the attached images:

I had built the code in the Controller folder/file:
I have two public functions called retrieveArrayOne and retrieveArrayTwo. Each one has different data for me to query later (retrieving the data from these two functions).

public function mainviewlist() {
  $array1 = array($this->retrieveArrayTwo());
  $array2 = array($this->retrieveArrayOne());
  $retrieveData = array_merge($array1, $array2);
  $content = "

";
  foreach ($retrieveData as $key1 => $finalValues) {
    if ($key1 == 0) {
      foreach ($finalValues as $disCrop) {
        $content .= "";
        $content .= '' . $disCrop . '';
        $content .= "";
      }
    }
  }
  return array(
    '#type'     => 'markup',
    '#markup'   => $content,
    '#attached' => array(
      'library' => array(
        'modulename/modulename',

      ),
    ),
  );
}

Here is the function from the $array1 and array2. Both are similar.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'content-type-name');
$query->sort('title', 'ASC');
$entity = $query->execute();
$options = array();

foreach ($entity as $n) {
  $node = \Drupal\node\Entity\Node::load($n);
  $options[$node->id()] = $node->getTitle();
  $elementA[] = [//
    'nid'        => $node->get('nid')->value,
    'title'      => $node->get('title')->value,
    'body'       => $node->get('body')->value,
    'field_crop' => $node->get('field_crop')->value,
  ];
}

return $elementA;

OK, I found the problem.

In my routing file, I was missing:

  options:
    no_cache: TRUE

That fixed it.


“Illegal Choice has been detected” I want to prevent validation check on the field_abc ?
How can I prevent validation for a field_abc

  function test_mail_menu() {
         $items['test-mail-1'] = array(
            'page callback' => 'drupal_get_form',
            'page arguments' => array('test_mail1_form'),
            'type' => MENU_CALLBACK,
            'access arguments' => array('access content'),
          );

    return $items;
    }
    function test_mail1_form ($form,$form_state) {
      $form = array();
      $form['field_abc'] = array(
        '#type' => 'textfield',
        '#title' => t('ABC'),
        '#validated' => TRUE,
     );

      $form['submit-button'] = array(
        '#type' => 'button',
        '#title' => t('sub'),
      );

      $form['#submit'][] = 'test_mail1_submit';
      $form['#validate'][] = 'test_mail1_validate';
      return $form;
    }

    function test_mail1_submit($form,&$form_submit) {

    }

    function test_mail1_validate($form, &$form_state) {

      if (!(is_numeric($form_state['input']['field_abc']))) {

        form_set_error('field_abc','ERROR');

      }
    }

If you don't want to validate that field, then remove the following function

function test_mail1_validate($form, &$form_state) {

  if (!(is_numeric($form_state['input']['field_abc']))) {

    form_set_error('field_abc','ERROR');

  }
}

And remove the following line from test_mail1_form

$form['#validate'][] = 'test_mail1_validate';

Are you asking for validation. If so please use this code, else explain your question clearly

function test_mail1_form($form, &$form_state) {
  $form = array();
      $form['field_abc'] = array(
        '#type' => 'textfield',
        '#title' => t('ABC'),
     );

      $form['submit-button'] = array(
        '#type' => 'submit',
        '#value' => t('sub'),
      );

      $form['#submit'][] = 'test_mail1_submit';
  return $form;
}

function test_mail1_submit($form, &$form_state) {
print_r($form);
exit;
}


How do I obtain the result summary from within a form on the view page? I have a design requirement or ask that wants to have a search form at the top of a Views page look like the attached image.

So there is an exposed full text input, exposed sort by filters.

However, the result summary for the view would appear to need to go in the middle of the form.

Since this is on a View page, is there a way to get the current View and fetch its result summary within a hook_form_alter()?

However, the result summary for the view would appear to need to go in
  the middle of the form.

  Since this is on a View page, is there a way to get the current View
  and fetch its result summary within a hook_form_alter()?

Don't complicate your Drupal life, and just KISS.

I assume you already added the Result Summary to your View's header. So just:

style.css

.view-id-[your-id] .view-header {

  position: absolute;
  top: 70px;

}


Are user browser information and ip address available as tokens in Rules? I am sending an email to admin from contact form. In the email I want to send the user browser information like browser name and version and the user ip address. But I'm unable to see the tokens for these values?

I want the browser info and ip address for both logged-in and anonymous users.

Are these tokens available in the Rules module? Or I will have to create custom tokens?

Use [current-user:ip-address] token for IP address of the current user.

For browser related token you have generate it using token_generate API.

  function token_generate use to generates replacement values for a list of tokens.

if you want browser info them use this...

look like


Remove subject field from comments Is it possible to remove the subject field on comment forms?  I find it to be kind of useless and redundant, since the subject of the comment is usually the title of the article being read, at least for me anyway.

You can turn it off in the UI at admin/structure/types/manage/type-name with the "Allow comment title" checkbox:

//get comment by node id
$comment->nid = $nid;
//get form by form name
$form = drupal_get_form('comment_form', $comment);
//hide subject in form
hide($form['subject']);
//check comment form
print render($form);


Difference and relationship between View, Page, Panel and Mini Panel? I'm quite familiar with Views but for others, especially page, panel and mini panel introduced by the module, Panels. Can anyone provide some simple but elegant description between them?

Views are used to create lists of things.

One difficulty with Views, is that when used on their own, views tend to become fairly static. Let's say that you have a view that lists "Friends of user X". In your view, you must know define where to find user X. This will mostly be either a contextual filter, possibly using a relationship, but whatever configuration you have, it becomes a static part of the view. This leads us to Pages.

Pages provide the rest of your site with Context. Continuing on the example above, a Page can figure out how to find user X at run-time, and then feed that as an argument to other components, such as the friend view. This means you can re-use the same view, and all the rules that go with it, on both the same page more than once, but also across pages, and having it base it's results on different users every time.

If you want to show the browsing users friends, and my best friends friends, on the same page, you tell the current Page about those two contexts, use the same View twice, and give each instance of that View, a different context as argument.

A page on it's own however, doesn't have a visible interface, neither back- nor front-end, which is were Panels comes in.

Panels Provides a GUI on top of Panels, allowing you to configure Page manager, as well as adding further functionality to Pages, such as render caching.

Mini Panels Essentially embeds an "small" Panel rendering into another Panel. You can think of it as a very intelligent version of a block, capable of defining layouts, requiring parameters, and more.

Views: It is used to create custom queries. If you want to make a list of particular type of content, view is suitable.

Page: Page that you can use to create static pages. If you want to create a custom static page, for example like About us page. That page my be not reside in any particular content type or anything, but you just want to create a static page. Pages are using panels to alter the contents inside it.

Panels: Panels are using to define a custom layout for a particular page. Means, for example your theme have basic structure firstsidebar|Main content but you need one rightsidebar region only for a particular page. Then panels are useful. In panels you can define custom layout for a particular page. And you can assign block or any contenets to the various regions of that page without writing any single line of code by using panels, here you can see how we can use panels for altering node layout.


Inserting data to external DataBase i'm trying to insert data to a different data base that i created. I've read a lot in the forum, the support documents and other pages but i haven been able to figure it out the problem, can someone give me a hand? point me to a right direction?

first i modified the settings.php like this:

<?php
/** ORIGINAL DATA BASE CONNECTION
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpsw',
      'host' => 'dbhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
*/

/** DOUBLE DATA BASE CONNECTION  */
$databases = array();
$databases['default']['default'] = array(
   'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'dbpsw',
      'host' => 'dbhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
);
$databases['civilproconstru']['default'] = array(
   'database' => 'name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'datahost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
);
?>

And then in the module i'm creating i'm using this code: (i'm pasting the full module code, the insert is at the end, just in case the error is in the back)

<?php
/** START CONFIG MODULE
 * Implements hook_permission().
 */
function project_creator_permission() {
  return array(
    'access project_creator content' => array(
      'title' => t('Access content for the project_creator module'),
    )
  );
}

 /**
 * Agrega a lista de estructura hook_block_info().
 */
function project_creator_block_info() {
  $blocks['project_creator'] = array(
    // The name that will appear in the block list.
    'info' => t('Project Creator'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Agrega menu en toolbar para "role" contratante hook_menu().
 */
function project_creator_menu() {
  $items['admin/crear_proyecto'] = array(
    'title' => 'Crear Proyecto',
    'description' => 'Crear Proyecto',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('project_creator_insert'),
    'access callback' => 'project_creator_access',
  );

  return $items;
}

function project_creator_access() {
 global $user;
 if (in_array('contratante', array_values($user->roles))){
     return TRUE;
 }
}
 /**
 * END CONFIG MODULE.
 */

/** START PROJECT CREATOR FORM */

function project_creator_insert($form, &$form_state){

    $form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => 'p_name',
    '#size' => 15
    );

    $form['save'] = array(
    '#type' => 'submit',
    '#value' => 'save',
    '#submit' => array('project_creator_insert')
    );
    return $form;

db_set_active('civilproconstru'); /* OPEN DATA BASE*/
db_insert('project_info')
->fields(array(
'p_name' => $form_state['values']['p_name'],
))->execute();
drupal_set_message("succesfully saved");
db_set_active(); /*CLOSE DATA BASE*/

}
?>

At the end, it shows me the form but when i click save button it seems to be inserting the data but when i check the database it still empty. It doesnt give me any kind of errors on execution.
Thank u for the help...

You don't have any submit callback. You should do any process with the submitted data in a submit callback like that:

function project_creator_insert_submit($form, &$form_state) {
  db_set_active('civilproconstru'); /* OPEN DATA BASE*/
  db_insert('project_info')
    ->fields(array(
      'p_name' => $form_state['values']['p_name'],
    ))->execute();
  drupal_set_message("succesfully saved");
  db_set_active(); /*CLOSE DATA BASE*/
}

In the code you are giving submit callback but not writing insert code inside that function. You should write insert code in a function like this:

function project_creator_insert($form, &$form_state) {
      db_set_active('civilproconstru');
      db_insert('project_info')
         ->fields(array(
         'p_name' => $form_state['values']['p_name'],
          ))->execute();

      drupal_set_message("succesfully saved");`
      db_set_active();`
}


apply condition to pages created by user roles if(isset($node) && $node->type == 'page') {
}

In the above code, I need add one more condition, so that it get applied on those pages which was created by users having user role "EDITOR" Please help.

if(isset($node) && $node->type == 'page') {
  if($node->uid) {
    $node_author = user_load($node->uid);
    if(is_object($node_author)) {
      if(in_array("editor",$node_author->roles)) {
        // This is the condition to match the current node author belongs to editor role.
      }
    }
  }
}


How do I get the count of all messages in the inbox? How can I get the count of all the inbox messages, with the Private message module?

Below the inbox messages, I need to display the count of total messages, such as:

  10 of 55

_privatemsg_get_new_messages() is the function to get new messages in Drupal 5.

Is there any function to get the count of all messages in Drupal 6?

There is a privatemsg_unread_count() function in Drupal 7. If that doesn't work in Drupal 6, check the module file for the name of the function.

print privatemsg_unread_count($account = NULL);

;)

;)