How to attach files using mimemail (Getting 0kb file) (This isn't the same as the other issue I raised. I thought I'd got the attachment working but I haven't)

Initial Problem

I'm trying to attach a file to an email. It's part of job application so a person goes to a node, presses apply and it sends an email to the creator of the node. I want to attach a CV & cover letter to it.

Here are my submit and hook_mail functions.

function tellafriend_form_submit($form, &$form_state) { ...

        $message = drupal_mail('tellafriend', 'notify', $email, language_default()); ...
}

function tellafriend_mail($key, &$message, $params) {

        global $base_url;

        $attachment = array(
          'filecontent' => file_get_contents('http://localhost/public/counciltax.txt'),
          'filename' => 'counciltax.txt',
          'filemime' => 'text/plain',
          'list' => TRUE,
          );
        $message['subject'] = t('Your friend thought you might like this site');
        $message['body'][] = t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
        $message['params']['attachments'][] = $attachment;
}

Sometimes this will send an attachment. Othertimes it won't. It sent once, I repeated the same process and it didn't work. Mostly it doesn't work.

These two tests were run 10 seconds apart and I didn't change any code.

Here's the successful email.

And here's the unsuccessful email.

Am I doing this wrong, or is this just broken? How would I debug this?

(This was the example I used as reference http://rapiddg.com/blog-post/drupal-7-html-e-mail-pdf-attachments)

EDIT  ----- 05/08/2013

I tried using frazras's technique (cheers!), of putting the attachment in the submit function however it still doesn't work every time. (Code not shown because it's identical to the section he posted.)

My public folder looks like this:

This is the information I'm entering:

'uri' => 'public://hashtags.txt',
'filename' => 'README.txt',
'filemime' => 'text/plain',

The results of sending 12 or so in a row. It mostly works now, but still randomly fails

I'm changing nothing inbetween the tries, it just doesn't work sometimes. Any other ideas or info about how I could debug this?

I usually do mine I little different from you, I add the attachment in hook_submit then pass it as a param to hook_mail, but even then some of our variables differ. here is an example from a working solution I have implemented, but changing to your text. I also added in the headers, maybe they arent necessary because I use it when dealing with jpeg file types.

function tellafriend_form_submit($form, &$form_state) { ...
    $attachment = array(
      'uri' => $filepath,
      'filename' => 'counciltax.txt',
      'filemime' => 'text/plain',
    );
    // Add attachments
    $params = array(
      'attachments' => $attachment,
      'file' => file_create_url($attachment['uri']),
    );

    drupal_mail('tellafriend', 'notify', $email, language_default()), $params);
}

function tellafriend_mail($key, &$message, $params) {
  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['subject'] = t('Your friend thought you might like this site');
  $message['body'][] =t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
  $message['params']['attachments'][] = $params['attachments'];
}


HTML tags of an article not working I came across this issue. I wrote an article in editor and I put there basic HTML tags like <strong> and so on. The thing is, in editor it shows right, but when I publish the article, the HTML tags dont do anything and they are displayed just like normal text.
Do you have any idea why is this happening?
Thank you for any reply

i hope , you have used basic html filter. Basic filter doesn't support all of the tags of html. you have to use full html filter instead of basic html.


How to check all checkboxes in a Views exposed filter by default? I'm using the Views and Better Exposed Filters modules to allow users to select age ranges like this:

This view functions as a search page.  However, users are confused because if they simply hit Apply, all age groups are searched even though no age groups are checked.  For this reason, I would like to show all age groups as selected by default to make it clear that all age groups are searched by default.

How can I do this?

If you click on the filter in the Views admin UI to get to the "Configure filter criterion" popup, and then select all of the options for the filter like so:

Then they appear ticked by default when you access the View page.


How can I add a filter to an export display? I have a view "Nearest Dealers" that lists all the near dealers. There are two displays - Page & REST Export. I've added a filter(exposed to visitors) that lets customer search dealers based on current location and distance(eg: 10km radius). Filter works perfectly, but I want to show the same filtered results in REST Export display for the same view. Is it possible to do so because I have no clue how to make this work. Or is there any way to add the same filter for the REST Export display ?

is there any way to add the same filter for the REST Export display ?

On your regular View page, apply filter for something, and you'll see a URL query gets appended to your URL. For example, when I'm filtering by content type, for mine, I see:
mysite.com/page-view?title=&type=article&status=All&langcode=All (This is based on the view filters I have).
Then all you have to do is append this query to your REST export URL.
mysite.com/rest-export?title=&type=article&status=All&langcode=All (Assuming you have the same filters as your page view, they should've been added by default when you added the REST view).
You'll need to create documentation for this. So people that are using your API know what parameter names & values are accepted.


Promotions not translated on cart and checkout page? I have commerce site in 2 languages: English (default) and German.
I enabled translation of promotions so when I go to promotions admin page ( /admin/commerce/promotions ) for each promotion there is also "Translate" operation. I can enter German translation for each and it's saved well.
Problem is that when I'm on cart page or later on checkout page (German pages) promotions are displayed in English only. Other content, including subtotal, total, shipping costs are translated well, but promotions are always on English?!?
I searched but couldn't find that anybody reported that issue before, so most likely I overlooked something (hopefully), but just can't find out what it is.
Any idea why promotion titles are not displayed in page language, but always in English (default language)?

I found work-around for this issue. Inside the template that prints that section (commerce-order-total-summary.html.twig) there is a loop that prints adjustments:
{% for adjustment in totals.adjustments %}

        {{ adjustment.label|t }} {{ adjustment.amount|commerce_price_format }}

{% endfor %}

and where adjustment label is printed I added t twig filter, so now it can be translated on standard user interface translations page:
/admin/config/regional/translate

I know that it's not optimal solution, but it works, so I hope this can help someone until bug is fixed.


How to pass an array to drupal7 form select as value of #options? This problem makes my head burn all day. Please see the code below.
I got a variable $region_value contains the region value with the same structure listed in the code. However different page has a different region value, so I have to use a variable to store it, it's not static.

$region_value = array(0 => 'US', 1 => 'EU')
//form code details have been left out.
//the below code define the form.
$form['region_options'] = array(
                '#type' => 'select',
                'prefix' => 'Region',
                '#options' => $region_value,
                               );

now I get the problem, cuz drupal can't accept the value of $region_value, something wrong happened cuz the $region_value's can not be passed into the form function itself in template files, it might be caused by the drupal core settings. I know it's not a good choice to write functions or other customer variables in the template files, but it's convenient for simple test, you don't have to dump the cash.

So my problem is, is there a mean to pass a variable value into the form function?

//variable set here
$options = array('foo' => 'bar',...)
//form define function goes here
function region_form($form, &$form_state) {
            $form['submit'] = array(
                                   '#type' => 'select',
                                   '#options' => $options,
                                   );
            return $form;
          }

Much appreciated for all advises.

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

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

Try something like this:

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


Call a php function on text selection in text area I have a text area in form. When some text from text area is being selected, I have to enable a button. How can I do that?

If you want to do something when text is selected, take a look at the .select() jQuery event.  Then you can enable/disable the button however you like.

Example from the jQuery page:

<!DOCTYPE html>

    Click and drag the mouse to select text in the inputs.

  <input type="text" value="Some text" />
  <input type="text" value="to test on" />


Render entity from entity reference field (Drupal 8) So I have a content type called Browse, then I have created a paragraph which is a entity reference field for content of Blog. So now when I create a piece of content in Browser I can add multiple blog posts to this page with the entity reference field from paragraphs. I can not figure out how to render the blog data into my twig template. Maybe I am using the wrong twig template file? I am trying with a field--paragraph--blog.html.twig. Does this need to be done in the theme_preprocessor?

You can enable Twig Debugging in sites/default/services.yml. If services.yml does not yet exist; copy default.services.yml and rename it to services.yml.

Set the debug variable to true:

parameters:
  twig.config:
    debug: true

Now clear cache and refresh your page. Look in the html source and you should see some template suggestions.


views information in exposed form hook I am trying to compare views in exposed form but so far there is no way I am getting views information in exposed form. Is there any way to do so? I need to compare view id for theme suggestion.

The view and display of an exposed form are stored in $form_state.

function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $view = $form_state->get('view');
  $display = $form_state->get('display');
}


Is it possible to make the Book Outline a mandatory field when creating a new book page? I would like to make sure that certain content types always have a parent book/page.

Is there a way to do this, by JavaScript, by modifying the book module or whatever?

EDIT: On review, I see this question is D7 specific. There may be subtle things wrong with my code snippet. It should be fundamentally the same.

If something should never happen, I prefer to make it never-an-option.

If you want to make all book pages default to being new books:

/**
 * Implementation of hook_form_FORM_ID_alter() for node_form.
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (book_type_is_allowed($form['#node']->type)) {
    // Remove the "none" option.
    unset($form['book']['bid']['#options'][0]);
  }
}

Once that's done, you can leave it be or set $form['book']['bid']['#default_value'] explicitly to be a new book, or a specified book bid of your choice. It will probably naturally fall into creating new books, as that is the first option in the selector after you remove none.


How to create a view of existing blocks? My aim is to make a Views grid of existing blocks in Drupal 7 (Might be possible without any additional code\module in Drupal 8).

I've tried to make a Content based View and filter it via Block ID's, but when I came to filter this View, I found no such option.

I've tried to check the "Relationships" option to see if I can add a relationship to Blocks but no such option was available there either.

Therefore, I wonder if a View of existing block is even an option naturally.

This question seems like a perfect illustration of why you'd use the Bean module (to actually create such view as in this question). Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

In this specific case, after you enabled the BEAN module, you should be able to create a view of blocks. As an illustration, have a look at this (basic) view (in Views export format):

$view = new view();
$view->name = 'blocks_created_with_bean';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'bean';
$view->human_name = 'View of blocks created via the BEAN module';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'View of blocks created via the BEAN module';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'bid' => 'bid',
  'label' => 'label',
  'title' => 'title',
  'type' => 'type',
  'uid' => 'uid',
  'url' => 'url',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'bid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'label' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'uid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'url' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Block: Internal, numeric block ID */
$handler->display->display_options['fields']['bid']['id'] = 'bid';
$handler->display->display_options['fields']['bid']['table'] = 'bean';
$handler->display->display_options['fields']['bid']['field'] = 'bid';
/* Field: Block: Label */
$handler->display->display_options['fields']['label']['id'] = 'label';
$handler->display->display_options['fields']['label']['table'] = 'bean';
$handler->display->display_options['fields']['label']['field'] = 'label';
/* Field: Block: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'bean';
$handler->display->display_options['fields']['title']['field'] = 'title';
/* Field: Block: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'bean';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Field: Block: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'bean';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Block: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_bean';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'view-of-blocks-created-via-the-bean-module';


Preventing user creation, but allowing edit I have defined a role in which I'd like to grant:

1) Permission to edit users

2) Prevent from creating new users

Is this possible? I only see one permission under User called "Administer users" which looks like grants both abilities.

Thanks

You might want to use the Administer Users By Role module. The 7.0-2.x version depends on the Chain Menu Access API.

After both modules have been installed and enabled, you will be able to grant user edit but not user add permissions to certain roles within the /admin/people/permissions form.

Nice side-effect: The user editors won't be able to alter the site admin's profile, if you don't allow it, as it could cause serious problems.


Node.tpl.php file: Check is several fields are empty On my node, I have three location fields (primary, secondary, code) and three object fields (food, fuel, accommodation).

I want my node.tp.php to check if all the location fields are empty or if all the object fields are empty and then print a message.

How can I do this?

Steps I have tried

1. Checking if the fields are empty.

This post says you can check if a single field is empty with the following code:

$field = field_get_items('node', $node, 'field_post_image');
if ($field) {
//Do something with the field
}
else{
//There are no results
}

I have adapted the code by adding the fields to an array and then testing to see if the array is empty:

<?php $empty_message = "No items here, click edit to add some.";?>

<?php
$field = array();
$field[]= field_get_items('node', $node, 'field_primary');
$field[]= field_get_items('node', $node, 'field_secondary');
$field[]= field_get_items('node', $node, 'field_code');

if (empty($field)) {
print $empty_message;
}
?>

<?php
$field = array();
$field[]= field_get_items('node', $node, 'field_food');
$field[]= field_get_items('node', $node, 'field_fuel');
$field[]= field_get_items('node', $node, 'field_accomodation');

if (empty($field)) {
print $empty_message;
}
?>

But it doesn't seem to work. The original post actually says this is the wrong way to check if fields are empty, but I'm not sure how to adapt the suggested code.

2. Using Field Group

I would prefer not use this module, as it adds too much complexity for my needs.

Put all the logic in your template.php (or wherever your preprocess functions go) with THEME_preprocess_node():

function THEME_preprocess_node(&$variables) {
  // Grab the node
  $node = $variables['node'];

  // Only run for your content type
  if ($node->type == 'your_content_type') {

    // Grab your fields with field_get_items so that it is translation friendly
    $location_field1 = field_get_items('node', $node, 'location_field1');
    $location_field2 = field_get_items('node', $node, 'location_field2');
    $location_field3 = field_get_items('node', $node, 'location_field3');
    $object_field1 = field_get_items('node', $node, 'object_field1');
    $object_field2 = field_get_items('node', $node, 'object_field2');
    $object_field3 = field_get_items('node', $node, 'object_field3');

    // Check if all location fields are set or not
    if (isset($location_field1[0]['value']) && isset($location_field2[0]['value'] && isset($location_field3[0]['value'])) {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['location_message'] = 'All location fields are set...';
    } else {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['location_message'] = 'All location fields are not set...';
    }

    // Check if all object fields are set or not
    if (isset($object_field1[0]['value']) && isset($object_field2[0]['value'] && isset($object_field3[0]['value'])) {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['object_message'] = 'All object fields are set...';
    } else {
      // Create a variable that can be used in your node.tpl.php
      $variables['messages']['object_message'] = 'All object fields are not set...';
    }
  }
}

Then, in your node.tpl.php you will have access to the message and you can print it anywhere with:

print $messages['location_message'];

and

print $messages['object_message'];


How do I add the  tag in ? If I want to add JavaScript in the head tag, I use drupal_add_js($js, 'inline'). This will add a <script type="text/javascript">.

How do I add the <noscript> tag? I want to add the following in <head> also.

<noscript>
  <meta http-equiv="refresh" content="5;url=<?php echo $file ?>" />
</noscript>

BTW, I'm using a simple module for this.

function custom_download_menu() {
    $items['download-code'] = array(
    'title callback' => 'custom_download_page_title',
    'page callback' => 'custom_download_view',
    'access arguments' => array('access content'),
    'access callback' => TRUE,
    );
    return $items;
  }

function custom_download_view() {
    $js = "var time_left = 5;
        var cinterval;

        function time_dec(){
            if(time_left > 0) time_left--;
            document.getElementById('countdown').innerHTML = 'Your download will start in ' + time_left + ' seconds...';
            if(time_left < 1){
                clearInterval(cinterval);
                window.location = '<?php echo $file ?>';
            }
        }

        cinterval = setInterval('time_dec()', 1000);";

    drupal_add_js($js, 'inline');
}

You can add elements to the <head> section of a web page using drupal_add_html_head().

$target = url('enable-javascript', array('absolute' => TRUE));
$meta = array(
  '#theme' => 'html_tag',
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'refresh',
    'content' => "2; url=$target"
  )
);
$noscript = array(
  '#theme' => 'html_tag',
  '#tag' => 'noscript',
  '#value' => drupal_render($meta)
);
drupal_add_html_head($noscript, 'noscript');

API Documentation


drush uli command goes to wrong domain I'm new to the command line, having trouble understanding why the uli drush command is taking me to the wrong domain.

On Pantheon, the dev site address is: dev-example.pantheon.io

I've successfully installed drush and all the aliases I need. However, when I enter this command:

drush @pantheon.example.dev uli

It takes me to wrong domain: wrongsite.com/user/reset/1/1....A/login

It should be: dev-example.pantheon.io/user/reset/1/1....A/login

I can login as user1 if correct the domain in the address bar. But what's happening here and how do I fix default domain?

Thanks!

This one was more obvious than I thought. Client added bogus domains to the dev environment which caused the uli to go to the wrong site.


add file browser button to ckeditor I have installed ckeditor 3.5.2 with Wysiwyg profiles and every thing works great.
but in admin user  page i can see file browser link . how to add this link like button to ckeditor? i checked buttons like image and imce a but it doesn't add file browser to ckeditor.
at now i have upload files in admin user page and link them with ckeditor.
Anyone have this filebrwoser button (for uploading zip ,...) on ckeditor?

I'm not 100% sure but I think you need the IMCE Wysiwyg Bridge module.


how to apply two themes for an element in custom module? In the custom field module that i have written, i am trying to use two themes for same element. One is pager theme and another one is item_list theme ..

I want to make both of these themes work for this element. Do i have to add them in array one item after another ?

Thank you very much :)

Edit: I have modified my code as per patmacs suggestion. I will put that code below, since my page is not displaying anything with change in code.

function event_webpages_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

// Retrieve documents from Solr function using query
foreach($items as $delta => $item) {
$records = solr_get_results($item['query']);

// iterate through the documents and put them in the array $items in which every record is passed over a theme defined in hook_theme()
foreach($records as $record) {
  $items[] = array(
    'data' => array(
    '#theme' => 'event_webpages_field_list',
    '#node' => $record,
    ),
  );
}

// Number of items per page
$per_page = 10;
// Initialise the pager
$current_page = pager_default_initialize(count($items),$per_page);
// Split your list in to page sized chunks
$chunks = array_chunk($items, $per_page, TRUE);

// The pager theme element
$element1 = theme('pager', array('quantity',count($items)));

// The item_list theme element
$element2 = array(
  '#theme' => 'item_list',
  '#items' => $items,
  '#pre_render' => array('event_webpages_item_list_child_render'),
  );

// the final element passed along with the theme defined in hook_theme()
$output = array(
  '#theme' => 'event-webpages-theme-list',
  '#element1' => $element1,
  '#element2' => $element2,
 );
drupal_add_css(drupal_get_path('module', 'event_webpages') . '/event-webpages.css');
return $output;
 }

The above one is my formatter_view function and my hook_theme function looks like this

/**
 * Implements hook_theme()
 */
function event_webpages_theme($existing, $type, $theme, $path) {
  return array(
    // The theme applied for each item in the item_list
    'event_webpages_field_list' => array(
    'variables' => array(
    'node' => NULL,
    ),
    'template' => 'event-webpages-field-list',
    ),
    // The theme applied to the final output and each variable is theme element
    'event_webpages_theme_list' => array(
    'variables' => array(
      'element1' => NULL,
      'element2' => NULL,
    ),
    'template' => 'event-webpages-theme-list',
    ),
  );
}

The code in event-webpages-theme-list is

<?php
// $Id$
?>
<div class="<?php print $classes; ?>">
<?php print $element1; ?>
<?php print $element2; ?>
</div>

Sorry if it made it more confusing but i thought this will give a overall view of what i have done. Should i use a preprocessor function for 'event-webpages-theme-list' before passing the variables ?

Many Thanks

**
* Implements hook_theme().
*
* Defines the theming capabilities provided by this module.
*/
function YOURMODULENAME_theme() {

  return array(
    'THEMENAME1' => array(
    'template' => 'PATHTOTEMPLATEFILE',
       // EXAMPLE URL FOR ABOVE - 'templates/mymodulename--event--list-item',
       // This will make the module look for mymodulename--event--list-item.tpl.php
       // in the template folder within the module's directory
    'variables' => array(
      'SOMEVARIABLETOPASSTOTHETEMPLATE' => NULL,
      'ANOTHERVARIABLETOPASSTOTHETEMPLATE' => NULL,
      ),
    ),
  ),

}

Then when you have to return the content for the block or page, just call this function:

$output = theme("THEMENAME1", array('SOMEVARIABLETOPASSTOTHETEMPLATE' => "this is the variable that gets passed to the tpl", 'ANOTHERVARIABLETOPASSTOTHETEMPLATE' => "Another variable that is being passed to the template"));
return $output; // You could also just return the theme function above

Now, within your mymodulename--event--list-item.tpl.php file (Or whatever you named it) you can print any of the variables that you defined above.

<div class="somemarkup">
  <?php print $SOMEVARIABLETOPAsStOTHETEMPLATE; ?>
</div>


add a checkbox to the image_field I want to add a checkbox-field to each image I upload (like the title- or alt-fields) , to set the option whether the theme should render the image as a gallery or not. the value should be saved in the db. int(1)

I don't want to install heavy modules for this...

edit: but if there is no other option, I take the module :D

is there maybe a strategy I should use to solve the problem? writing a widget or something? hooking into the images_schema ?

I just did this with the imagefield extended module and a small custom module. After enabling the imagefield_extended module, I add this code to my custom module.

/**
* Implementation of hook_imagefield_extended_widget().
*/

function MYMODULE_imagefield_extended_widget($element, $extra_values) {
  // If you need the field or widget to conditionally add a FAPI field, use these.
  $field = content_fields($element['#field_name'], $element['#type_name']);
  $widget = $field['widget'];
if($element['#type_name'] == 'occupancy_status' && $element['#field_name'] == 'field_task_files'){
  return array(
    //This will Replace the Textfield with dropdown select for the description
    'description' => array(
      '#type' => 'select',
      '#title' => t('Document Description'),
      '#options' => array(
         'Occupancy Flyer' => t('Occupancy Flyer'),
         'Personal Property Release' => t('Personal Property Release'),
         'Introduction Letter' => t('Introduction Letter'),
         'Notice of Rights' => t('Notice of Rights'),
         'Miscellenous' => t('Miscellenous'),
      ),
      // this makes b the default value when the value is not set.
      '#default_value' => isset($extra_values['description']) ? $extra_values['description'] : 'Miscellenous',
    ),
  );
  }

   if( $element['#type_name'] == 'property_gallery' && $element['#field_name'] == 'field_gallery_images' && arg(1)!=='add'){

  return array(
    //These are stored in the 'data' column of the cck imagefield's db table
    'revised' => array(
      '#type' => 'checkbox',
      '#title' => t('Revise This Description'),
       '#default_value' => isset($extra_values['revised']) ? $extra_values['revised'] : 0,
     '#attributes'=>array('class' => 'revise-check')
       ),
    'revisedby' => array(
      '#type' => 'textfield',
      '#maxlength' => 64,
      '#title' => t('Revsied By'),
      '#description' => t('Replace your name with the current name if you are making a new revision.'),
     '#default_value' => ($extra_values['revised']==0) ?  NULL : $extra_values['revisedby'] ,
       ),
       'revisedon' => array(
      '#type' => 'date',
      '#title' => t('Date Revised'),
     '#default_value' => ($extra_values['revised']==0) ?  NULL : $extra_values['revisedon'] ,

       ),

  );
  }
} /*End function */

You have the ability to add or modify the filefield or the imagefield field widgets. The only problem that I'm stuck at is making this work for fupload_imagefield.


Which tables are safe to omit from sql-sync? I sync my database with drush sql-sync @dev @live and the other way round. Can I omit the following tables safely, like in my drushrc.php from sql-sync?

$options['structure-tables'] = array(
   'common' => array(
     'cache', 'cache_filter', 'cache_menu', 'cache_page',
     'cache_admin_menu' 'cache_block', 'cache_coder',
     'cache_content', 'cache_form', 'cache_hierarchical_select',
     'cache_location', 'cache_update',
     'cache_views', 'cache_views_data',
     'ctools_css_cache', 'ctools_object_cache',
     'history', 'sessions', 'watchdog'
   ),
);

Additionally I wanted to exclude variable_cache and views_object_cache if that is safe.

Is that a good practice? Is there a list of tables somewhere on drupal.org for all modules?

If you update to the latest dev version of Drush, you will find the following definition in examples/example.drushrc.php:

# $options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');

The wildcard syntax is very useful, as with it, it is no longer necessary to make a comprehensive list of all cache tables used by all of your contrib modules.  Note that you must use the latest version of Drush pulled from git; the 8.x-6.x-dev from 18 June does not have wildcard support.


Region for the footer not working, but the header is working I have the following regions set up in my *.info.yml file:

name: Test
type: theme
description: 'Theme'
base theme: stable
core: 8.x
regions:
  header: 'Header'
  content: 'Content'
  footer: 'Footer'
libraries-override:
  system/base: false

In page--front.html.twig, I placed {{ page.header }} where I wanted the header to be, and noticed via Twig Debugging that Drupal was expecting a file named region--header.html.twig.  Great!

So, similarly, I did this for the footer.

{{ page.footer }} and region--footer.html.twig ... but it does not work!  Twig Debug's comments do not reveal any hook for the footer at all.

What am I doing wrong?

Regions are only rendered by default if they contain blocks (of which at least one must have content).

You can check whether the Footer region has blocks assigned to it by visiting the Block Layout admin page at /admin/structure/block. If you see the No blocks in this region message under the Footer block, you know that's the problem.


How to cache minipanels I use minipanels in specific regions of pages (such as the main menu region) and they generally conain content that stays the same. How can I cache these minipanels?

Is the block caching system independent from the minipanels? I am not sure about that, since minipanels also show in the blocks configuration admin page.

You can cache mini panels from mini panels UI settings.
Go to the mini panel content edition page.

You have then 2 choices. Above in global mini panel display settings or per panel content piece : in its wheel settings at the bottom...


Cannot re-order the blocks of Drupal 7 site This error happens just on my local server (I use the last version of Acquia Dev Desktop, kind of XAMP for Drupal), not on our remote servers:

I am suddenly unable to re-order the blocks of our site (Drupal 7.23). The drag-and-drop functionality is not working and entering the weight numbers manually either. I have researched this problem and tried all solutions posted (Aggregate JS, disable LightBox2, change the DB block fields from tiny to INT...).

We have a large number of files in our website, and in some regions they have reached the magic number of 127. Reading a few posts, I see this may be the problem when you have some DB fields defined as tiny, but after changing all the tiny (4) fields of the blocks table to INT(11) I do not see any change.

Any clue?

Thank you very much in advance.

If there's no javascript error in the console, and you have a lot of blocks, and are using the Suhosin extension, you may be hitting a Suhosin limit. If that's the case, you will need to increase the relevant values there. There may be more information in your server error log.

More info: http://www.hardened-php.net/suhosin/configuration.html#suhosin.post.max_vars


Is a DB transaction executed when it is committed? cache_get() is not working as expected when called in a request initiated by drupal_http_request() on the same server.  Is it true that the cache_set() immediately before drupal_http_request() doesn't actually take place in the database until the first database transaction is committed?

Given the sequence:

cache_set($cid, $data)
cache_get($cid) // returns data
external request using drupal_http_request()

cache_get($cid) // same $cid, returns FALSE

cache_get($cid) // of course, returns data

To make the cached item available to the request initiated by drupal_http_request() I wrapped the cache_set call in a function like this, but it had no effect.

function cache_set_wrapper($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  $txn = db_transaction();
  return cache_set($cid, $data, $bin, $expire);
}

Why is there a discrepancy in the cache between the initial request on the second request?

Copied from my comments:

That depends on where and how you are calling cache_set(). A transaction only exists if someone explicitly started it. If you're in a node, user or other entity insert/update hook for example, then yes, then you are in a transaction.

If there is an active transaction that it will only get committed at the end. Nested transactions are supported but only to rollback to a certain step. Does the external request need to happen immediately? Doing external requests from a entity crud hook is always a bit problematic for performance (imagine a bulk resave or import of nodes) too. Consider moving the HTTP request to a shutdown function or a queue.


Get site name in custom template I want to print the site name in a custom template (page--front.html.twig)

{{ site_name }} does not work.

If I use {{ page['#title'] }} I only get "Welcome to [site_name]".

I'm looking for a way to only print the site_name. Do anyone know how to achieve this?

Thanks!

Add this to the YOUR_THEME.theme file:

function YOUR_THEME_preprocess_page(&$variables) {
  $variables['site_name'] = \Drupal::config('system.site')->get('name');
}

And then this in your page--front.html.twig template:

{{ site_name }}


Changing the value to negative I have a content type of invoice. This also has a drop down list (list text) to let the user pick one of three types - receivable , payable and proforma.

I also have it so I'm getting the amount, vat and total of the invoice.

However, what I need to do is change the value of the invoice amount, vat, and total when the user picks payable from the drop down menu to a negative value. For example, I fill out the invoice make it payable and I enter 2000 in the amount, 230 in vat and 2300 in total fields. I need these values to become negative when I run aggregator plus on them so instead of adding these numbers it subtracts them instead.

I was wondering if I can do this using rules, or do I create a new module to do this, or if I add a function to the template.php file. Any ideas of what is easiest and best

In my opinion, the most elegant solution would be to leave the original values and to define how you operate with them (adding, substracting, etc.) at the Aggregator Plus level, but I am not familiar with that module, and I don't know how easy it would be to extend it.

If you want to modify the value of these fields before saving the node, there are at least two possibilities I can think of:

Using Rules (it involves creating some custom PHP code). The following example (using increment instead of changing the sign) can give you a hint: https://www.drupal.org/node/1389074
Creating a custom module and implementing hook_node_presave(), in order to modify the fields before they are written to the database.

Hope that helps,


Looking for node revision author token According to http://drupal.org/node/252241 a revision author token may be available. However I do not see anything referencing revision:author (variation?) in my list of available tokens. Is there something like this?

For D7, in order to gain access to revision:author tokens, you have to install Revisioning module. (of course you also need token module)

Then you can see all the available tokens by going to Help -> Token (/admin/help/token)

So after enabling the module, a new token category, named "Revisions", is available. You can see for example
[revision:revision-author] which refers to "The author (or editor) of the revision" and a bunch of others regarding the revision author.

P.S. As per this there seems to be currently a bug regarding [revision:revision-author:mail]

Good luck and let me know if you need more help!


How do you include a Dev module in a make file? I am using Drush make files to automate my site development.

I have followed this tutorial to create a Make File via Drush.

Everything works fine, except when I run the make file, Drush says it can't find the Development versions of modules (for the modules where I have used the Dev version).

According to this tutorial, this is because you have to specify the Git Address and Revision ID of the module. How do you do that?

Steps I have taken

For example, lets say I want to include 7.x-1.x-dev release of the Fences module.
This dev module was released on 2013-Sep-30.

On the project page, there is an option called View all Releases. However, on this page, none of the releases are dated 2013-Sep-30. The project page also has links to a Git page for the project. However, this doesn't seem to have been updated for a while as the newest update was 15 months ago.

How do I find the Git address for this Dev module or is there another way of including it in my make file?

You're almost there - what you need to add to your make file looks like this and you have to specify the git url and commit identifier.

projects[path_breadcrumbs][version] = "3.x-dev"
projects[path_breadcrumbs][download][type] = "git"
projects[path_breadcrumbs][download][url] = "http://git.drupal.org/project/path_breadcrumbs.git"
projects[path_breadcrumbs][download][revision] = "c9c570b0b4bde1df0e5a322ab90197d7fc1cf9c6"

To find this, go to the project page on drupal.org and select 'view commits', ex

On the next page, select the one you are interested in that reflects the state of the module you want to add to your make file. For this example, I'm going to grab the last commit:

and I'm clicking the 'commit bdcf88a' link which takes me to:

http://drupalcode.org/project/path_breadcrumbs.git/commit/bdccf8a

Now I know that the the [download][url] is:

http://drupalcode.org/project/path_breadcrumbs.git

and the full hash for the commit I am looking for is:

bdccf8a901b6d2359b6da195d23cadf7dd90c4ec

--

Further updates as requested -- if you're looking for a specific dev branch you may want to switch to the command line to do a --recursive clone to make sure you're getting all the branches. Following this question:

How do I git pull a dev branch?

I'm going to do a recursive pull of the git 7.x-1.x branch

git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/fences.git

Now I can see what branches are available:

git branch -r
  origin/1343724-region
  origin/7.x-1.x
  origin/HEAD -> origin/master
  origin/master

Now I can checkout this branch for 7.x-1.x and check the log, which will give me the last commit and the one that was used to generate the development snapshot.

git checkout 7.x-1.x
git log

  commit 67206b5220cbebf52e8e6a290ccb977b2420b2ad
  Author: JohnAlbin <virtually.johnalbin@gmail.com>
  Date:   Tue Sep 4 13:44:40 2012 +0800

      Fix code comments on figcaption.

The date is different from what you may see on the project home page only because this is an automatic development snapshot created by the Drupal.org git bots but the development snapshot is always created from the branch with the same version number and the '-dev' part is never used in the branch name.


Contextual Filter not getting the correct NID from URL I THINK my Contextual Filter from my view is not getting the correct NID from my URL.

I have a view page with a path of "node/%/agenda".

The link on my menu is "node/[node:nid]/agenda".

The view page will get the nid from a content type "Venue".
Example:
Venue: Rave = NID: 101
View page will be = "node/101/agenda"

I have a working block of "Upcoming Events" and this works perfectly fine on my venue content type. But when I use it on a view page it's not working anymore. Basically this block shows the "Upcoming Events" from "Event" content type that is related to the "Venue" content type.

BLOCK:
Setting:

How it works on content type venue:
This is the wrong part:

As you can see it does not get the same result on the view page, it does not even show the "No Result". I am calling the correct block.

Am I missing something big? I hope someone can help!

THANK YOU VERY MUCH!! ^_^

According to what i can see from the screen shots, you didn't specify your relationship entity on advanced menu. If I were you, I would pick a entity reference, then i would pick a content contextual filters with Nid. Otherwise there is no way that block is gonna understand what the relationship is. Please update us your work. This is a very sensitive topic of drupal. Kind regards


What are the ways to handle a fresh new project? There is a lot buzz around regarding installing Drupal via Composer, but many tutorials manage Drupal via Drupal Console. Last but not least, the other Drupal command line tool, Drush. It causes lots confusion and I would love to hear a good round up what each tool brings.

This is maybe not a stackexchange question but a good question to rather discuss somewhere else. The reasons for your confusion are caused by a problem, the Drupal community is already aware of for a long time but it is not easy to find a better solution for that than as it is at the moment.

An overview

Drush was THE terminal command line tool for Drupal and was precursor in type of such tools long time before Composer or other command line tools like this even existed. It was a very helpful tool for Drupal developers on a daily basis, was VERY innovative in this time and still is.

Drupal Console raised over the last years in the time of when Drupal 8 was on development state and the Symfony PHP framework started to become the underlying construction kit for this new Drupal version. A decision which was long discussed and worried about ot map a good future for Drupal and its principles. A lot of stress and discussion raised in this time regarding the community choices afterwards again and even forks have started. Drupal Console has tried to fill gaps of Drush and treis to find its gap now between Drush and Composer.

Composer is like Symfony a widespread tool on many development projects and therefor not to ignore. Drupal has learned from its isolated position with its own tools in history and tries to adapt tools which are common for developers.

It's all in all a very basic and flat explanation here. But I wanted to keep it simple yet. There are many details missing and finally all 3 tools have a good reason to coexist IMHO.

TL;TR

Drush = Command line Devel, Drupal Console = Good module and theme creation helper, Composer = Maybe THE Drupal project installer in the near future (even admin UI implementation discussion occurs atm).

A good source to read about the work on this: An interesting discussion is going on here regarding Drush pointing same points you have asked about: https://www.drupal.org/node/2906637


Configuration settings in filedepot for folders How to setup permissions in filedepot module?

I have 2 users like A and B.

User "A" can create the folders and he can upload the files into that folders, but folders and files should not show or share to user "B". User "B" be follow the same functionality.

Only user can view the owned files.

Is this a job for the Content Access module?

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


Adding extra info to each Node -> Taxonomy Term relationship We have a basic site with a pages that have a taxonomy term content type associated with a number of terms.

What we would like to is to add more information to each of the node -> taxonomy relationship.

For example, the details of the author that tagged the term(different authors can tag a term to a node), the date the particular tag was added and so on.

I have looked at the Entity API, the Relation module and various other solutions in between.

From what I can tell, Entity Reference along with the Entity API seems to be the simplest way forward.

While I am not loathe to get my hands dirty and start coding this out, my knowledge of how each of these things fit together is limited.

Can someone point me in the right direction and point out any potential pitfalls along the way with regards to getting this done?

Imho, the simpliest way to achieve associations of data with field value without coding is to use Field Collection.

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is
embedded in the host entity. Thus, if desired field collections may be
viewed and edited separately too.

You will then be able to set, each time you tag one or more terms, additional informations in other fields of your field collection. Plus, you can have multiple field collections of the same type on your content.


Pass URL alias info to default value of Webform field I'm running the Storm (project management) module and for each task, the user needs to fill out a form regarding information about the task, including uploading images about certain information captured in the form. I'm trying to pass the url alias from the task page to the default value of a field I created in webform. My current URL's look like this: ?q=content/82245940-initial-services
. My problem (well, at least my first problem) is that I use the %get[q] but get node/5 as the default value. I don't understand and know enough about PHP programming yet, to know how to fix this so that I get 82245940-initial-services as the default value instead. Any help is much appreciated for the noobie. Thanks in advance!

EDIT By the way I have read these posts that while I have found helpful to understand the general concept, the details are over my head:

http://drupal.org/node/296453#webform-url-default

http://drupal.org/node/228622

So, I've tried, I just don't know enough yet!

You can get the URI with $_SERVER["REQUEST_URI"] and remove the "q=content/" string from it.


Why is the CSS for my theme not loading while the JS is? Theme mytheme is placed under /sites/all/themes/

Content of mytheme.info.yml :

name: My Theme
type: theme
description: Custom theme.
core: 8.x
base theme: classy
version: 8.x-1.0
libraries:
  - mytheme/global-styling
regions:
  logo: 'Logo'
  navigation: 'Navigation'
  page_header: 'Page Header'
  content: Content  # the content region is required
  page_sidebar: 'Page Sidebar'
  contact_first: 'Contact (First column)'
  contact_second: 'Contact (Second column)'
  contact_third: 'Contact (Third column)'
  footer_logo: 'Footer logo'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_copyright: 'Footer Copyright'
regions_hidden:
  - sidebar_first

Content of mytheme.libraries.yml :

global-styling:
  version: 1.x
  css:
    theme:
      assets/plugins/bootstrap/css/bootstrap.min.css: { minified: true }
      assets/plugins/font-awesome/css/font-awesome.min.css: { minified: true }
      assets/css/style.css: {}
      assets/fonts/montserrat/montserrat.css: {}
  js:
    assets/plugins/jquery-1.11.1.min.js: { minified: true }
    assets/plugins/bootstrap/js/bootstrap.min.js: { minified: true }
    assets/plugins/moderniz.js: {}
    assets/js/app.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

The JS is loading but the CSS isn't. How come?

try wrapping the google fonts entry in quotes like this:

'//fonts.googleapis.com/css?
family=Open+Sans:400,300,600&subset;=latin,cyrillic': { type: external }

Maybe there is a problem with the url using yaml special characters https://stackoverflow.com/questions/19109912/do-i-need-quotes-for-strings-in-yaml#22235064


Problem setting a private directory I have problems establishing a private files directory (D7.22)

I started at reading this article: http://drupal.org/documentation/modules/file.
I then created a private folder above the Drupal root, and entered its path ../private at admin/config/media/file-system. Despite being warned about the performance implications, I chose the Default download method as Private local files served by Drupal.
Then, in a content type I created a native file field named Attachment, with Upload destination set to Private files. Widget: File.

At this stage I imagined that these settings would cause an uploaded file to go inside the ../private directory. Nope, instead they go into public directory sites/default/files. Was my assumption wrong?

I tried the following debugging changes - but to no avail:

changed ../private to sites/default/files/secure
changed field widget to Media file selector
changed default download method to Public local files served by Drupal

Is it a site ghost? Am I doing anything wrong?
I really see no reason for this not to work. I'm close to filing a bug issue but would appreciate someone confirm that on their installation before I do so.

I'm using private upload on several sites and can confirm that this works.  So no need to file a bug issue.

  At this stage I imagined that these settings would cause an uploaded file to go inside the ../private directory. Nope, instead they go into public directory sites/default/files. Was my assumption wrong?

No. This is indeed what should have happened.

So just to make sure, I set up a site to your exact specifications. I.e. with Drupal root in /demo/drupal and the private directory in /demo/private  (where / is the Unix file system root).

I first tested it using the absolute path (i.e. /demo/private as the private upload directory).  That worked without a glitch.

I then re-tested it using the relative path to the same directory (i.e. ../private).  That also worked without a glitch.

I also noted that Drupal threw the following error if I tried to input a non-existing directory as the private upload directory:

Warning: mkdir(): Permission denied in drupal_mkdir()
 (line 2341 of /demo/drupal/includes/file.inc).
 The directory /demo/bogus does not exist and could not be created.

In other words: If Drupal allow you to use ../private as the private upload directory without throwing this error, your setup should work for private upload.

Drupal will automatically place a .htaccess-file in the private upload directory to protect it against  prying eyes.  However, for best security, the private upload directory should be above the web-root.

PS: As for the file being "served merrily to an anonymous user", this will happen if the anonymous user is granted access to the node the privatly uploaded file it attached to.

All that the "private download method" does, is to extend Drupal's access control system so that files attached to nodes are made inaccesible to those who happen to know their URL.  It does so by pretending that the attachement is stored in the fictitious directory (system/files/).  Since this directory does not exist, bypassing Drupal by converting the path into an URL and requesting it directly from the web server will not work.

This is different from, and more secure than the "public download method". This method let those who know a file attachement URL bypass Drupal's access control.


Is it possible to combine several template files togather and make single integrated template instead? For example to render a simple form like search block should be invoked 8 different templates like below and each of this template only has one or few line of code, see below:

region.html.twig
└─ block.html.twig
   └─ form.html.twig
      ├─ form-element.html.twig
      |  ├─ form-element-label.html.twig
      |  └─ input.html.twig
      └─ container.html.twig
          └─ input.html.twig

As you can see in below some of this files Just have a few line of code:
region.html.twig

{% if content %}

    {{ content }}

{% endif %}

form.html.twig

<form{{ attributes }}>
  {{ children }}
</form>

form-element.html.twig

{% if title is not empty or required -%}
  {{ title }}
{%- endif %}

input.html.twig

<input{{ attributes }} />{{ children }}

container.html.twig

{{ children }}

Some of this templates files are common with other parts of page and
editing each of them can affect to other parts and cause unwanted changes
. for example in this case drupal theme system for: "input.html.twig", suggest only input--submit.html.twig and this suggestion also common between search block and search form.
Editing and managing this template files is tedious and difficult and
make my theme folder busy.
Most of these templates have ambiguity and unclear content code

For this reason I'm looking for a method to combine this template files and make one template file like "form--search-block.html.twig" to I can edit all element needs for rendering a form in one special place
and with more flexibility and confidently.

In drupal 8 there's this rule called theme inheritance and backward compatibility, what you have to do to accomplish what you want is to make sure that your subtheme does not inherit any core theme's HOOKS

You might want to play around in your subtheme and set your base theme to null
I haven't checked it myself but it might work.

And then of course you have to define new preprocess templating rules in your themename.theme file using theme_suggestions_page_alter function, you can read more here

Then based on what you defined in your .theme file you may proceed with creating a unified template file

Also you might want to read this suggestion that somewhat explains a similar use case


How can I undo the changes made by setting a private file system path? I was installing the demo module on D7. I wanted to create a snapshot to use the demo reset part of the module. It told me to set the private file system path. So I entered the directory where all my websites live. /var/www/vhosts/domainname.com/ . Inside that folder there is a folder by domain name for each domain in the subscription. Including the folder for the site where i changed the path.

Now all the websites that are contained on the subscription are broken. As you can imagine, I'm desperate to know how to undo whatever I did. I'm so confused as yto how it has effected the other websites. I thought it was just going to be used to store the snapshot.

When I set the path to the directory that contained my actual site/s, it placed a .htaccess file restricting access. Being as that folder contained many Drupal sites, all sites seemed broken.

Deleting that .htaccess file in the folder I entered resolved the issue.


Comma Separated List in VBO I am trying to select a bunch of users with a bulk operation so I can delete them and unpublish their comments. I have a comma separated list of about 250 users. However, when I use the filter command in views, it only lets me enter about 10 names before the form runs out of space.

Is there something I am missing here? How do I create a filter that will take a much longer list of names? and/or just pass in a CSV file?

The textbow must have a size so you wont be able to make more than what your are doing now. But if your in views you can see the DBquery generate and use it on PMA to delete a greater number of users with theirs comments.

Be carefull, it's to do if you know what you are doing. I suggest to look at the query of view  because Drupal create a table for each CCK field so it's hell to figure the inner joins. If you have a doubt, make a save of your database before.


Custom view mode for entity references - getting rid of title I have an entityreference field that displays content in a custom view mode. It works great.
The only problem is that in addition to the fields that I placed in my custom view mode, it also displays the title as a link to the content. I would like to replace it and have another field (that is already in the view mode) be used as the link to the content. Also the title is appearing in the markup outside the entityreference field's view mode's wrapper, making styling a bit cumbersome.
So right now I have something like the following as field output
The title of the node

headline
My cool description that has some words in it
[and a picture]

I want essentially the same thing, but minus the title, and with the headline as the link, like so:

headline
My cool description that has some words in it
[and a picture]

How do I go about getting rid of the title and substituting the headline?

You could do this with display suite as follows:

Enable display suite and display suite extras (important)
At structure > ds > list > extras > Other, enable Page title options
At Manage Display > [view mode] > [layout], enable a DS layout for your view mode
Manage Display > [view mode] > custom page title, hide the page title

DS has a lot going on. But if you need custom display modes and need to hide the page title in some cases it works well. Plus you get a lot of other nice features.


IIS - how to handle file permission problem Here is a generic error message, shown several times on each page :

  Warning: file_put_contents(temporary://fil25BC.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in > file_unmanaged_save_data() (line 1935 of C:\inetpub\www-v2.3\includes\file.inc).

What can I do ?

EDIT
I stopped struggling with that problem by changing my temporary directory on this server
It was C:\Windows\temp (or C:\Windows\temp\drp-tmp)
It is now sites/default/files/drp-tmp
Note : on another server, the first setting is not giving warnings... Well, looks like I do not master that topic !
THANK YOU FOR your answers and attention

Seems like issue is that Drupal is trying to write a temporary file somewhere it cannot write, like in the site's docroot...

Try running below commands using drush and make sure write access is available for temp directories..

~$ drush vget file_directory_temp

~$ drush vget file_temporary_path


EntityTypeManager database transaction I am using \Drupal::EntityTypeManager() in Drupal 8 to save data provided from a form into a content type. The following code saves the information in the content type news:

$data = [
  'type' => 'news',
  'title' => $title,
  'body' => ['value' => $content, 'format' => $format],
];

$node = \Drupal::EntityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

Now I need to get the nodeID of the node that was just saved. How do I do that ? Furthermore, I need to insert another set of data into a second content type that needs to store the nodeID I just mentioned.

$node2 = \Drupal::EntityTypeManager()
  ->getStorage('node')
  // $data2 contains the $node->id()
  ->create($data2);
$node2->save();

Outside of Drupal I am used to mysql transactions to make sure that both things only get stored together and get rolled back if there is an error with either of them. Is there a way to achieve this 'all-or-nothing' functionality with \Drupal::EntityTypeManager()?

Do I genrally need to put this in a try{}catch{} block in Drupal?

You can create the node without saving it.  You wouldn't really need a try catch if you know what types of data you're saving.

    $node = \Drupal::EntityTypeManager()->getStorage('node')->create([
      'type' => 'news',
      'title' => "hello world",
      'field_some_textfield' => "Here's some text",
    ]);

    $node->set('status', 1);
    $node->set('field_site_section', [['target_id' => 6]]);
    $node->set('field_first_name', $data->firstName);
    if (!empty($data->middleName)) {
      $node->set('field_middle_name', $data->middleName);
    }
    $node->set('field_last_name', $data->lastName);

When you're satisfied that your node is set up properly, then you can call:

$node->save();

At this point, you can get the node id this way:

$nid = $node->id();


How to set permissions of creating content only for referenced users I have 2 content types: Courses and Documents. In Documents there is a node reference field which connects it to Courses (actually with a Node Reference URL Widget). In Courses there is a user reference field.

I'd like to add permission of Document content creation only the user who is referenced in Courses. Is it possible somehow? I tried it with Node access user reference modul (it has a "Grants for referenced users to create content" option) but it adds the create permission in every Course content, not only in that he/she is referenced.

If you are using the Node Reference URL Widget to add the create link then you could use panels (with the built in context) to hide that link if the user is not referenced on that node. This would not stop people from going to the url directly but would keep the honest people from creating content on nodes that they are not referenced on.

If you need a more secure way to prevent the creation of the document nodes I assume you would need to write some code or do some rules magic.

Rules magic idea: Create a flag that is hidden like I mentioned above. When the node is flagged then if the user reference is the current user then create the node and go to the edit page(and unflag when done). If not then unflag and show a message.


Form submission with AJAX to override a block content So, I have a block that I render with the following code.

public function build() {
  $filterForm = \Drupal::formBuilder()->getForm('Drupal\smeno\Form\FilterForm');

  $renderArray['filterform'] = $filterForm;
  $renderArray['McRefund_data'] = $this->getMcRefund();

  return [
    '#theme' => 'Remboursement-sur-compte',
    '#McRefund_build_data' => $renderArray,
  ];
}

As you can see within this block, I render a form and data (McRefund_build_data) which I put in a table(couple of Divs). The purpose of the form is to filter the data and put the response back in the block so that the block get rendered with the new filtered data. For this process I want to use AJAX to avoid the page from being reloaded.

I tried adding this on buildForm().

$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('OK'),
  '#button_type' => 'primary',
  '#prefix' => '
',
  '#suffix' => '

',
  '#attributes' => array(
    'class' => array('proximabold', 'tc', 'transition', 'no-underline', 'ph3', 'pv2', 'mb2', 'dib', 'white'),
  ),
  '#ajax' => [
    // 'callback' => 'Drupal\smeno\Controller\RemboursementsController::filterRefunds',
    'url' => Url::fromUserInput('/filterremboursement'),
    'event' => 'click',
    // 'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => t('Verifying entry...'),
    ],
  ],
);

I added a route and a controller to handle the request and the response.

Route

filterRemboursement:
path: '/filterremboursement'
defaults:
  _controller: 'Drupal\smeno\Controller\RemboursementsController::filterRefunds'
  _title: 'filterRemboursement'
methods:  [POST]
requirements:
  _access: 'TRUE'

Controller

function filterRefunds() {
  ddl('HELLO WORLD'); //devel module debug messages (usefull for ajax requests)
}

This isn't working, though.

Remove the data table from the block

public function build() {
    $filterForm = \Drupal::formBuilder()->getForm('Drupal\smeno\Form\FilterForm');

    $renderArray['filterform'] = $filterForm;

    return [
       '#theme' => 'Remboursement-sur-compte',
       '#McRefund_build_data' => $renderArray,
    ];
}

and add it to the form (placed in a wrapper):

  $form['McRefund_data'] = [
    '#type' => 'container',
    '#attributes' => ['id' => 'table-wrapper'],
    'table' => $this->getMcRefund(),
  ];

Attach this ajax callback to a form element

          '#ajax' => [
            'event' => 'click',
            'callback' => '::updateTable',
            'wrapper' => 'table-wrapper',
            'progress' => [
              'type' => 'throbber',
              'message' => t('Verifying entry...'),
            ],
          ],

and replace the table in the ajax callback:

  public function updateTable(array $form, FormStateInterface $form_state) {
    return $form['McRefund_data'];
  }


Comment ID in Comment field I've added a custom static field to comments. This static field is custom php code but I need to access the specific comment ID using php code in it. So how can I get the comment ID for every comment in the static php field?

Thanks

In Drupal 7 you can use the below code to get all the comments of a node using node ID

 $nid = 2;
 // you can get nid
 // $node = menu_get_object();
  //  $nid = $node->nid;
    $comments = db_select('comment')
              ->fields('comment', array('cid'))
              ->condition('nid', $nid, '=')
              ->execute()
              ->fetchAssoc();
    foreach($comments as $comment) {
        print your comments here
    }

Also you can check below links
https://api.drupal.org/api/drupal/includes%21common.inc/function/entity_load/7
https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/comment_get_thread/7

In Drupal 6 you can use the comment_render() ;


How to change MENU_LOCAL_TASK title for the View and Edit tabs according to content type? I am trying to change the title ( tab text ) of the standard Drupal menu local task tabs 'View' and 'Edit'.  I want them to reflect the content type of the current node.  So on the page node/1234 ( which is a blog node, say ) I want the View tab to say 'View blog' etc.

I can change the text using :

$items['node/%node/view']['title'] = 'View blog';

in a hook_menu_alter() function, but I can't seem to get hold of the node itself to test what content type it is to vary the text.  The arg() function doesn't return anything within the hook_menu_alter() function for some reason ?

How do I do this ?

Thanks

hook_menu() implementations are cached so aren't executed for every page (can you imagine how bad that would be for performance?)

You can use the title callback property from hook_menu() to evaluate a title on each page load, e.g.

$items['node/%node/view']['title callback'] = 'MYMODULE_title_callback';
$items['node/%node/view']['title arguments'] = array(1);

...

function MYMODULE_title_callback($node) {
  if ($node->type == 'foo') {
    return 'bar';
  }
  else {
    return 'baz';
  }
}


How do I associate multiple users to a node? Let's say we have a node as a School class, and I'd like to assign users (students) to that particular node. I have seen couple of modules (signup) or (user reference) but I'd like to make it much simpler and just assign those users to that node somehow. is there any easy way of doing this without using CCK or other modules?

User Reference sounds perfect for what you are trying to achieve. Not much is simpler than being able to select the users in the edit node form. Can you describe what kind of GUI you would like to use to select the use


Display a view block on multiple pages I have a block that I want to display on /group/*. That is working, but it is also displaying the block on /group/*/editwhich is pretty annoying and unwanted.

Is there a way to restrict that?

If you can't list all the groups' paths (if there are too many) you can use an extra module Block Exclude Pages.

Although when it comes to Edit pages it's customary to use the Administration theme for editing content instead of the default theme. This way the blocks meant to be displayed to visitors wouldn't appear when creating/editing content.

You can change this at the bottom of the Appearance page: Use the administration theme when editing or creating content.

You could also use a lot more complex solution depending on your project needs, like Context or Panels that take over the Blocks layout configuration and allow for a lot more control.


Show Content Type Fields from a entity reference I have a content type which i have linked to another content type. For e.g.

Companies (Content Type)
Employees (Content Type)

When creating a new employee i have to say which company it works for so in the Field Type i chose "Entity Reference and chose Autocomplete as the widget".

Now i have created a view which shows a list of all the employees, in this view i can show the companies Name however i want to show the companies logo instead of the name.

How can i grab the fields from "Companies" and display them within the Employees VIEW?

Thanks in advance.

To show the Parent info (Company) through Child nodes (Employee) you need to add the Relationship for the Entity Reference field that is connecting the child to the parent.

Once you add that Relaionship you will be able to add the fields from the Company CT. Those fields must use that Relationship to show the Company info, otherwise if you don't select the Relationship for a field it will show the original (Employee) info.

So after you add the Relationship for the Company ER field (that is on Employee CT), you will be able to add the Logo field to your Views, and that field will use the Relationship you've just added.


Get ID in HOOK_preprocess_container I'm currently working a styling of a drupal 8 website. And I'm trying two things.

In HOOK_preprocess_container I want to output a block, I got the block script figured out but I want to filter and output only when the Container ID matches a certain ID. Can someone help me out with this?

Thanks in advance.

My current HOOK:

function HOOK_preprocess_container(&$variables) {
  //something like this
  $containerID = //get container ID;

  $block = \Drupal\block\Entity\Block::load('block_id');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

  if($containerID == "containerID"){
    $variables['containerblock'] = $block_content;
  }
}

You should be able to get that with:

$container_id = $variables['element']['#id'];


features issues not overriding I have a feature that I copied from site A to site B. Site B is created using a profile install based on site A. Now I have to enabled a feature that I copied from A to B but whenever I enable this feature I always "overrides". I revert to the feature but it's always overriding. It's usually the field_base portion that has overrides. I have more than one feature that does this.  I dont want to recreate using DB settings. I want the feature settings. Any help would be appreciated. Thanks.

it was the actual features module itself. The latest version removed foreign keys which caused the overridden to be permanent.


Passing HTML to the response object I had this piece of code in a module developed for some previous version of Drupal 8.

protected function getOutput() {
    $content = $this->buildContent();
    //print_r($content);
    $page = array(
      '#theme' => 'html',
      '#page_object' => new Html(render($content)),
    );
    $rendered_page = render($page);
    return $rendered_page;
}

Now, in the present beta release, it shows this error:

  Fatal error: Class 'Drupal\hardcopy\Plugin\Html' not found in C:\xampp\htdocs\drupalbeta7\modules\custom\hardcopy\src\Plugin\HardcopyFormatBase.php on line 175

Can someone tell me how to pass the HTML of the whole page in the response object?

As D8 uses Symfony responses it's as simple as:

use Symfony\Component\HttpFoundation\Response;

...

$response = new Response(
  'Your HTML content here',
  Response::HTTP_OK,
  array('content-type' => 'text/html')
);

return $response;

See the docs for more information.


Programatically retrieve a block and print it in a page I have a form, generated by the Webform module, which is available as block. Now I want to retrieve the form itself and print it in a page.

How can I achieve this, programmatically? I'm using Drupal 7.

I'm not sure on which page you want to print the block. This is an example that prints the block in a custom page.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['my/page/path'] = array(
    'title' => 'Block in A Page',
    'page callback' => 'mymodule_block_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * The page callback which display the block
 */
function mymodule_block_page(){
  $block = module_invoke($module_name, 'block_view', $delta);

  return $block['content'];
}

hook_menu() registers a menu path which will display the block. mymodule_block_page() is invoked when the menu path is accessed like http://example.com/my/page/path.

module_invoke($module_name, 'block_view', $delta); will return the block ready to render. Please find out the module name and delta. I guess $module_name would be webform. If you go to the block configuration, e.g. admin/structure/block/manage/comment/recent/configure, the module name is comment and the delta is recent.

If you want to print the block on every page except the front page, create a variable in hook_preprocess_page() of template.php.

function MYTHEME_preprocess_page(&$variables) {
  if (!drupal_is_front_page()) {
    // It is not the front page.
    $block = block_load('module_name', 'block-delta');
    $variables['myblock'] = _block_get_renderable_array(_block_render_blocks(array($block)));
  }
}

In page.tpl.php, you can place the following code snippet where you want.

<?php if (isset($myblock)): ?>
  <?php print render($myblock); ?>
<?php endif; ?>


Entity reference multi-select I'm trying to make an entity reference field a multi-select options select but I can't seem to find out how to make that happen. Any help is appreciated. Below is the code I'm using.

$fields['some_field'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Some Field'))
  ->setDescription(t('This is a field.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'other_entity')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [
      'options_select' => 'multiple',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(FALSE);

Ultimately this was answered in a different but similar question I asked. The answer is the code below attached to the field in my entity.

use Drupal\Core\Field\FieldStorageDefinitionInterface;

->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)


How can I integrate the job news API into my site to access data through the API? I want to integrate the API of job news to display news of different companies. I need to let my system access the data through the API.

How can I integrate it with my website? Can anyone help me by telling me a way or giving some idea for the integration process?

With Feeds module you can import data from other sources to your Drupal installation. I would create a new content type for the jobs, and import the data with Feeds module into this newly created content type.


Database get uid for menu creator I just want to get the user information who create a new menu item under menu section.  I am not able to get any entry in database regarding the menu creator (UID). There is a entry in {menu_links} table, but in this table or any other table there is no UID linked.

Create a custom module and use the hook hook_menu_link_insert. Get the active user with global $user; and save the user + link id in a separate table.


How can I replace a value already present in the database? Is there a way for db_insert() to overwrite existing entries?

As @kiamlaluno mentioned db_insert() inserts a new row in the table. You can use db_update(), to update the row if it already exists. You can use db_merge(), to combine both of them.
See the example (taken from the documentation):

db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
    ))
  ->execute();

  In the above example, we instruct the query to operate on the "example" table. We then specify one key field, 'name', with a value of $name. We then specify an array of values to set.

  If a row already exists in which the field "name" has the value $name, then fields field1 and field2 will be set to the corresponding values in that existing row. If such a row does not exist, one will be created in which name has the value $name, field1 has the value $value1, and field2 has the value $value2. Thus at the end of the query, the end result is the same regardless of whether or not the row already existed.


Router can't find route in LanguageNegotiation plugin route name I'm having to write a new LanguageNegotiation plugin for an API because the language is not the first part of the URL (it's the third). But D8 refuses to recognise the route to the plugin for the config menu item.

I have been following the Language module itself as a model and there is no other mention of an equivalent route name for any of the other LanguageNegotiation plugins. I have tried replacing 'doublespeak' with 'language' in the route name (no change).

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "doublespeak.negotiation_api_url" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()

So the doublespeak.routing.yml looks like this:

doublespeak.negotiation_api_url:
  path: '/admin/config/regional/language/detection/apiurl'
  defaults:
    _form: 'Drupal\doublespeak\Form\NegotiationApiUrlForm'
    _title: 'API URL language detection configuration'
  requirements:
    _permission: 'administer languages'

And the start of the plugin is this:

namespace Drupal\doublespeak\Plugin\LanguageNegotiation;

use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Url;
use Drupal\language\LanguageNegotiationMethodBase;
use Drupal\language\LanguageSwitcherInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class for identifying language in an API URL via an infix value.
 *
 * @LanguageNegotiation(
 *   id = \Drupal\doublespeak\Plugin\LanguageNegotiation\LanguageNegotiationApiUrl::METHOD_ID,
 *   types = {\Drupal\Core\Language\LanguageInterface::TYPE_INTERFACE,
 *   \Drupal\Core\Language\LanguageInterface::TYPE_CONTENT,
 *   \Drupal\Core\Language\LanguageInterface::TYPE_URL},
 *   weight = -10,
 *   name = @Translation("API URL"),
 *   description = @Translation("Language from an API URL (/api/<channel>/<market-language>/refdata/<>)."),
 *   config_route_name = "doublespeak.negotiation_api_url"
 * )
 */
class LanguageNegotiationApiUrl extends LanguageNegotiationMethodBase implements InboundPathProcessorInterface, OutboundPathProcessorInterface, LanguageSwitcherInterface {

I've tried all sorts of options but can't make it work, and yes, I've cleared caches :-)

Okay, the problem was not in either of these two files.

As suggested by @Berdir I checked the router table and found that my route was not there. However there is nothing wrong with the file.

So the problem must be somewhere else. What if a bad class/method reference could cause this?

As an experiment I replaced the '_form' property with one that was known to work and cleared the caches. Suddenly the route was there in the table.

Checking my Drupal\doublespeak\Form\NegotiationApiUrlForm file I discovered that in my copy/paste haste I hadn't changed the namespace so the form class effectively did not exist. And the route was not loaded into the table.

Fixed. (Phew.)


Display Date field in email body with rules module On this page I have a registration form. The registration form is send to an e-mail address with Rules module.

The related event (Content type 'Event') has a Date field (Wanneer/When), the Date of the event.

How do I display the Date field in the e-mail body? When I put [entity-fetched:field-event-date] in the e-mail body, it's not displaying any Date?

i had a wrong date field. It should be entity-fetched:field_event_date. Now its working.


How to Send an email with the list of products ordered in its body? I created a rule and a component, to send an email to my customers 7 days after their orders. This email asks them to leave a comment on the products they have purchased.

My problem: I can not retrieve the list of products in the email. With [order:commerce_line_items], the e-mail displays "No order items found".

Here is the export of my rule :

{ "rules_schedule_follow_up_email" : {
    "LABEL" : "Schedule follow-up email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "processing" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_send_follow_up_email",
          "date" : "now",
          "identifier" : "Follow-up email for [commerce-order:order-id]",
          "param_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

Here is the export of my component :

{ "rules_send_follow_up_email" : {
    "LABEL" : "Send follow-up email",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "order" : { "label" : "Order", "type" : "commerce_order" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : "[order:mail]",
          "subject" : "Votre avis nous int\u00e9resse",
          "message" : "[order:owner],\r\n\r\n\r\nvous recevez ce courriel car vous avez r\u00e9cemment fait un achat sur notre site. Nous aimerions avoir votre avis sur les produits que vous avez command\u00e9.\r\nC\u0027est simple et rapide, il vous suffit de cliquez sur les liens ci-dessous :\r\n\r\n[order:view-url]\r\n\r\n[order:commerce_line_items]\r\n\r\nMerci pour votre retour d\u2019exp\u00e9rience. Nous appr\u00e9cions le temps que vous prenez et nous l\u0027utiliserons activement pour am\u00e9liorer notre boutique. \r\n\r\n\r\nCordialement,\r\nL\u0027\u00e9quipe [site:name]\r\n[site:url]\r\n\r\nPour rester inform\u00e9 des nouveaut\u00e9s et b\u00e9n\u00e9ficier de nos offres promotionnelles, suivez-nous sur :\r\nhttps:\/\/www.facebook.com\/S1biosecom\r\nhttps:\/\/twitter.com\/S1biosecom\r\nhttps:\/\/plus.google.com\/+S1biosecom\r\nhttps:\/\/www.pinterest.com\/S1biosecom\r\n\r\nPS : ceci est un mail automatique, merci de ne pas y r\u00e9pondre.",
          "language" : [ "order:owner:language" ]
        }
      }
    ]
  }
}

I want to display in my email, the links to the product pages ordered by my client. How can I do so?

If what you're looking for (= the list of products) is not available, then just (a) make it available first and (b) wait with your Schedule Rules Component action (to send an eMail) until it is available. Read on for more details ...

The trick to do so is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

Add some new Rules variable that will be used later on as part of the eMail body, before the Rules Action to schedule the Rules Component. Say you name the variable prod_list_var_for_email_body.
Add a loop to iterate over the list of links to the product pages. Within that loop, for each iteration, prepend or append the value for each list_item to that variable prod_list_var_for_email_body (see where we're going???).
Make sure that the Schedule Rules Component action is your last Rules Action, after the loop completed. And finetune the details (configuration) of your Rules Action to Schedule Rules Component. When doing so, you'll be able to select the token for file_list_var_for_email_body to include anywhere in your eMail body.

Easy, no?


How to send formatted html email using swiftmailer? How can I send styled html body using custom module to send an email. I am using swiftmailer module. With that I am able to send normal body, but I am not able to use html tags or css. How can I do this?

Swiftmailer only sends mails, it doesn't let you create HTML / plaintext content for emails.

I think that you want to use a module like mimemail to do this.

I came across this article that describes how to style mails send out using mimemail.

Theming HTML Mail sent through Mime Mail

This guide is made for Drupal 7, but the module has been made for Drupal 8 as well, so I think you might just create a mimemail-message.html.twig


Cloning content types and corresponding Display Suite settings I need to clone a content type, so I choose to do that with module: Bundle copy.

I need to clone Display Suite settings of my bundle as well. How would I clone that? (Found a patch that enables that with Bundle copy: https://drupal.org/node/2055157). Wondering is there any better solution?

Nevermind, found a solution:

Bundle copy version 7.x-2.x-dev allows cloning directly (without exporting/importing and changing bundle's machine name).
There is a patch that gives support for display suite cloning, exporting and importing. (I had to fix the patch first to be able to apply it with patch manager.)

All worked like a charm!


Facet Blocks are not appearing in indexed views I have created Index with apache solr server using search API.

Created a view using that index in page display and facets are appearing as rendered in side bar.

Now I Created another block display in the same view but now the facets are not displaying in the block display.

What would be the problem with block display and facets?

I figured out what the problem was... I rendered that block in sidebar region.. That was it..

When your search isn't the main content on the page then the facets does not appear now I rendered the block view it in Content Region.

Now the facets appear!!!


Creating linkable images using Flexslider and Slideshow View I am looking to create the ability to have my slider images link to link specified in my field_link. I have tried to put the node [field_link], but it is reading as plain text. I have tried a few suggestions, but I must not be doing them right.

Below you will find the current configuration I am using.

This is how I have set up my Slideshow View:

This is how I have set up my Image Field:

This is how I have set up my Link Field:

I have always had to modify the view template for the specific display to wrap everything in a link properly. The issue is compounded even more when using Picture for responsive image variations.

The custom template changes aren't extensive, but I've not found a re-usable or GUI based method to do this with sliders.


what's the difference between using js injector module and ['#attached']['js'] Please can any one tell me what's the difference between:

adding a java script to a webform using js injector module
And
adding it using Implements hook_form_alter() and $form['#attached']['js']

Technically the difference is very small.

Whatever js you add in $form['#attached']['js'] is added via drupal_add_js() when the form attachments are processed using drupal_process_attached() - just like the JS Injector Module adds js snippets using drupal_add_js().

The JS Injector page claims the js it serves is loaded last, so order is an aspect where the two approaches may differ, unless you do some manual adjusting of the loading order afterwards.

If you try to decide what to use - it really depends. If it is just a minor snippet you want to add, the injector has the advantage that you don't need to write an entire custom module just to add some minor js functionality. It might also be nice for front end designers who know js, but have little experience with php or writing modules. If the js to add is part of a larger module/functionality upgrade anyway though, there is little reason to make use of the JS Inspector Module.


Computed field value in twig template I use a computed field, to calculate and store a floating value for a node. Now I want to work with this value in a twig template. When I access the field value via {{ content.computed_field.0 }}it outputs the correct value, say 0.22. When I try to calculate with this value, i.e. {% set newvalue = content.computed_field.0 * 100 %} the page breaks (just pre-calculation twig content is outputted).

My first guess was that, for some reason, the field value is stored or read as a string (or another type?!). My DB says its a float and I don't know how to check a variable type in twig.

I tried to to use twigs number_format()-function : {{ content.computed_field.0|number_format(2) }}. This transforms the computed field to 1. I have no clue why this happens.
What am I doing wrong? Any tips or a workaround?

I use Drupal 8, Twig 1.25, and Computed Field 8.x-2.0-alpha3

Thank you in advance

You could try this, if your using a node template:
{{ node.computed_field.value * 100 }}


How to skip "Checked available update data for" all modules when I just want to update core or a specific module? I'm upgrading a lot of my Drupal sites to 7.32. Unfortunately it takes a lot of time for each site because of some update check that I don't need.

On How to upgrade only core with drush? I learned I can use drush up drupal to only upgrade core. But unfortunately drush is still checking a lot of statuses, which takes a long time for every site:

Checking available update data ...
Checked available update data for Administration menu.
Checked available update data for Admin VBO Views.
Checked available update data for Advanced CSS/JS Aggregation.
Checked available update data for Block.
...

How can I skip this? I just want drush to fetch 7.32, check if the site is still functional and head to the next site.

Drush calls Drupal code to update the list of available releases, so regrettably there is no way to update the release info for just some subset of available projects.


How to pass a custom object from a page to another page through a route or other means? I want to be able to pass a custom object of type FormMode through a route or any other way.

My custom.routing.yml file is:

custom.page:
  path: '/custom/{model}'
  defaults:
    _controller: '\Drupal\custom\Controller\CustomController::page'
    model: ''
  requirements:
    _permission: 'administer site configuration'

My FormModel class looks like:

class FormModel {
  public $name;
  public $area;

  function __construct($name, $area) {
    $this->name = $name;
    $this->area = $area;
  }

I create an instance of the object and use Drupal URL function like shown below:

$model = new FormModel('name', 'area');

Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model));

but Drupal throws an error saying Drupal cannot convert a object to a string which I understand it cant convert object to string.

What would be the best practice to pass a object through a route or pass object created from a form into a controller? I dont want to create an entity as I would then need to update the database with the new fields.

Thanks

You are passing the object, but you need to pass the object ID. So you will change this:

Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model));

To this:

Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model->id()));

Note that your model object will need to have a public id() method that returns the ID for this to work. This will send the ID that is passed in place of {model} to the callback.

If you want the callback function (the controller) to receive a loaded object rather than just the ID, you'll need to do a few things. The first is to add options to your route:

custom.page:
  path: '/custom/{model}'
  defaults:
    _controller: '\Drupal\custom\Controller\CustomController::page'
    model: ''
  requirements:
    _permission: 'administer site configuration'
  options:
    parameters:
      model:
        type: model

Then you'll need to set up a new route in services.yml:

services:
  model:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

And you'll need to create the class (Drupal\mymodule\ParamConverter\MyModuleParamConverter) that does the conversion from ID to object. This class needs to implement ParamConverterInterface:

namespace Drupal\mymodule\ParamConverter;

use Drupal\Core\ParamConverter\ParamConverterInterface;
use Symfony\Component\Routing\Route;

class MyModuleParamConverter implements ParamConverterInterface {
  public function convert($value, $definition, $name, array $defaults) {
    // Create your Model object here (not shown) then return it:
    return $model;
  }

  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'model');
  }

}

You can read more about parameter upcasting here: https://www.drupal.org/docs/8/api/routing-system/parameter-upcasting-in-routes


JS not work in bootstrap subtheme I am using bootstrap 3.6 sub-theme/cdn, I've added scripts[] = js/custom.js and I can see it in the source code of the page.

But... javascript is not working.
I copied some javascript code modules to test and from my custom.js and still does not work.

how I can run my code javascript in my sub?

To put a JavaScript in your theme you must do the following steps:

Assuming that your sub-theme name is example.

Update your example/example.info to have this scripts[] = js/custom.js. That means the custom.js path is example/js/custom.js.
Clear the cache.

Troubleshooting:

If your code in custom.js is not working then there is something wrong. First, check if there is a js error using browser console. Second, check the http response code make sure that there is no permission issue.

Alternative way to add Javascript.

Another way of adding Javascript is by using drupal_add_js. With this API you can control which page the js is going to load.