Default values in tableselect I have a custom module that, among other things, shows the user of a certain role. I want some of the users in this tableselect, do already be checked and I have and arry with these uids.

Now, how do I chedk default values in my list? See code below:

$companies = 'mail1@test.org,test2@test.org';
$uids = array();
$comp_mail = explode(',', $companies);
foreach ($comp_mail as $mail) {
    $uids[] = db_query("SELECT uid FROM {users} WHERE mail = '$mail'")->fetchField();
}

$form['msg']['accounts'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => in_array($uids),
    '#empty' => 'no companies',
);

in_array() returns a boolean (and takes two arguments), whereas Drupal is expecting an array to be passed for the default value.

The default value array needs to be keyed by the same key used for the options array, so in this case uid. The value for each array element should be TRUE or FALSE, to mark the element as checked or unchecked respectively.

$uids[1] = TRUE;
$uids[2] = FALSE;
$uids[3] = TRUE;
// etc.

$form['msg']['accounts'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $uids,
  '#empty' => 'no companies',
);

EDIT

I haven't tested the following, but since your $uids array contains only the array keys you want checked, and a positive number is automatically cast to a boolean TRUE in PHP, you might get away converting your array in one step:

$uids = drupal_map_assoc($uids);

In looking at the code, the form api expects the default to be set with '#value', not '#default_value'.  I hope this helps someone else avoid the frustration I have experienced!

form.inc: line 3458

  if ($element['#multiple']) {
    $value = is_array($element['#value']) ? $element['#value'] : array();
  }

form.inc: line 3486

  $element[$key] = array(
    '#type' => 'checkbox',
    '#title' => $title,
    '#title_display' => 'invisible',
    '#return_value' => $key,
    '#default_value' => isset($value[$key]) ? $key : NULL,
    '#attributes' => $element['#attributes'],
  );


E-mail validation form api What is the best way to handle server side e-mail validation in the form API?
Can it be implemented somewhere inside part of the form described below or are there other options?

 $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
 );

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

 return $form;
}

Create a validation function for your form.  Here is an example using your form. For instance, say your form code is in a function called my_email:

<?php
function my_email() {
  $form = array();

  $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
  );

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

  return $form;
}

function my_email_validate($form, &$form_state) {
  // YOUR CUSTOM VALIDATION CODE GOES HERE
 if (!valid_email_address($mail)) {
   form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
   }
}

function my_email_submit($form, &$form_state) {
  // YOUR CUSTOM SUBMIT CODE GOES HERE
}
?>

This function will allow you to write custom code to determine if the values entered in your fields are valid or not.  You can also add a custom submit function for your form to execute custom code while the form is being submitted.

Read more about validating forms at Validating Forms, submitting forms at Submitting Forms or read the whole article for a better understanding of the Forms API: Form API Quickstart Guide

Email address can be validated with your form validate handler

If function your_form defines your form then default validate handler would be your_form_validate or otherwise you can also set it manually

 $form['#validate'] = array('callback_to_validate');

 function your_form_validate($form, $form_state){
   if(!filter_var($form_state['values']['mail'], FILTER_VALIDATE_EMAIL))
     form_set_error('email', t('Invalid Email Address'))
 }


How NOT to cache a hook_menu callback I wrote a callback in my hook_menu() implementation, wich won't work the way it is intended to because of caching. The callback just returns some text depending on a cookie. Something like that:

function _show_logoutpage(){
    if($_COOKIE['foo'] == true) {
        return 'foo';
    }
    else {
        return  'bar';
    }
}

The code is called after the user is logged out so I would say the user is anonymous. Problem is the the output is cached (since the last menu cache clear) so the logic won't work.
Any idea how to fix this in a simple way?

$GLOBALS['conf']['cache'] = FALSE;

See also module CacheExclude, here are some more details about it:

  This module provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.

That could be done using JavaScript (client side on page load), instead of PHP (server side on cache build).


Drush bootstrap level error Im running onto some issues with Drush. I worked with php 5.3 and after upgrading to 5.5, i ran into some issues and decided to downgrade my PHP version back to 5.3. Now im running into the issue that Drush isnt working anymore.

Command cache-clear needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment [error]
to run this command.
The drush command 'cc all' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                     [error]
Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured
database.

Drush was attempting to connect to :
  Drupal version    : 7.28
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : 127.0.0.1
  Database username : root
  Database name     : drupal_practice2
  Default theme     : garland
  Administration theme: garland
  PHP configuration :
  Drush version     : 4.5
  Drush configuration:
  Drush alias files :
  Drupal root       : /var/www/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

You can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line or $options['uri'] in your drushrc.php file.

Ive been searching on google for almost 3 days now and re-installing my computer would be a lot faster. I have lots of data so i dont want to re-install.

Someone that can help me with the solution?

Your problem is that Drush is running the PHP version that you have installed for your hosting environment (and Drush's own php.ini). You need to get Drush to run its own PHP that it installs with.

What host are you running on? If it is Windows then open a console and type set. That will show you the environment variables that you are using for your account. If there is a PHP variable in there, note it's contents and delete it by issuing the following command in the command windows: set PHP=

If that doesn't work set it back to what is was before. Any other platform I cannot help you with.

Also check this post: Modifying the PHP or PHP configuration that drush runs under

Before doing anything time-consuming just go to the root of the directory and then run the command again.

Run from here at Drush console: /var/www/drupal


How to override views-view-field.tpl.php in custom module? I am trying to override views-view-field.tpl.php in my custom module as suggested in override views-view-fields.tpl.php in custom module but looks like it's syntaxes are old.

My codes are like:

In mymodule.info

 ; $Id$

  name = My Module
  description = Create custom views template.
  package = Views
  dependencies[] = views
  core = 7.x

  files[] = mymodule.module
  files[] = includes/mymodule.views.inc

 ; Information added by drupal.org packaging script on 2011-07-21
  version = "7.x-4.1"
  core = "7.x"
  project = "mymodule"
  datestamp = "1311290520"

In mymodule.module

function mymodule_views_api() {
  return array(
   'api' => 3.0,
   'path' => drupal_get_path('module', 'mymodule') . '/includes',

   );
 }

function mymodule_theme($existing, $type, $theme, $path)
  {

   return array(
    'views_view_field__views__ticker' => array(
    'variables' => array('view' => NULL, 'options' => NULL,'row' =>NULL),
    'template' => 'views-view-field--views--ticker',
    'base hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'mymodule') . '/includes',

         ),
       );
    }

In /mymodule/includes/mymodule.views.inc

  function theme_views_view_field__views__ticker($vars) {

    $view = $vars['view'];
    $field = $vars['field'];
    $row = $vars['row'];

    return $vars['output'];
   }

  function template_preprocess_views_view_field__views__ticker(&$vars)
   {

    $vars['output'] = $vars['field']->advanced_render($vars['row']);
   }

My custom template file views-view-field--views--ticker.tpl.php in /mymodule/includes

 <?php print $output; ?>

Problem: it is not overriding views-view-field.tpl.php

I am using drupal version 7.41

You should add the template file on your module info file:

name = My Module
description = Create custom views template.
package = Views
dependencies[] = views
core = 7.x

files[] = mymodule.module
files[] = includes/mymodule.views.inc
files[] = includes/views-view-field--views--ticker.tpl.php

version = "7.x-4.1"
core = "7.x"
project = "mymodule"
datestamp = "1311290520"


filter criteria: current users role I am using views to show some published content. I would like to give users with the role preview the ability to see all content within the view – published and unpublished. So they can preview how the page would look like after publishing content. My thoughts: I need to add a filter-criteria:

Published (=Yes)
 OR
Current-User-Role (=preview)

Ideas?

edit #1: to make it easier, I could also allow to see the content for all authenticated users.

edit #2: I have about 15 views where I need the preview functionality. they have different structure (filter criteria, viewmode, context etc) that means I need to keep it flexible. means probably that I need to define a filter and validate the data in the template.php

As said in the comment: If you want to give user access to unpublished content you can have a look at view_unpublished

You can also try to use this in combination with the 'Content: Published or admin' filter, but I didn't have a change to try it.

A filter like you're describing can be a good addition to views, consider creating an issue for it.

You could write a custom module to implement

a new permission view unpublished content
check if the connected user has the permission to view the content if unpublished when processing the view

In your CUSTOM.module file :

/**
 * Implements hook_permission().
 */
function CUSTOM_permission() {
    return array(
    'view unpublish content' => array(
    'title' => t('View unpublished content'),
    ),
  );
}

/**
 * Implement hook_preprocess().
 */
function CUSTOM_preprocess(&$variables, $hook) {
    global $user;
    if ($hook == 'views_view_unformatted') {
        $view = $variables['view'];
        if ($view->name == 'THE_MACHINE_NAME_OF_YOUR_VIEW'){
            foreach ($variables['rows'] as $key => $row) {
                $result = $view->result[$key];
                $node = node_load($result->node_nid);
                if ( $node->status == '1' || ( user_access('view unpublish content') && $node->status == '0' ) ){
                    $variables['rows'][$key] = render(node_view($node, 'teaser')); // or render it full if you prefer
                }else{
                    unset($variables['rows'][$key]);
                }
            }
        }
    }
}

You install your CUSTOM module
Then you give this permission to your specific role
And set the view to display content without filter on node status

Hope that helps :)


inheriting fields from a base content type I need to create 10 content types which, apart from their specific fields, will have 4 common fields (e.g name, surname, email, age).

Since I'm using Features I could create the first and copy paste the definitions to the other 9 content types. The problem though is that if the specifications ever change and I need to add or change any of those common fields I'll still need to do repetitive work.

How should I solve this? Is there a module which allows the construction of a "base content type" from which other content types can inherit fields? Or should I just reuse fields?

The following modules don't seem to be active for D7:

http://drupal.org/project/field_inherit
http://drupal.org/project/bundle_inherit
http://drupal.org/project/inherit

Short answer: I would simple go with sharing these four fields across the content types that you have. This is boring and repetitive work, but I'm not aware of a well-established way to do it otherwise, so this is the safest bet in my opinion. This gained a bad reputation in D6 as it caused performance problems, but in D7 there is no difference.

Longer answer: I did try copy/pasting of features code at one point, it works, but is quite messy and carries a large risk of "getting it wrong" as it's not documented nor entirely obvious what code needs to be updated.

As Joe Beuckman suggests, creating a custom entity is one way of solving this as well. If you add your shared data columns as entity "properties" instead of fields, they will be shared across all bundles of that entity type. A core example of this is the "title" property on nodes. A lot of modules today work in a entity agnostic fashion, but it's important however to note that the entity API was far from finished in D7. There is no general way for example to handle "entity access" which may or may not be a problem.

Also, on the last approach, you may also want to take a look at the Entity Construction Kit (ECK) module. I haven't used it myself yet, but I believe it could be helpful in creating new entities.

What you are looking for is exactly Entities in Drupal 7. You can create an entity with your common fields, then create fieldable bundles for each of your subtypes.


Tableselect with dropdown per row I use a tableselect to output a list of terms and per row I want a drop down (select):

$header = array(
      'name' => array('data' => t('Name')),
      'weight' => array('data' => t('Weight')),
    );

    $options = array();

    foreach ($terms as $term) {
      $options[$term->tid] = array(
        'name' => array(
          'data' => array(
            '#title' => $term->name,
            '#type' => 'link',
            '#href' => sprintf('/taxonomy/term/%d', $term->tid),
          ),
        ),
        'weight' => array(
          'data' => array(
            '#type' => 'select',
            '#options' => range(1,25),
          ),
        ),
      );
    }

    $form['term_list']['list'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
    );

My problem is that I do not see the value of the drop down (select) when I debug.

function example_block_save($delta = '', $edit = array()) {
  debug($edit, null, true);
}

Here is what I get:

[term_list] => Array
        (
            [list] => Array
                (
                    [5] => 5
                    [4] => 0
                    [6] => 0
                )

        )

When I check the code I can see that the select has no name, I'm guessing that's why I don't see it in the debug.

give default value property to select element e.g select form element returns value if select has been checked

add this attribute

'#default_value'= 1;

to every select list and your data to select list must be an array with key and value

$element=array(
'#type'=>'select',
'#default_value'=>1,
'#options'=>array(
         0 => t('No'),
         1 => t('Yes'),
    )

);

maybe then you have to render this element array with theme_form_element to your data variable. sorry but i havent enough time to test this solution

I had the similar problem. I tried with the following element added to the array.

'#name' => 'status',

It should be like...

   'weight' => array(
      'data' => array(
        '#name' => 'weight',
        '#type' => 'select',
        '#options' => range(1,25),
      ),
    ),


Webform does not submit when a file field is added I have a single page webform with a bunch of fields (text field, radio buttons, etc) that works fine. As soon as I add a file upload field it stops working:

when submitted, the form returns with all the fields still filled in
there are no validation messages of any kind

I've littered webform.module with lines of print statements and it appears that webform_client_form_validate and webform_client_form_submit are never called at all. I suspect some module may be altering my form because it picks up the file field somehow.

All webform related modules have been disabled.

I suspect I'm having a similar problem this question describes: Webform does not submit, instead redirects to self . The suggested solutions are rather vague though, and I'm not sure how to proceed.

I discovered the issue: I had added a script to my theme to prevent double form submissions: a simple "if the submit button is clicked, disable submit buttons in the form" jquery script.

This script prevented the submit button of the field field from being activated at the same time the main submit button was pressed. This confused Drupal to a sufficient degree that nothing worked anymore.

I fixed it by wrapping the disabling of submit buttons in a window.setTimeout(function yada yada ... , 50).


Commerce checkout does not work when loading from AJAX In D7, I have a dropdown form field that has an #ajax attribute pointing to a callback function that triggers when the drop down value is selected. In the callback function, I load the current Commerce order and then the Commerce checkout form using:

$commerce_form = commerce_checkout_router($order);

I then render the checkout form and display in the template:

$commands[] = ajax_command_html('#checkout-section', '');
$commands[] = ajax_command_append('#checkout-section', render($commerce_form));

return array('#type' => 'ajax', '#commands' => $commands);

When I do that, it looks like my checkout form does not get properly bootstraped and I lose all the interactivity of the checkout form I've set up using hook_info's etc.

When I visit the checkout form without AJAX everything works well.

Do I need to somehow bootstrap Drupal Commerce inside AJAX callbacks if I want to use AJAX so all my hooks that customize the Commerce Checkout?

PS: I am doing a

require_once '../contrib/commerce/modules/checkout/includes/commerce_checkout.pages.inc';

inside the callback. Without this I get functions not defined errors on core Commerce functions. (The Drupal Commerce and all related modules are enabled and it only happens in the AJAX callbacks.)

Thank you

I had exactly the same Problem, i think this page should help you: Loading a form by ajax.

I have solved this problem, but I think its a little bit ugly. The Problem was that I have loaded the checkout form, but not the scripts which are necessary on the checkout page. So i have loaded the scripts from the checkout page, too. After that i have done a

Drupal.attachBehaviors();

So all scripts can attach there functionality to the checkout form.


How do I create a year-only drop-down field? How do I create a year-only drop-down field?

I want to create a Drupal 8 field that shows a year drop-down with 100 years to the current year.

The Year Only module provides this feature by defining a new field type.

.

It comes with a range configuration.

It produces the following result in the entity (node, ...) edit form. Configured with unlimited number of values in this example.

You can use Date module.

  This package contains both a flexible date/time field type Date field
  and a Date API that other modules can use.

When you add field you can choose what you want to show (day, month, year) and + and - from current year.


How do I add a dynamic Facebook like button to every node of a certain content type One very comfortable solution to that problem is provided by http://drupal.org/project/fblikebutton. Unfortunately the positioning of the button isn't flexible enough for my needs.

I want every single node of one certain content type to have a FB like button at its bottom, making the base+node-url like-able. Facebook provides some snippets for that. Since I know that loading many iframes makes the site load very slow, I'ld like to add the JavaScript snippet into the appropriate template file.

My questions now are, in what template file exactly would I inject the little snippets and how do I have to customise the url in the plugin to make it fetch the url of every single node dynamically?

Inside a template_preprocess_node() I have done:

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['full_url'] = url('node/' . $node->nid, array('absolute' => TRUE));
}

Then in my node.tpl.php, I have

<?php // http://developers.facebook.com/docs/reference/plugins/like/ ?>

<div class="fb-like" data-href="<?php print $full_url; ?>" data-send="true"
  data-layout="button_count" data-width="450" data-show-faces="false">

In my html.tpl.php, I will hardcode the JS include so that it is right after the body (so I am not at the mercy of render trees, preprocess, etc:

This is from a pretty specific use case on a recent site.  I am not 100% sure if I tested this with multiple nodes on a single page, as the site I did this on doesn't have pages like that.

Try Facebook Like Button Module

  Rather than having to manually copy/paste the Like this on Facebook
  code for each piece of content you (or your users) create, this module
  will automatically add that code to the end of each chosen node type.
  You are able to add a Like button which likes a given URL (static,
  e.g. your homepage) or/and put a dynamic Like button on your page to
  like the page you are actually visiting.

Also there is Facebook Share

  The Facebook Share module enables Drupal site administrators to add a
  Facebook Share button to selected content type nodes in their
  website(s).


Re-indexing of site stalled, & running cron won't advance I have a site recently moved from D6 to D7. The search in D7 was not finding nodes containing the search terms, so I began a re-index in the search settings. This has stalled at 11% of site (with 3570 items left to index), and running cron does nothing to advance the re-index.

The log messages show that when cron runs, it encounters this error:

  EntityMalformedException: Missing bundle property on entity of type
  comment. in entity_extract_ids() (line 7766 of
  /var/www/html/[domain]/includes/common.inc).

And this notice:

  Notice: Undefined variable: key in comment_prepare_thread() (line 901
  of /var/www/html/[domain]/modules/comment/comment.module).

Also, there are many instances of this notice, which is associated with use of the site, not cron:

  Undefined index: weblinks in custom_search_form_alter() (line 232 of
  /var/www/html/[domain]/sites/all/modules/custom_search/custom_search.module).

None of these seem to affect the function of the site, and it's not clear to me that they are actually related to the stalled re-indexing. But it's all I've got to go on at this point.

If anyone could give me some ideas for how to troubleshoot this, I'd very much appreciate it.

Thanks!

This problem was caused by discussion forum posts with a single comment from a user whose id was no longer in the user table (threads with more than one comment, even though one was from an invalid user id, did not cause the error).

The fix was to find comments with invalid user ids, then change those ids in the Comment table to 0.

This SQL query identified the problem user ids:

SELECT DISTINCT a.uid FROM comment a left join users b on a.uid = b.uid
WHERE b.uid IS NULL

With the problem user ids identified, you can either edit the table directly, or use UPDATE to change the column values.

With those values changed in the comment table, the re-indexing proceeded to 100% without a hitch.

If you have installed Drush in your root directory, then you can run the below command to begin a re-index in the search settings.

drush search-reindex

To rebuild the index immediately, instead of waiting for cron, please execute the below command.

drush search-reindex --immediate

This will bring upto 100% reindexing of a website.


Get pure SQL from Drupal::entityQuery Given the following code, how can I print the SQL that is generated?

$bundle='my_bundle_type';
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', $bundle);
$entity_ids = $query->execute();

What I have tried:

__toString() doesn't work
dpq($query) throws an error

With debug tag (devel module is mandatory) we can print the raw sql.

$query = \Drupal::entityQuery('foo')->condition('bar', 'xyz')->addTag('debug');
$ids = $query->execute();

Enable  Devel and Devel Kint modules then  just try

 kint ($query);


How to show all terms with are used in Content? I have Content type: Products. It has field (Brand) on taxonomy base.
I use Views and want to see list of terms (all brand names) wich are used in my materials on the Product type base. I understand that it is possible to chose Taxonomy as base for Views building, but I want to build View on Content base.

Is this in Drupal 6 or Drupal 7? In Drupal 7, you should create a content view, use fields, and then in the fields section and select the relevant content field. This should then display all the various options that are selected.

I found that necessary point is using the Aggregation option; it will give only unique terms. The main point is taking out the "Sorting by date" option.


WYSIWYG CKEditor config.js not being used? I've installed and configured the WYSIWYG module (latest dev) to use CKEditor, and I have downloaded the latest version of CKEditor (latest full release) to sites/all/libraries.  I'm able to use the editor.

I need to customize a few additional things, so I'm applying configuration changes to config.js in sites/all/libraries/ckeditor/config.js.  However, it seems like this file is not even being used or read at all.  I tested this hypothesis by adjusting the stock config.js as so:

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    config.allowedContent = true;
    alert('Hello!');
};

alert('World!');

Whenever I load the editor, I would expect to get either one or two alerts, one saying either Hello! or World! or both.  However, no alert windows are launched.

How does one customize the configuration of CKEditor when using the WYSIWYG module?

This took some research, but I found this article which describes how to do it.

The meat of the article is the following hook, which defines a custom config file:

<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function MODULENAME_wysiwyg_editor_settings_alter(&$settings, $context)
{
    // The $context variable contains information about the wysiwyg profile we're using
    // In this case we just need to check that the editor being used is ckeditor
    if ($context['profile']->editor == 'ckeditor')
    {

        // The $settings variable contains all the config options ckeditor uses.
        // The array keys correspond directly with any setting that can be applied
        // to CKEditor - as outlined in the CKEditor docs:
        // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
        // Another way to override configuration is to use your own configuration javascript
        // file. In this case, we're going to add our own configuration file that will
        // Hold our stylesSet customizations...
        $settings['customConfig'] = base_path() . drupal_get_path('module', 'MODULENAME') . '/ckeditor_custom_config.js';
    }
}

All you need to do is to edit /sites/all/modules/ckeditor/ckeditor.config.js instead of ckeditor/config.js file.


Views Template Field Rendering I have a view which is a block on a page and I want to style the view. I tried using the rewrite output however I ran into a problem with it removing the style="" tag. So I had to resort to a .tpl.php to modify the display as I please.

Currently I am using

$d = $view->result;

    // Loop through it
    foreach($d as $r) {
        // Get values
        $position = $r->_field_data['nid']['entity']->field_position['und']['0']['value'];

        $name = $r->_field_data['nid']['entity']->title;

        $image = file_create_url($r->_field_data['nid']['entity']->field_picture['und']['0']['uri']);

        $path = drupal_lookup_path('alias',"node/".$r->nid);

        print "

".$name."".$position."
";
    }

And as you see this is extremely ugly and I am dependent on 'und' not changing... which it does.

Is there another way to get the view field data besides having to go through the array and find it? I tried render() and that didn't work. I also tried using entity_metadata_wrapper('node', $view); and that didn't work (the fields where not attached to the array).

I can't figure out how to do it without the hacking code... Help!

There did not appear to be any way to do this easier, so I did it manually/hacky.


Adding an image base field to custom content entity consider the following situation: I have created a custom content entity with several base fields (string and string_long fields) and it works flawlessly. In addition I want the entity to hold an image field which I defined the same way I did with the other fields:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    …

    $form_options = array(
        'type' => 'string',
        'weight' => $key,
    );

    $view_options = array(
        'label' => 'hidden',
        'type' => 'string',
        'weight' => $key,
    );

    …

    $type = 'image';
    $settings = array();
    $form_options['type'] = 'image_image';
    $view_options['type'] = 'image_image';

    …

    $fields[$fieldname] = BaseFieldDefinition::create($type)
        ->setLabel(t($sections['labels'][$key]))
        ->setDescription(t($sections['descriptions'][$key]))
        ->setSettings($settings)
        ->setDisplayOptions('view', $view_options)
        ->setDisplayOptions('form', $form_options);
}

Now, why would I get the errors Notice: Undefined index: target_type in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::propertyDefinitions() (line 70 of core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php). and Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityManager->getDefinition() (line 256 of core/lib/Drupal/Core/Entity/EntityManager.php).?

Anyone has a hint?
Thank you in advance!

Looks like you need to specify the target_type.

It should get the default from FileItem::defaultStorageSettings(), I am not sure why that doesn't work.

Unrelated, but note that you should not call t() like that, as it makes it impossible for potx to extract translatable strings from your code. Also, watch out for https://www.drupal.org/node/2363099, you need to update it to use nt() then.

Edit: Turns out, the problem is that the code was using setSettings(), which is considered problematic because it replaces all existing settings, including defaults. Switching to setSetting() for specific settings should solve it.

You are using wrong formatter type, these is no "image_image" formatter so

$view_options['type'] = 'image_image';

should be

$view_options['type'] = 'image';

for more on how to get proper formatters ids look here
https://www.drupaldump.com/custom-entities-and-how-get-setdisplayoptions-types


deleting comments in bulk how can I delete all comments at once? I have seen how to do it with nodes and bulkdelete module, How to delete all nodes of a given content type?
but am looking at a similar solution for comments.

I am looking for a solution that does not leave any artifacts in the database. Is Views Bulk Operations the best solution?

AFAIK, VBO should be able to do the job, but I haven't tried it myself to delete comments.

Another way is to run some code (in a module or in Devel module's 'execute php' block) that gets a list of all queries from the db, builds an array of the comment IDs and passes that array to the comment_delete_multiple function. Note that this can take a while to complete (depending on server performance and the number of comments), so you may have work your way around that, for instance by using set_time_limit (http://php.net/manual/en/function.set-time-limit.php) or Drupal's batch API.

[update: see Chris Cohen's answer for example code based on this approach.]

Enable the PHP filter, and create a basic page with the following code:

<?php
  db_query("TRUNCATE TABLE {comment}");
  db_query("UPDATE {node_comment_statistics} SET comment_count = 0");
?>


Custom subdomains with htaccess I have page structures like:

example.com/aaa
example.com/aaa/a1
example.com/aaa/a2
example.com/bbb
example.com/bbb/b1
example.com/bbb/b2
example/com/ccc
........

What I need is instead example.com/xxx/x1, I want users to see xxx.example.com/x1

How can I achieve this with a rewrite rule? Or any other suggestions?

Subdomains module does not work for me because it doesnt allow custom subdomains.

I ended up creating a multisite structure.

Under sites folder I created a folder for each subdomain like: "aaa", "bbb",...
I created a settings.php inside each folder (starting with php tags, do not close it though):

include_once(dirname(dirname(__FILE__)) . "/default/settings.php");
$conf['site_frontpage'] = "aaa";

(It inherits the general settings.php file since I dont need very different settings per domain)

Created a sites.php file inside sites folder (again starting with php tags):

  $sites['aaa.example.com'] = 'aaa';

  $sites['bbb.example.com'] = 'bbb';

  .......

xxx.example.com IS a subdomain. It could be set as example.com/xxx/, or xxx.example.com, doesn't really matter. The point is, you are trying to achieve a subdomain structure. And you should be able to set subdomains.


How to use helper/private methods with a .module file? Let's say I use a hook with a lot of code inside. To improve readability and reusability I'd like to use helper/private methods. However, a Drupal .module file is not a class.

The idea is to split big methods from this file into more readable and reusable smaller methods.

What is the correct way to call helper/private methods from a Drupal .module file?

I always follow Symfony standards when it comes to helper functions. I normally have one module for developer-central stuff where I add a class under src/Utils for that and then call it everywhere I need it. Also in *.module or *.theme files.

web/modules/custom/my_module/src/Utils/MyHelperFunctions.php

namespace Drupal\my_module\Utils;

/**
 * Class MyHelperFunctions.
 */
class MyHelperFunctions {

  /**
   * Get current multisite directory name.
   *
   * @return string
   *   The basename of the matching multisite directory.
   */
  public function getMultisiteAlias() {

    $site_path = \Drupal::service('site.path');
    $site      = explode('/', $site_path);

    return $site[1];
  }

}

web/modules/themes/custom/my_theme/my_theme.theme

use Drupal\my_module\Utils\MyHelperFunctions;

/**
 * Implements template_preprocess_html().
 */
function my_theme_preprocess_html(&$variables) {

  // Add multisite body class.
  $site = MyHelperFunctions::getMultisiteAlias();

  $variables['attributes']['class'][] = 'site-' . $site;
}

@NoSssweat suggested that the more Drupalitically correct way to do this would be to create a service to let that method be called by other modules via dependency injection as well.

web/modules/custom/my_module/my_module.services.yml

services:
  my_module.helper_functions:
    class: Drupal\my_module\Utils\MyHelperFunctions

And then you wouldn't need to use the namespace anymore, but just can call the service wherever you want:

\Drupal::service('my_module.helper_functions')->getMultisiteAlias();

Read more: When should I create a service or a utility function?

Kwadz answer is the most cleanest so far, but here is another solution:
In our project we create classes for hooks:

/**
 * Implementation of hook xyz.
 */
function my_module_some_hook($arguments) {
  MyHookClass::create(\Drupal::getContainer())->myMethod($arguments);
}

In your class you just need to implement ContinaterInjectionInterface, and you are good to go. You can do anything in OO now, nevertheless you can also write unit tests for it if needed.


$content is only showing array text I have a theme, and for the life of me can't figure out why $content is rendering "array". I have switched to two other themes (framework and seven, and my new theme is based off of the framework theme that is working).

Here is an example of the theme code:

    <div <?php if ($left): ?>id="maincolright" <?php elseif ($right): ?>id="maincolleft" <?php else: ?>id="main" <?php endif; ?>class="nobg node-<?php print $node->nid; ?>">

    <?php if ($tabs): print '

'. $tabs .'
'; endif; ?>
    <?php if ($tabs2): print '
'. $tabs2 .'
'; endif; ?>
    <?php if ($tabs): print '
'; endif; ?>
    <?php if ($show_messages && $messages): print $messages; endif; ?>
    <?php print $help; ?>
    <?php print $content; ?>

So $content is there, and it should be fine, but on any pages I view, for instance, the page render, the edit page, or even my devel page, show only 'array'. See the screenshot:

Has anyone come across this?

print() is a command that doesn't work with arrays. print_r() will print out arrays for debugging but what you want is print render($content). Drupal uses large render arrays to output content, and they cannot be printed directly.

some other people are saying the modules have a bug where you have to use underscore instead of dash in the div definitions; try tabs_wrapper for example


How do I control what to publish as Facebook Instant Articles? I am using this Facebook Instant Articles module to integrate articles being published as Instant articles on Facebook. I have successfully tried to publish instant articles using the RSS Feed and Views modules.

When I look at the preview of the feed, the articles being added on the feed are all the articles recently published. This is not what I want. I checked the configuration, and I found out that I have to select each article.

Now, after doing this, I still can't filter out the articles which are selected to be published as instant articles. I tried adding a filter, but I can't add a Filter on my view. I have not yet added custom codes just via the administrative dashboard.

What I want is to freely filter out specific articles I want to publish as instant articles. In my case, the articles processed from the feed are the latest ones; if I edit an article to add it as instant article, it won't be shown.

Can someone help me here?

You can for example add a taxonomy to the articles and filter by that in the view.


Any easy way of implementing a mega menu? Im wondering if there is a easy way to implement the following dropdown menu(ive added a before hovering on a list item, and after):

If i had to do it right now, i would use a bootstrap dropdown, and basically have to create an entire module around making the paths to point in the right directions.

Do you guys know of any existing menus or any easier way of doing this?

thanks

(not a complete answer, but too much for a comment)

The main characteristic of a "mega menu" is that the contents of the menu are not limited to a simple list or tree of menu links. In your own example you have links with descriptions / subtitles, you have a picture, you have multiple columns that probably have nothing to do with a menu tree structure.

This is why you should use tools other than menu links system, for the contents of each megamenu box.

The first step is to forget you are creating a menu, and instead imagine you would be creating custom pages or blocks. How you create these, is a question for itself.

I have heard of someone who used nodes (possibly with pragraphs module), where every megamenu page is a node.

Another option would be to do something with panels.

The next question is how to anchor the megamenu contents to the actual menu items.

The person who used nodes for the megamenu pages (if I remember correctly) used a field where people specify the menu link path. Then when displaying the menu, the contents from the matching node are inserted as submenu.

You could also completely give up on the links being menu links, and instead just display node titles as toplevel items (sorted by whichever criterion), and then the rendered node as "submenus". This could be done with views, if you use a ul/li list as the style plugin (with custom classes) and a special view mode + layout for each item with its megamenu page. The special html you need would be in the custom layout.

Special attention should be given to multiple language versions, and possibly access checks for links. Maybe you use different paths in different languages?

This still requires some creativity in putting everything together.

But the main idea should be to look for solutions outside the menu links system.

EDIT:
I should add: You may want to think about doing something with ajax, to let the contents of the pages load after the main page contents. If I remember correctly, the person I talked to did this somehow, I just don't remember how exactly.

Credits to https://twitter.com/rachel_norfolk

You can check this https://megadrupal.com/project/md-megamenu
Very easy to use (I watch the video), the problem: it's not free


Is it always bad to pass a variable through t()? I have a little helper function for my hook_schema:

function _bbcmap_schema_asr_field($description) {
  return array(
    'type' => 'int',
    'unsigned' => TRUE,
    'size' => 'small', // Up to ~66k with MySQL (equivalent up to ~660.00 adjusted)
    'not null' => FALSE,
    'description' => t($description),
  );
}

And then I can use it something like:

/**
 * Implements hook_schema().
 */
function bbcmap_schema() {
  $schema['la_data'] = array(
    'fields' => array(
      ...
      'mort_asr_male' =>    _bbcmap_schema_asr_field('The age standardised mortality amongst men (fixed point with scale factor 1/100)'),
      'mort_asr_female' =>  _bbcmap_schema_asr_field('The age standardised mortality amongst women (fixed point with scale factor 1/100)'),
      'incid_asr_male' =>   _bbcmap_schema_asr_field('The age standardised incidence amongst men (fixed point with scale factor 1/100)'),
      'incid_asr_female' => _bbcmap_schema_asr_field('The age standardised incidence amongst women (fixed point with scale factor 1/100)'),
      ...
    ),
  );
}

I know that the guideline is not to pass variables through t() but this seems very similar to how the menu system passes the callback's title through t() (by default). Any comments on this being good or bad style?

The first argument of t() needs to be a literal string, which excludes:

variables, even the parameters of a function: t($description)
a concatenation of strings: t('If you want to add a link, click on' . 'this link.')
the value returned from a function:t(get_menu_description())
a constant: t(MYMODULE_MY_WIDGET_TITLE), t(MyClass::WIDGET_TITLE)

The reason is that, apart few specific hooks (e.g. hook_menu(), hook_perm(), hook_permission()), the string to translate are found from a script that scan the code of a module, looking for code such as t('This is an example.'); when it finds a value that depends from runtime, such as the value of a variable, the script is not able to understand which is the string that needs to be translated, as a variable could contain a different value each times the code gets executed.
In fact, http://localize.drupal.org reports a warning similar to the following one, in the case the argument for t() is not a literal string:

  The first parameter to t() should be a literal string. There should be no variables, concatenation, constants or other non-literal strings there. At t($filter['name']) in customfilter/customfilter.module on line 30.

If you are passing a dynamic value to t(), the script that extracts the strings to translate will not extract any value, in that case; the effect is the argument passed to t() will not be translated, which has the same effect of not using t() and using the dynamic output directly in the user interface. The only case for which the string will be translated is when the dynamic string is equal to the literal string a function passes to t(). Suppose, for example, that you have a library not thought for Drupal, which contains a function returning the name of the current month. With the following code, the value returned from that function would be translated.

function mymodule_calendar_page_title() {
  return t(Calendar::getCurrentMonth());
}

function mymodule_calendar_translations() {
  $translations = array(
    t('January'),
    t('February'),
    t('March'),
    t('April'),
    t('May'),
    t('June'),
    t('July'),
    t('August'),
    t('September'),
    t('October'),
    t('November'),
    t('December'),
  );
}

mymodule_calendar_translations() doesn't need to be called, nor to return any value. When the code of the module will be parsed, the call to t() will be found from the code that looks for literal strings passed to t().

Translating the description given for a database table and its fields is then not something that you should do, as none of the Drupal core modules do that; for example, node_schema() contains the following code:

function node_schema() {
  $schema['node'] = array(
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'vid' => array(
        'description' => 'The current {node_revision}.vid version identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      // …
    );
    // …
  );

  // …

  return $schema;
}

The report that caused the removal of the calls to t() from any Drupal core implementations of hook_schema() is Remove t() from all schema descriptions, which has been open by webchick (Drupal 7 co-maintainer).

  In Szeged, we had a big long discussion about t() around the schema descriptions and it was the consensus of everyone at the table (who included Dries) that t()s should be removed from these descriptions. They mess up things because t() isn't available that early, and people discussed that no one is going to take the time to translate technical descriptions of stuff, and it doesn't really make sense since we also don't translate code comments, for example.

The article about converting a Drupal 6 module to Drupal 7, has a dedicated paragraph: Schema descriptions are no longer translated.

It is, however, possible to use t() around a variable, and for it to work. I have done it with $title in page.tpl.php.

EDIT: Perhaps the strings don't get translated, but they can be used for string overrides.


Pulling #hashtags and displaying them on site I see that you can you the Activity Stream module to pull feeds from twitter and other social media sites. Well how could I pull a predefined #hashtag from ANY social meida site and present it in a feed on my drupal site.

Example:

Hashtag is #NCAABasketball

From bjones on Twitter:
Saw KU beat UNC's butt. Love #NCAABasketball

From jbean on Google+:
Love #NCAABasketball !

From ktghram on Instagram:

I'm at the game! "picture:" #NCAABasketball

It doesn't have to be like this, but would this be possible with out the user posting or tweeting to my account?

Any suggestions?

This is possible using the dev branches of a few modules put together:

feeds, >= 7.x-2.0-alpha8+56-dev

feeds_oauth, >= 7.x-1.0-beta3+2-dev

feeds_jsonpath_parser, >= 7.x-1.0-beta2+12-dev

I think there are a few other necessary modules you'll need to have installed, like oauth, ctools, feeds_ui.
One of the most important things is that you need to register an app at dev.twitter.com, and get an API key / secret. You put that into the feeds setup (admin/structure/feeds/FEED_NAME/settings/OAuthHTTPFetcher). When you setup your feed, you will want to choose the HTTP OAuth fetcher (oauth2 does not work) as the Fetcher type.

You create a new feed importer.

Additionally, you'll want to create a content type like "tweet" and add the fields you want to parse (like author, date, name, body, location).

Back in the feeds setup, setup your mapping, and create several jsonpath_parser maps to your respective fields. After that, click "settings" under JSONPath parser, to map your json contexts to your fields.

It should be something like this:

Context: $.statuses.*

Title: id_str

body: text

etc, etc, etc

Finally, once this is all setup, you can go to SITEURL.com/import
and input your search string, which will look like this:

https://api.twitter.com/1.1/search/tweets.json?q=%23HASHTAG

Anyway, I hope this is helpful. I realize that my answer could be better organized, but it should give the gist as to how this is done.

For my "tweet" content type, I have the default setup to be NOT published, so that I can moderate what actually shows up on my site.

One more caveat is that non UTF-8 strings (common in foreign languages for example) will error out and break your feed importer (which should run on cron automatically). Ideally you want to sanitize the input before writing it into the database anyway.

Here's the PHP you can put into a quick custom module to sanitize the input of the body field for example. You want to make sure your jsonpath_parser:ID matches the ID you setup in the node-processor settings.

<?php

/**
 * Implements hook_feeds_after_parse().
 */
function feeds_custom_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
//dpm($source); // look at source variables, requires devel
//dpm($result); // look at result variables, requires devel

  foreach ($result->items as $delta => $item) {
    $result->items[$delta]['jsonpath_parser:1'] = utf8_encode($item['jsonpath_parser:1']);
  }
}

You can use Twitter Pull module...

Project page says

  Twitter Pull is a small module, the only purpose of which is to allow
  super-easy embedding of public twitter data like: a user timeline or
  twitter search results by hashtag or a search term. The emphasis is on
  making these very specific tasks as easy and straightforward as
  possible. The purpose of the module is not to be an end-all solution
  for Twitter.


How to find out which form I want to alter I am adding a functionality to drupal commerce kickstart, which involves product display modification. There should be a lot of forms but I don't which one to alter and add my new object to the existed form. Any good idea? (There is almost no documentation about it)

The way I usually do it is just implement hook_form_alter and inside put dpm($form_id);. Reload the page and it will echo all form ID's. You should find the one you want pretty easily, you can then change the hook_form_alter into a hook_form_FORM_ID_alter.

You can find form_id by looking in the HTML of your site with firebug. Forms have their own id.
For example the form to add a article-node has this:

<form id="article-node-form" class="node-form node-article-form" accept-charset="UTF-8" method="post" action="/node/add/article" enctype="multipart/form-data">

So the form name is article-node-form. So check the html for the forms you want to alter for a  element.


How to configure a module after installation In my Drupal 6 website there are a bunch of modules. What is the simplest way to configure these modules? Also I am not sure of where their settings are? If there is a simple link that can be invoked to configure them , that will be awesome. In this case its the ctools module.
I am not looking for http://www.sitename.com/admin/by-module neither the Site building has the module.

Thanks

It's up to the module itself to present configuration options, and in Drupal 6 these can be a bit harder to find. I definitely recommend installing the admin_menu module (http://drupal.org/project/admin_menu), which can provide expanding drop-down menus to easily browse through all of the admin-side links.

With cTools specifically, the base 'Chaos tools' module won't do anything on its own, though it can be required by other contrib modules. If you're looking to use one of the bundled modules such as Stylizer or Page Manager, you'll need to enable and configure those modules separately.

[your website domain]/ctools_ajax_sample
You don't really configure that module, but you can see it in action after it's been activated.


Explanation of Content Types, Modules, and Views Attempting to structure a page within Drupal has led me down a convoluted path and I wanted to clarify the relationship between Drupal content types, modules and the views element before I ventured any further. My current understanding is that you can add content types via modules and with these various content types create a page that you can then format with views? What I am trying to do is create a basic page from various elements (pictures, tables, text, etc.) and format it through views. I realize this may be too generic to comment upon, but I would greatly appreciate any feedback!

Reading the Drupal documentation might be your best bet to get an in-depth explanation, but let me try to summarize each in my own words so you can hopefully get a basic foundation so you can understand better.

Content types - Content types are how you add any of your content to a website. For most of your general pages that have just regular text on them, nothing special, you would use the Basic Page content type to just create a basic web page, or node. However, say you were going to have an events feed on your website - you would want different fields for information that you would want to display. In this case, you would make a content type called Events (or whatever you would like), and then add fields to it (e.g., Event Title, Date, Time, Location, etc.). Now, Events would be listed as a content type you can use to add content. When you add content and choose Event to add, your fields will show up and you can add the information for an event, save that event, and repeat. Saving an event will bring you to the page for that event with all of that event's information (the formatting of which can be changed in the content type settings for that content type. Every event entry now has its own page displaying its information.

Views - Now, you have pages for events, but say you wanted to have a feed or list of events on a specific page. You would do this using a View. A view aggregates content (from one or more content types) into a display. So you would create a view, specify which fields from earlier you want to display (like maybe just event name and date) and then filter the content to just show content of type events. This view can be created as its own page, or you can create a block which you can then place in a region on another page. There is a lot of customization that Views allow you to do that isn't obvious in the beginning, but this is the gist of what views do.

Modules - Modules are jus "extras" for Drupal. Really, most of what you would need to create a basic site is already included. However, say you wanted to add some sort of fancy menu that Drupal can't already do. People have made modules to give you that capability. Say you wanted to create forms for people to fill out. There are modules for that.

If you want me to explain anything in more detail or if anything is not clear to you, feel free to ask and I can clarify or elaborate.

Take a look at the documentation here about Drupal

According to the documentation:

  A single web site could contain many types of content, such as
  informational pages, news items, polls, blog posts, real estate
  listings, etc. In Drupal, each item of content is called a node, and
  each node belongs to a single content type, which defines various
  default settings for nodes of that type, such as whether the node is
  published automatically and whether comments are permitted.

Views

  Although not all sites have Views, most sites include the Views module
  because of the excellent tools it provides. Views allows people to
  choose a list of nodes or other entities and present them as pages,
  blocks, RSS feeds, or other formats. The main use case for views is to
  create dynamically updating lists to content (for example, a listing
  of latest news), based on properties of that content (in the case of
  the news listing, that the content type is “News” and sorted by
  publication date).


How do I increase the length of a text-field with saved values? I have a multi-value text-field, projects. Its length is 4, and I would like to increase it to 255, but there are values saved in the database for that field.

How can I increase its length?

I got an answer from my friend as well. I would like to share his code here:

/**
 * Update field.
 */
function MODULE_update_8301() {
  $db = \Drupal::database();
  $field_name = 'field_MY_TEXT_FIELD';
  $table_prefixes = [
    'node',
    'node_revision'
  ];
  foreach ($table_prefixes as $table_prefix) {
    $db->schema()->changeField(
      "{$table_prefix}__{$field_name}",
      "{$field_name}_value",
      "{$field_name}_value",
      [
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ]
    );
  }

  $config = \Drupal::configFactory()->getEditable('field.storage.node.' . $field_name);
  $settings = $config->get('settings');
  $settings['max_length'] = 255;
  $config->set('settings', $settings);
  $config->save();
}

This is what I do. I would only use it to increase the length of a string. I have not tested, but assume that shortening a string will truncate data.

First, backup the database.

Then, edit the structure of the following tables (change yourfield to match the name of your field):

field_data_field_yourfield
field_revision_field_yourfield

Change the length of the field_data_field_yourfield_value field (VARCHAR) in both tables to the value you want. This allows the fields to hold more characters. But doesn't tell Drupal about the change in length.

Next, locate this table:

field_config

Find your field in the list and edit the data value. Look for a section like this:

s:10:"max_length";s:3:"100";

The length of the field in this example is 100. Change it to match the change you made earlier. If the number of characters changes (e.g. you increase it from 100 to 1000), change the s:3 value to reflect the new character count.

Flush all caches.

Edit the field on an entity type to which it is attached to verify that its length has changed.

Edit an entity with this field and verify that you are able to enter a value that is the new length.

That's all ....


Why are these filters producing different results? I'm working on a view, and I'm trying to apply a global filter (based on a field known as School Year). I've set up the contextual filter and I've added the block used to set the filter, but after setup, I receive completely different results - they have very few similarities, and the contextual filter narrows the view down to about 20% of the expected results.

On the other hand, when I do a standard Views filter using School Year (this time, determined locally), it gives all the expected results.

Basically, my confusion stems from this: if I'm trying to use the same data, stored either globally in a block or locally in a standard filter, why does that give me different results? How can I fix that?  What might I be missing?

EDIT: Despite my answer below this seems to only be working on one of my views - but even though I replicated the steps on another view, it provides the same unexpected behavior, so it only applies to half the views I need it to work on.

I actually figured it out - as it turned out, I missed a small but important detail. The original (local) filter included a relationship to a content type within the view, which was providing the correct results. When I went back to edit it, I'd noticed that when I created the contextual filter, I hadn't provided the relationship to the filter. Upon adding the relationship, everything worked out the way I'd intended - getting all the expected results. I still don't know why I was getting that unexpected behavior, though.


How to get Drupal 7 installed in a sub-folder / sub-directory properly? Currently i'm trying to installing a drupal 7 installation in a subfolder of another drupal public_html folder, but it doesnt seem to work. I am getting a redirect loop error in chrome. I already modified the .htaccess in the parent drupal installation to ignore the sub-folder and i also set the $base_url in the sub-directory drupal installation.

When I do this, provided I have a clean install, I do not modify anything. Take the domain http://diw.ifi.uio.no/, where Drupal is installed in both /www/, and /www/gruppe01/, etc. (I just create the number of subdomains I need for various experiments). My DocumentRoot is set to be /www/. I just direct my browser to http://diw.ifi.uio.no/ for the main site, and  http://diw.ifi.uio.no/gruppe01/ for the first subfolder site, etc. and it works - just like that.

Have you tried starting with a clean install and just install Drupal in the subfolder using the standard install procedure without changing .htaccess? (While not always necessary, I recommend that you have $base_url set correctly in the site's  settings.php.)

In my experience, Drupal works fine out of the box when installed in a subdirectory of a vhost. The fact that there is another Drupal in the DocumentRoot does not make this any different, as long as each Drupal site has its own .htaccess, it will not try to read the .htaccess in any superior directory.

Examples:

http://diw.ifi.uio.no/
http://diw.ifi.uio.no/gruppe01/

Okay after fiddling around some more. I finally solved the issue. First off the .htaccess in the subdirectory override's the root's .htaccess. so that means you dont have to worry about the root's .htaccess file

Therefore, anything that needs to be adjusted is within the subdirectory and you shouldn't need to touch anything in the root directory where you have your other drupal installed.

What i did was:

Comment out line 81 and line 82 of the subdirectory drupal installation .htaccess file.
Un-comment the line 94 RewriteBase to where you have your subdirectory drupal installed
Add in the $drupal_base variable in your sites/default/settings.php file to fix any file path issues you might have.

If this worked for you let me know! +1! :)


Drush sql-sync: Access denied; you need the SUPER privilege for this operation I am trying to use drush to move my live database down to my dev database. I am doing

drush sql-sync @live @devel --sanitize

However I get the error:

  "ERROR 1227 (42000) at line 1478250: Access denied; you need the SUPER privilege for this operation"

I think it is due to the views in the db from uc_views module, is there any way around this?

I also tried to do

drush sql-sync --skip-tables-key uc_views @live @devel --sanitize

where uc_views is an option declared in drushrc.php with an array of the db views from uc_views, but to no avail.
Here is my drushrc.php

$options['skip-tables']['uc_views'] = array('uc_order_products_pair_vw', 'uc_order_products_qty_vw', 'uc_order_products_user_vw');

I would actually prefer to copy the database views from uc_views rather than exclude them if that is possible.

The user defined in settings.php on one or both sides of the sync lacks the SUPER privilege on the database.

Log in as the mysql root user and do

GRANT SUPER ON [db_name] TO '[username]'@'localhost' IDENTIFIED BY '[password]';

If you are security-conscious (as you should be), it's worth taking the following into account:

  Do not grant the PROCESS or SUPER privilege to nonadministrative users. The output of mysqladmin processlist and SHOW PROCESSLIST shows the text of any statements currently being executed, so any user who is permitted to see the server process list might be able to see statements issued by other users such as UPDATE user SET password=PASSWORD('not_secure').

use same username in both the DB servers. take the dump using the same user privileges. this will fix your issue. use mysql -h  option while taking dump.


Create new content type on hook_install Can someone show me a proper example of how to create a new content type in a module's hook_install method?

I'd also like to know if/what I should do during hook_uninstall to clean up my mess; I read there is some debate about simply removing the content.

I haven't been able to find an example of the proper method of accomplishing this task, any help would be appreciated!

One of the best ways to keep this information in code is to use features. Feaures can put into code:

Content types
CCK fields
Permissions
Roles

The list goes on.

One nice feature about features is the drush integration

drush features will give you a list of all features on the site, and their status
drush features revert all will revert all features back to what is in code (really handy for running after deployments)

Help this helps

I did this in the MySpace Sync module.
I remember piecing that together from various sources, but I don't remember what all the sources were. You can browse the git repository there to see what I did, but it's basically an export of each content type with CCK's Content Copy module on install, and then deleting all nodes before deleting the content type on uninstall.


How to rename Sticky at top of lists? I am using Drupal 8 theme and i am wondering is there any way to change the phrase Sticky at top of lists which appears when creating new posts, to something different like Appear in Search Results or Trending?

In a custom Drupal module do something like:

function sfusd_scheduler_form_alter(&$form, $form_state, $form_id)
{
    // Let's change sticky at top of lists to client preferred verbiage
    $form['sticky']['widget']['value']['#title'] = 'Pinned to top of announcement list';
}

I found a not so clean way if you're still looking for this.

in the following file: \core\modules\node\src\Entity\Node.php on line 414(for me)

$fields['sticky'] = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Sticky at top of lists'))
  ->setRevisionable(TRUE)
  ->setTranslatable(TRUE)
  ->setDefaultValue(FALSE)
  ->setDisplayOptions('form', array(
    'type' => 'boolean_checkbox',
    'settings' => array(
      'display_label' => TRUE,
    ),
    'weight' => 16,
  ))
  ->setDisplayConfigurable('form', TRUE);

Change the setLabel value and clear your cache, and the text will be changed. if someone has a neater way of doing this please correct my answer.

Since this is in core i would recommend making a text file and adding the line you replaced and give some extra info because with a drupal update you will have to change this again.


How to clear the a block cache programmically I have a custom block that display some information from a custom configuration form.  I want the block to be cached, however, I want the block cache to be cleared every time I save the form.
I would like to do this in the submitForm function.  How do I go about and do this?

When displaying information from a config object add it also as cache dependency to the render array.
For example in a preprocess hook:
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');
  $variables['some_field'] = [
    '#markup' => $config_value,
  ];
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);

See How to clear cache for config entity after making changes?
You don't need to change form submit because saving a config object automatically invalidates cache entries having this cache dependency (cache tag).

Another example based on the block code from your answer and using a different method to add the cache tag:
  /**
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'uw_cbl_special_alert.settings';
  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config(static::SETTINGS);
    return [
      '#markup' => $config->get('message'),
      '#cache' => [
        'tags' => $config->getCacheTags(),
      ],
    ];
  }

Access caching
As asked in the comments, you can add cache dependencies to access results as well:
AccessResult::allowed()->addCacheableDependency($config)
AccessResult::forbidden()->addCacheableDependency($config)

Ok I believe I figured it out.  This works for me.
use Drupal\Core\Cache\Cache;
class ConfigurationForm extends ConfigFormBase {
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Invalidate block cache.
    Cache::invalidateTags(['config:block.block.{block_id_tag}']);
  }
}

I had to search the cachetags table in the database to find the block id tag.
In my case my custom block id in the annotation was uw_cbl_special_alert but the block id tag was specialalert
In case you are interested, code snippet from custom block
  /**
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'uw_cbl_special_alert.settings';
  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config(static::SETTINGS);
    // Turn caching off as this is a special message and show never be cached.
    return [
      '#markup' => $config->get('message'),
    ];
  }


How do you print View fields on Twig? I have a view and added the title as a field.
For example: How do I print the title?

In Drupal 7 it was as simple as
views-view-fields--[viewname].tpl.php
<?php print $fields["title"]->content; ?>

How do we do this in Drupal 8?
I have created views-view-fields--[viewname].html.twig
I thought it might be {{ fields.title }} but I get the classic error message like so:

The website encountered an unexpected error. Please try again later.

I then tried {{ field.title }}, {{ title }} and {{ content.title }} but nothing prints.

After eating dinner, washing the dishes, playing around with it and reading the comments in views-view-fields.html.twig located in core\modules\views\templates

/**
 * @file
 * Theme override to display all the fields in a row.
 *
 * Available variables:
 * - view: The view in use.
 * - fields: A list of fields, each one contains:
 *   - content: The output of the field.
 *   - raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - class: The safe class ID to use.
 *   - handler: The Views field handler controlling this field.
 *   - inline: Whether or not the field should be inline.
 *   - wrapper_element: An HTML element for a wrapper.
 *   - wrapper_attributes: List of attributes for wrapper element.
 *   - separator: An optional separator that may appear before a field.
 *   - label: The field's label text.
 *   - label_element: An HTML element for a label wrapper.
 *   - label_attributes: List of attributes for label wrapper.
 *   - label_suffix: Colon after the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 *   - has_label_colon: A boolean indicating whether to display a colon after
 *     the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 * - row: The raw result from the query, with all data it fetched.
 *
 * @see template_preprocess_views_view_fields()
 */

{{ fields.title.content }} worked for me. In hindsight it's very similar to the D7 code, duh, lol.

For other fields:

{{ fields.machine_name.content }} What's the machine name? You can find them under the Machine Name column in the Manage Fields of your content type or block.

An easier way to do this is to install HTML Field Formatter

Then, go to your field display settings and pick the new HTML formatter. It works with Views in D8, too


Using IN clause in db_query I can't figure out how to add an IN clause in my query, using placeholders.

I'd want it to be something like:

$nids = array(1, 2, 3);
$result = db_query('SELECT * FROM {node} WHERE nid IN :nids', array(':nids' => $nids));

Can't find any documentation on this simple task. What's the proper way to achieve this?

You are missing the braces.

Try this:

$nids = array(1, 2, 3);
$result = db_query('SELECT * FROM {node} WHERE nid IN (:nids)', array(':nids' => $nids));

For more information, see http://drupal.org/node/310072, especially the chapter on Placeholder arrays:

  Placeholder arrays

  Drupal's database layer includes an extra feature of placeholders. If the value passed in for a placeholder is an array, it will be automatically expanded into a comma separated list as will the corresponding placeholder. That means developers do not need to worry about counting how many placeholders they will need.

  An example should make this behavior clearer:

<?php
// This code:
db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144));

// Will get turned into this prepared statement equivalent automatically:
db_query("SELECT * FROM {node} WHERE nid IN (:nids_1, :nids_2, :nids_3)", array(
  ':nids_1' => 13,
  ':nids_2' => 42,
  ':nids_3' => 144,
));

// Which is equivalent to the following literal query:
db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)");
?>

Drupal 8 update.

Also valid.

$nids = db_query("SELECT nid FROM node_field_data WHERE nid IN (:nids[]) AND status = 1", [
  ':nids[]' => $nids
])->fetchCol();


Sidenotes / Inline notes on nodes I was wondering, is there already a module making it possible to make inline or sidenotes/comments inside the content of a node. A good example is the notes you can add in Google Docs.

Would be great for editorial purposes!

If I am not mistaken, it seems you want to have something like "private comments" on a node. You can find some information in the following question: How to have separate private comments for nodes apart from the general comments?

It mentions the Reply module, which is still in alpha. There might be other similar modules.

Hope it helps,


Non-static method view::load_views() should not be called statically with VIEWS When I copied my Drupal 6 web site to another server with a higher version ofPHP, I get this problem on all pages that have views:

strict warning: Non-static method view::load_views() should not be called statically in C:\xampp\htdocs\sites\all\modules\views\views.module on line 864.
strict warning: Non-static method view::db_objects() should not be called statically in C:\xampp\htdocs\sites\all\modules\views\includes\view.inc on line 1417.
strict warning: Declaration of calendar_plugin_display_page::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_page.inc on line 297.
strict warning: Declaration of calendar_plugin_display_page::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_page.inc on line 297.
strict warning: Declaration of calendar_plugin_display_block::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_block.inc on line 78.
strict warning: Declaration of calendar_plugin_display_attachment::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_attachment.inc on line 242.
strict warning: Declaration of calendar_plugin_display_attachment::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_attachment.inc on line 242.
strict warning: Declaration of calendar_plugin_display_ical::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\calendar_ical\calendar_plugin_display_ical.inc on line 217.
strict warning: Declaration of views_content_plugin_display_panel_pane::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\ctools\views_content\plugins\views\views_content_plugin_display_panel_pane.inc on line 40

These errors, at least those coming from Views, does not really have a proper solution, because the versions of Views and Calendar that cause them, are no longer being updated.

Views 2 is officially not being updated anymore, and I doubt anything but serious security problems is going to change that. Calendar could potentially have the problem fixed, but this is also a module with a great deal of issues, and for an old version, I simply wouldn't expect these problems to be prioritized enough to get fixed.

Your basic options:

Upgrade to Views 3, and the corresponding Calendar version.
Disable E_STRICT error reporting.
Simply accept that the errors are there.

A more sophisticated and perhaps better solution would be to locate the relevant patches in the issue queues, and apply them in your drush make file.

goto

administer -> settings -> error handling

set: Error reporting: to write errors to the log


Can drush show list all available modules? With yum you can do yum list available ..., and know the name of the package you want to install.

For example, there is the Mime Mail module in Drupal. What name should I use with drush dl, mime_mail, or mimemail?

So does drush have something like yum list available?

No, drush can't do that.

Why should it when you can see the entire list yourself on drupal.org.


Why can't i get simple form theming to work? I've got this implementation of hook_theme in a theme :

function uncoated_theme($existing, $type, $theme, $path) {

  return array(
    'uncoated_user_register_form' => array(
      'render element' => 'element',
    ),
  );

}

Furthermore, I've got the following function:

function uncoated_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = array('uncoated_user_register_form');
}

function theme_uncoated_user_register_form($element) {
  return '

";
}

However, the function theme_uncoated_user_register_form is never invoked. I've also tried to replace $form['#theme'] with $form['#theme_wrapper'] to see if I could at least wrap the form in additional markup; but that does not work either.

I can't really see what I'm doing wrong? Drupal seems to be totally ignoring the theme function I'm trying to run the form through.

I think it's the simplest of things...

$form['#theme'] needs to be a string, not an array, so change

$form['#theme'] = array('uncoated_user_register_form');

to

$form['#theme'] = 'uncoated_user_register_form';

uncoated_form_user_register_form_alter -> hook_form_user_register_form_alter doesn't seem right. It looks like you're trying to alter the registration form, which is user_register_form and not form_user_register_form. I'm just guessing but it looks like it should be uncoated_user_register_form_alter. So it's not really a case of Drupal ignoring your theming function, you actually wrote a wrong name for the alter function and that never gets called, hence the theme never gets applied. Also specific form alters don't take parameter $form_id. If you're having trouble with form id's and naming correct hooks, try using the normal hook_form_alter which takes the $form_id as the 3rd parameter, and check it against user_register_form to apply the theme.


Drupal Commerce - Update profile on order without cloning? I understand the reasoning behind preserving integrity of data for existing orders tied to profiles, however...

I have a page where the user can edit the order contents and change their billing or delivery information. Instead of create a new profile, I would like to save the data directly to the order being viewed. I don't want it to affect new orders created later, either.

How can I do this? It would seem that every time commerce_customer_profile_save is called, a brand new profile is created.

This isn't a standard commerce workflow, but most of the fundamentals are there. A customer can have many open orders at any given time, and I want the flexibility for them to change the delivery address ON a specific order and save it for that order only. Someone out there has to have done this I would believe.

How about something like this leveraging Drupal's Entity API:

//assume we retrieved the $order_id via a page callback argument or something similar
$my_order = entity_load('commerce_order', array($order_id));

$billing_profile_id = $my_order[$order_id]->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'];
$billing_profile = entity_load('commerce_customer_profile', array($billing_profile_id));

// **replace this comment with PHP logic to update the profile values**

//save our customer profile object using the updated values from logic above
$success = entity_save('commerce_customer_profile', $billing_profile[$billing_profile_id]);

This allows us to directly edit the customer profile object associated with a particular order, and leaves the rest of the profiles unaffected.


Webform with Content Access module not allowing access for the authenticated user role I've run in to an interesting problem that I've not been able to solve yet.

I've got a webform that is restricted to only be able to be accessed by users with a certain role, called "member".

But upon testing I see that users with this 'member' role are not allowed to access the webform unless I have the content access per node allow for anonymous users to access it as well. When I allow "anonymous" access to the webform,  I can actually get it to come up for the member role.

When a logged in "member" tries to access the webform I'm getting the "accessed denied" page.

On the actual form itself under webform > Form  settings I've got the "submission access" set to allow my "member" role, but not anonymous users.

I've looked at the general user permissions too, and everything seems to be in place:

checked: view published content
checked: Access own webform results
checked: access own webform submissions

I've enabled access control on the webform content type itself, and allowed anonymous as well as authenticated (and "member") access to all webforms generally.

I'm using the Content Access module to attempt to restrict access to this particular node/form to authenticated "members". Both authenticated and member roles are checked so as to allow access.

That role is assigned upon a user completing their checkout, and I've double-checked to make sure it's appropriately assigned and it's in place. This part works fine.

I cannot have this webform open for anonymous users.

Any ideas as to what's keeping this node from being able to be accessed?

I did have a similar issue, using Content Access module and getting Access Denied in a Role I created. My problem was that my Role did not have the "View Published Content" permission enabled. After enabling it, it works. But thanks for the detail explanation, it helped solve my issue.

Under submission access, there is a Roles that can submit this form checkbox. I used that and it worked.


Create a form for editing a single field of an entity I need to find a way for users just to edit a specific node field. We have a quite large content type and in a review process we would like some fields of a node to be editable for the revisioning user and some not. To avoid that the revisioning user needs to scroll through a large node form it would be very handy if he/ she would find a link on node detail page close to the text of the field where he/ she is pointed to a form just showing the field.

I found "Editable Fields" and "Quickedit" module which work not so well in our project due to some JavaScript conflicts. Additionally they do not really meet our needs as our main aim is not to make nodes editable on detail page. We just want to show a reduced form to the user for one specific field.

Does anyone has a solution how to create such a form? I think of something like calling the path "custom-form/[NID]/[REVISION_ID]/[FIELD_NAME]" which is connected to a page callback which renders a form for field [FIELD_NAME] in node [NID] of the corresponding revision version and validating and saving the input respecting the field's widget settings.

You can install the Field Permissions module.


Drupal 7 Apache solr - how to index pages content instead of nodes content I have a drupal 7 website with pages that include multiple nodes and I use Apache Solr as search module. It works but the results are very messy.

This is a page structure exemple:

As you can see, I have multiple nodes defined on my page. I'd like the indexer handles the content as page content but not like node content. In other words, I don't want the indexer handles this page as an addition of nodes but like an unique content.

In this case, I'd like to get a page URL as result but NOT multiple node URLs.

I hope it's clear enough.
Thanks

If I get you right, you don't want to show nodes in search results which are only used to be referenced to from another node, correct?

First of all, you need to define which Content Types should be indexed by SOLR. For this go to your SOLR settings page and untick all Content Types you don't want to show up in your search results.

After this done, I would highly recommend you to install the Display Suite module. This Module allows you to create different View-Modes. Built in and among many others which are available when you enable them, is the "Search Index" View-Mode. After enabling it for your Content-Type you can set it up the way SOLR should index it. So in your case probably the best would be to show the full content of the referenced node in the search index.

I hope this brief hints and tipps will help you ... To explain the Display Suite with all its possibilities is not possible in one post, but you really should try it.


Notice: Undefined index: tid in taxonomy_field_formatter_prepare_view() (line 1669 of I'm getting this error on my website. I have tried cleaning up the content type of all fields but it still shows up.

Any ideas what could be causing it, and how to debug?

Thanks a lot,

Chiko

Your content have an taxonomy_term reference field which have invaild data, maybe it break.

You can install devel module and use error display with debug_backtrace and you will see where it comming.


How do you add a PDF attachment to an email? Goal: I need to send an email with a pdf attachment in Drupal 8.

Progress

I am able to send an email with subject and message but have never been able to get the attachment. When I turn on the logic to attach the file to the email, the email never gets sent but the mail service returns True as if the email was sent anyway. There are no errors and the logs say nothing.

I have the following modules installed:

SMTP
MailSystem
MimeMail

What I've tried

Tried using $message['params']['files'][] = $params['attachments'] instead of $message['params']['attachments'][] = $params['attachments'] like some examples have recommended
Tried changing $file->uri to $file->filepath
Tried attaching the file like so:

$params['attachments']['filecontent'] = $this->generatePDF($foa_list);
$params['attachments']['filename'] = 'MyFormsOfAssistance.pdf';
$params['attachments']['filemime'] = 'application/pdf';

Tried attaching the file by path alone with an array:

$attachment = array(
    'filepath'=>'sites/default/files/MyFormsOfAssistance.pdf',
);

$params['attachments'] = $attachment;

Tried attaching the file a different way:

$attachment = array(
    'filepath' => 'sites/default/files/MyFormsOfAssistance.pdf',
    'filename' => 'MyFormsOfAssistance.pdf',
    'filemime' => 'application/pdf'
);

$params['attachments'][] = $attachment;

Setup

There is email landing page in which a user enters the recipient's email address, subject for the email, and message for the email.
When user clicks Send button, that data is routed to my Email Controller
Email controller creates the pdf file, attempts to attach the pdf to the email, and then sends the email.
I have the hook_mail() function defined in my module file.

Here is the code for my Email Controller:

public function submit_email($foa_list = null) {
    $lang = "en";
    $email_to = "blah@blah.com";
    $params['subject'] = "Test subject";
    $params['body'] = "Test body";

    // -------------------- Attachment Logic -----------------------
    // Create pdf file and store file
    file_put_contents('sites/default/files/MyFormsOfAssistance.pdf', $this->generatePDF($foa_list));

    // Attach pdf file to email params
    $file = new \stdClass();
    $file->uri = 'sites/default/files/MyFormsOfAssistance.pdf';
    $file->filename = 'MyFormsOfAssistance.pdf';
    $file->filemime = 'application/pdf';
    $params['attachments'][] = $file;

    // Send email
    \Drupal::service('plugin.manager.mail')->mail('email', 'email', $email_to, $lang, $params);

    $response = new Response();
    $response->setContent("true");

    return $response;
}

Here is the hook_mail() code in my Email module file:

// Note that print_and_email is what my module is called.
function print_and_email_mail($key, &$message, $params) {
    switch($key) {
        case 'email':
            $message['subject'] = $params['subject'];
            $message['body'][] = $params['body'];
            $message['headers'] = [
              'MIME-Version' => '1.0',
              'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
              'Content-Transfer-Encoding' => '8Bit',
              'X-Mailer' => 'Drupal',
            ];
            // $message['params']['files'][] = $params['attachments']; // Note: I have seen other examples implement attachments this way
            $message['params']['attachments'][] = $params['attachments'];
            break;
    }
}

The Drupal 8 documentation isn't really helpful and I would like to be able to figure this out without installing SwiftMailer, like some sources have recommended. Really not sure why this isn't working as it has worked for others. What am I missing?

FINALLY! 4 weeks later...

So the following code ended up working for me:

    $attachment = array(
        'filepath' => 'sites/default/files/MyFormsOfAssistance.pdf',
        'filename' => 'MyFormsOfAssistance.pdf',
        'filemime' => 'application/pdf'
    );

BUT, the key was that in the MailSystem Configuration I had to set the Formatter and Sender to "SMTP Mailer". MimeMail's config automatically pulled it's values from my SMTP's configuration.

$invoice_pdf = File::load($fid); // the file id
$invoice_file = (object) [
  'filename' => 'invoice.pdf',
  'uri' => $invoice_pdf->getFileUri(),
  'filemime' => $invoice_pdf->getMimeType(),
];
$message['params']['files'][] = $invoice_file;

'files' must be an array, that's were I had the most difficulties with. Full code here: Send e-mail with managed file attachment in drupal 8


offseting date by integer I've got a content type with fields:
starting date: Date (Unix timestamp)
duration: integer
ending date: Date (Unix timestamp)

User is setting only starting date (year, month, day) and duration (in days)
end after saving the content I would like to automatically calculate ending date (=starting date + duration)

I suppose I should use rules. I tried using actions like set value or calculate value but I failed. Could you help me?

Interval module may help you. It provides an interval field type and also a rules action: "Apply an interval to a date".

For a quick fix I would recommend making a simple custom module with this function:

function YOUR_MODULE_node_presave($node) {
  if($node->type === "your_content_type") { // Replace with the content type of your node.
    // Replace $node->XXX with the actual names of your fields.
    $startdate = $node->start_date[LANGUAGE_NONE][0]['value'];
    $duration = $node->duration[LANGUAGE_NONE][0]['value'];
    $enddate = &$node->end_date[LANGUAGE_NONE][0]['value'];

    $enddate = strtotime('+ ' . $duration . ' days', $startdate);
  }
}


How to have SimpleSaml create a new account only when the user doesn't have a Drupal account already? I'm new to Simplesaml...I feel like I'm missing something obvious in the configuration. Could someone point me in the right direction?

Drupal - 7.53

simpleSAMLphp Authentication - 7.x-2.0-alpha2

We have this setup running, and it does not register a new user each time but only the first time a user logs in, as expected. I just remember running into problems when unique identifier and user name where set to different values (my old bug report is possibly related).
To further manage the displayed user names you could use Drupal modules like RealName.

configuring SimpleSAMLphp_auth to register new users

In the admin interface, navigate to admin/config/people/simplesamlphp_auth

Under the tabs

USER PROVISIONING
check - Register users (i.e., auto-provisioning)

and

USER INFO AND SYNCING
Which attribute from simpleSAMLphp should be used as user's name *
eduPersonPrincipalName

(enter an attribute that uniquely and consistently identifies the user in your realm and that your SAML IdP provides, some attributes change with each invocation and are therefore not suitable, eduPersonPrincipalName is suitable for most educational entities, email could also work fine here)

Which attribute from simpleSAMLphp should be used as unique identifier for
the user *
eduPersonPrincipalName

(enter an attribute that uniquely and consistently identifies the user, make sure to use the same attribute as in user's name before)

From the documentation:

  Determines wether or not the module should automatically
  create/register new Drupal accounts for users that authenticate using
  SimpleSAMLphp. Unless you've done some custom work to provision Drupal
  accounts with the necessary authmap entries you will want this
  checked.

Checking which SAML attributes are available

Navigate to the admin interface of your simplesamlphp install (you might need to activate the interface and look up the password of the install from config.php).
 navigate to the Tab Authentication and "Test configured authentication sources" (/module.php/core/authenticate.php), log in to the same authentication source that is configured in the drupal plug-in under "Autenticaton source for this SP (default: default-sp)" and an overview of all SAML attibutes for that user will be displayed.

The attributes that can be used are possibly best obtained from the documentation of the identity provider, example: https://www.feide.no/attributelist

You may need to write something custom to handle this--I don't think the out-of-the-box config will take care of it.  As you've probably experienced, when you have "Register users" checked (under User Provisioning), that will create a new account for every new SimpleSAML login--even if it is duplicating an existing Drupal user's email address or other user information.

Based on the help text there, I think you'll need to write something custom (probably checking the authmap entries before provisioning the account):

From the config page (admin/config/people/simplesamlphp_auth)

  Unless you've done some custom work to provision Drupal accounts with the necessary authmap entries you will want this checked.

It looks to me like you'll need to provide authmap entries for your existing Drupal accounts, and then you can write a check for SimpleSAML.  But that is theory; I've never tried to do what you're looking for. Hope this helps.


looking for a slider module to use in the header what's a good slider for a header in drupal 7 (I would like to have a slider for different content in other blocks/pages of the website, so if the same module could work for both, better)

Try Views Slideshow. It is the most used and most flexible and you can create as many as you need.

There is an awesome slider for featured content in the header called Flow Slider. It's not integrated into drupal but it is very easy to use.


How to extract data from DB into fields? How would I go about extracting the data from a DB into fields? I would like to display information on a page using Views, but the information isn't on the website, instead it is in a separate database. Is this possible?

I get that in order to use Views I need to have fields, but how do I extract this?

If you just want the content, you can use Feeds as Patrick said but this will replicate the content of the other database as entities in your Drupal site.

If you really want views connecting to a remote database, this question looks like a duplicate of:

https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data

This will help you make Drupal "aware" of the external db:

http://drupal.org/node/18429

The data module would help you to achieve what you are looking for.

Here is a quote about it (from the module's project page):

  ... helps you model, manage and query related sets of tables. It offers an administration interface and a low level API for manipulating tables and accessing their contents. Data module provides Views integration for displaying table data and Drupal search integration for searching table content.