How to add class only to top level ul in main menu I am new to drupal theming.I want to add class only to top level ul in main menu.Using theme_menu__tree_main_menu() affect all the ul tag.I found this for adding class only to top level..https://www.drupal.org/node/988694
function THEMENAME_menu_tree__menu_top_menu($variables) {
 return '' . $variables['tree'] . '';
}
But it didn't work.Doesn't adding any class.Am I missing something?Please Suggest Me!!Thank

That example is missing some code.  Those two empty strings should not be empty.

There is a link on that page just above the code example to api documentation of theme_menu_tree() https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/7.x

On the api documentation page you can see it done correctly:

return '
' . $variables['tree'] . '
';


Q&A answers not publishing We are using Commons modules and among other parts of it a Q&A module. We noticed that when a user question is answered ,, answers do not get published. Not even when admin answers the question. Instead, we have to go in and set publishing options for all answers, one at a time.

The content type used for answers is called "Answers" and a default setting for publishing options is set to "published".

When the answer form is submitted the publishing option is not checked..

Does anyone know why this is getting overridden and how to make this work?

Thanks!

Recently I had a slightly different but similar issue with answers in commons. When a user answers a question it was by default visible to trusted contacts of that user but not visible to group members and there was no way to change that even as an admin.
After spending quite some time, I tried disabling the commons feature "Commons Trusted Contacts" which solved the problem.

So, one thing is clear it is this feature/module which is overriding. If you don't need trusted contacts functionality, you can just disable this. Otherwise, Commons trusted contacts is the right place to look into to solve the actual cause.


Add new content to an existing view As I have stated in my last few questions, I have almost zero knowledge on Drupal. I have just been given access to a website and told to make changes. So please bare with me and excuse my ignorance. View the below link:

http://www.ascoworld.com/about-us/our-people/leadership-team

The section with the photos and names/titles seems to be a "view"? I have found the edit page (see screenshot). All I am trying to do is add more people. How would I do this? I can seem to add more fields but that just adds to the existing people and not new ones. Any help would be greatly appreciated.

Thanks!

EDIT: Updated the link to live site. Apologies.

According to the View, to add more people into this display you need to adhere to the filter criteria the View is filtering on.

So, it looks like you need to:

Create a new node of Leadership Team
Fill out the fields
Set the 'Role' field to Leadership Team
Set the node to to published

You should now see it show up in the list.


Commerce Recurring framework with customizable products I understand that one of the field's from the recurring framework need to be part of the product and by extension a rule needs that to create a recurring entity by getting the products that have recurring field in them.

I had added the recurring field in the line items types that are of the type add to cart, so that the customer can pick what kind of recurrence they want instead of adding it to the product. These type of fields do not get picked by the Get Recurring Product action in the rules and no recurring entity is created.

Any advice on how to make this work so customers can decide the period rather than the store providing different subscription options by creating that many products?

Make a version of the product for each period:

Toothbrush (Monthly)
Toothbrush (Quarterly)
Toothbrush (Bi-annual)

etc.

Then, add each of those products to the product reference. Your customer will then be able to choose which subscription they want.


When to use a php function vs a drupal_ equivalent function? I come from update my Coder module to the v1.3 and when I go to check one custom module I see the following message:

  Line 71: in most cases, replace the string function with the drupal_
  equivalent string functions

$node_type = substr($form_id, 0, -10);

  Line 187: in most cases, replace the string function with the drupal_ equivalent string functions

$info->language = ($info->language == 'und' || empty($info->language)) ? t('Undetermined') : ucfirst($info->language);

So, why I need to use the drupal_substr() and drupal_ucfirst() in this case? And in general why to use the drupal_ equivalent functions when we have the php functions?

Most PHP string function don't handle unicode characters. For this you need to use their mb_* variants, which are (were?) not always available on some host. The drupal_* variants ensure unicode compatibility. They wrap mb_* functions and provide pure PHP implementations for when they are not available.

So, this recommendation is there to ensure portability of your code across hosts.


Is there an easy way to update img src attributes when moving to a new server? I recently copied my site from the dev server to a test server, and I noticed that a lot of images which were placed using the Media module have src= attributes that point to the old server.  Ie., <img src='http://oldsite.com'...> I don't see any settings within the configurable options for the Media module which will update the links.

I know that WordPress has a handy link updater plug-in called Velvet Blue, or something like that.  Does anyone know of a similar module for Drupal?

What you are looking for is the Pathologic module.

  Pathologic is an input filter which can correct paths in links and
  images in your Drupal content in situations which would otherwise
  cause them to “break;” for example, if the URL of the site changes, or
  the content was moved to a different server.

Cheers,


How can I disable "Delete the account and its content"? On the Cancel account page, is it possible to disable the option "Delete the account and its content"?

Some roles have the permission to cancel user accounts, but they should not have the option to delete the user's content.

You can implement hook_form_alter() in a custom module or theme to either remove the radio button entirely, or disable it which grays it out. You'd need to add additional logic to check the role of the user and disable it appropriately. I've shown both examples in the code example below, just uncomment the one you want to use.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user-multiple-cancel-confirm') {
    // Set '#access' to FALSE to remove the radio button.
    // $form['user_cancel_method']['user_cancel_delete']['#access'] = FALSE;

    // Set '#disabled' to TRUE to disable the radio button.
    // $form['user_cancel_method']['user_cancel_delete']['#disabled'] = TRUE;
  }
}


How do I get the cache string? In Drupal 8, CSS files, images and many other files, are cached by appending a token at the end, as in /sites/default/files/styles/lrg_thumbnail/public/p2i-product_1_zoomout.png?itok=DroPCbms.

Notice the itok=DroPCbms part.

What Drupal function returns this code?

Contrary to CSS/JS the itok is not for caching, but for DoS protection, see this question
Why are tokens added to image URLs?

The token is generated in
https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Entity%21ImageStyle.php/function/ImageStyle%3A%3AgetPathToken/8.2.x


Need a current page's "Content Type" passed to a node.html.twig template (for a different content type) on page load, AND after ajax call I'm trying to get the Content Type value of a node page (that the user is currently visiting - let's call it CT-1)... and feed that value as a variable into a DIFFERENT content type's node.html.twig template (CT-2). This CT-2 template is being used in a View output, displaying on a CT-1 page. Here's my code...

function custom_mods_preprocess_node(array &$variables, $hook) {
   if ($node = \Drupal::request()->attributes->get('node')) {
     $variables['pageNodeType'] = $node->getType();
   }
 }

Then I print out the pageNodeType variable into CT-2's node.html.twig template like so...

{% if pageNodeType == 'TYPE' %}

TEST

{% endif %}

This all works perfectly on page load. But when the view output is filtered with AJAX (via an exposed filter), pageNodeType becomes NULL, and therefore the "if statement" breaks with the CT-2 template.

What can I do to keep that variable active after an ajax update?

I tried leveraging..

\Drupal::request()->headers->get('referer');

..to pull the previous page, but it seemed like quite a task to get the Content Type via this approach. Is there a better way.

Thanks!!

Edit: May be related to this post as well... but no answers? Views with ajax get current node in hook_views_query_alter

Well, here's what I came up with... and it's working as needed. If there are issues with this approach, please feel free to critique. My backend skills leave much to be desired. Thanks!

function custom_mods_preprocess_node(array &$variables, $hook) {

// Get the current page's content type on page load
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $variables['pageNodeType'] = $node->getType();
}

// Keeps the type available if an AJAX call happens
if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
  $previousUrl = \Drupal::request()->headers->get('referer');
  $fake_request = Request::create($previousUrl);
  $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
  if ($url_object) {
    $route_params = $url_object->getRouteParameters();
    $ent_id = $route_params['entity_id'];
    $node = \Drupal\node\Entity\Node::load($ent_id);
    $variables['pageNodeType'] = $node->getType();
  }
}


Change width of editable in views I am using Editable views for fast editing of fields that change a lot.
It works fine but the edit field is way to long.
I think it must be fixed with css but I don't know how.
I am using the Corolla theme.
When I use de chrome inspector on that fields this is the result:

block input.form-text, .block input.form-password, .block input.form-file {
max-width: 400px;
width: 100%;
}

When I change the width value it has effect but it will effect al input fields with those css classes. So that is not the solution.
I tried to add a css class in field settings in de view module. I called it editable_fields and I have added it to forms.css and corolla.settings.style.css with this line:

editable_fields {
width: 30%;
}

but it has no effect.

Is there a way to make the field smaller?

It looks like this now:

I think I have the answer. If I use the id selector on this way I can control the specific fields:

[id^="edit-node"] {
    max-width: 100px;
    width: 100%;

Edit:

I was happy to fast, I want to control all of the different edit fields for the first fields it looks great, but for others it does not. The complete id of the first field is id="edit-node-431-field-aantal-und-0-value"
The "431" is a variable but also the "aantal".

The css rule above works for everything that starts with edit-node, but i want to add differente rules for different fields. I have tried to put a * or a ^ in de place of the "431" like this:

[id^="edit-node-*-field-aantal"] {
    max-width: 100px;
    width: 100%;
}

But that does not work. Any ideas?


Rewrite View field value I have a Views table that simply shows a list of Entities.

Now at the moment, field 'status' just outputs the raw data 0 or 1.

I want this to be rewritten as 'Pending' or 'Approved' respectively.

I've looked at rewrite behaviour but this seems to be limited and my requirements out of the scope. Everywhere people say that adding PHP through the UI is bad practice.

So how do people normally deal with select boxes stored as integers, when displaying the data using Views?

(Maybe there is a hook to create a function in my module that will always rewrite this field wherever it displays in the Drupal system?)

You could do this several ways, the easiest from a hook standpoint might be to use views_pre_render(), eg, something along the lines of...

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='THE_VIEW_YOU_ARE_LOOKING_FOR') {

     drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>'); // to see what you have to work with

     foreach($view->result as $r => $result) {
      if ($result->node_data_field_status_field_status_value) { // or whatever the $result field is you are looking to change from 0 or 1 to Pending or Approved
        $result->node_data_field_status_field_status_value='Approved';
      } else {
        $result->node_data_field_status_field_status_value='Pending';
      }
    }

  }

}


theme_hook process: calling a theme function not working(example from DGD7) I'm just working through an example module in DGD7. The module reports statistics about the themes. It displays this information in the help region on the appearance admin page.

I can't get it to display and I'm wondering if I understand the theming process correctly.

My understanding is this:

I call my function. (with a function)
My function returns data.
I tell drupal about my theme function with hook_theme
My theme function then turns my data into HTML.

Here's the module:

It uses a switch to call the function based on the path:

function xray_help($path, $arg) {
 switch ($path) {
  case 'admin/appearance':
   return xray_appearance_summary();
 }
}

Then this function calls data from a stats function which returns a compact. (the stats function works - tested with dpm())

function xray_appearance_summary() {
  $data = array();
  $data['themes'] = xray_stats_enabled_themes();
  return $data;
}

They give a theme function (I'll put it last because it's quite long) but don't show how to call it with hook_theme. I tried using this hook_theme to call the theme function:

function xray_theme() {
  return array(
    'appearance_summary' => array(
      'variables' => array(
        'themes' => NULL,
        'attr' => NULL,
      ),
    ),
  );
}

The theme function takes two variables $themes & $attr so I put both of those in. But I get the error.

Notice: Array to string conversion in menu_get_active_help() (line 1722 of C:\XAMPP\htdocs\drupal\includes\menu.inc).

Am I misunderstanding hook_theme?

function theme_xray_appearance_summary($variables) {
  $themes = $variables['data']['themes'];
  // Collapse attributes for paragraph tag to a string.
  $attr = drupal_attributes($variables['attributes']);

$output = '';
  $output .= "<p $attr>";
  $output .= t('This site');
  $output .= ' ';
  $output .= format_plural(
    $themes['num_themes'] - $themes['num_hidden'],
    'has only one theme available',
    'has @count themes available'
  );
  $output .= ' ';
  $output .= format_plural(
    $themes['num_hidden'],
    'plus one hidden theme.',
    'plus @count hidden themes.'
  );
  $output .= ' ';
  $output .= t('Of the non-hidden themes,');
  $output .= ' ';
  $output .= format_plural(
    $themes['num_enabled'],
    'one is enabled.  The enabled theme',
    '@count are enabled.  In the enabled themes,'
  );
  $output .= ' ';
  $summaries = array();
  foreach ($themes['summaries'] as $name => $info) {
    $summary = '';
    $summary .= $name . ' ';
    $summary .= format_plural(
      $info['regions'],
      'has one region',
      'has @count regions'
    );
    if ($info['overlay_regions'] || $info['regions_hidden']) {
      $summary .= ' ' . t('(including') . ' ';
      $summary .= format_plural(
        $info['overlay_regions'],
        'one overlay region',
        '@count overlay regions'
      );
      $summary .= ' ' . t('and') . ' ';
      $summary .= format_plural(
        $info['regions_hidden'],
        'one hidden region',
        '@count hidden regions'
      );
      $summary .= ')';
    }
    $summaries[] = $summary;
  }
  $output .= xray_oxford_comma_list($summaries);
  $output .= '.';
  $output .= '</p>';
  return $output;
}

EDIT ONE.

I've got rid of the error by changing the switch; thanks to Yuriy, but nothing still displays:

 case 'admin/appearance':
      $variables = array('data' => xray_appearance_summary());
      return theme('xray_appearance_summary', $variables);

First of all, your theme_xray_appearance_summary should be theme_appearance_summary, and should take $variables by reference: &$variables.

Second of all, hook_help() expects you to return a string, but your implementation returns the data from xray_appearance_summary(), which returns an array, thus the error you're getting.


How to create an entity reference view that contextually filters based upon current user ID I'm looking to create a entity reference view that filters based upon a field I've placed on the user profile.

I have two content types (Speakers, and Blog Authors) (Speakers will also be blog authors) that I want to as an available list of authors on a Blog content type, so on creation, the speaker can choose the author profile to link the particular blog to, but filtered by only those listed on a particular user's user account.

I've placed an entity reference field on the user account that is a link from a specific user to a specific piece of content of either the Speakers or Blog authors content type (called blog_author_link).

I'm looking to create a view that filters the entity reference field on the blog content type based upon which field is selected in a users profile.

I have a view that successfully lists both content types, but when I attempted to add a relationship from that user account link (blog_author_link), and contextually filter based upon Content:nid and set it to pull from the logged in user's id, it doesnt seem to work.  (Yes, There are users that have that attribute assigned, and I've passed those arguments and the filter results in no output).  I tried to do a uid, but I dont think that is available on the entity reference view type.  I'm a bit over my head.

Any Ideas?

EDIT:
Ok, so It seems based upon when I start passing random arguments into the preview's contextual filter that it is looking doing exactly what I'm telling it to do, filter based upon the NID, when I need to filter based on the UID,  but there is no contextual filter for the UID under Entity Reference Views type...  Any one have any idea what I'm talking about?

You need to add a relationship to the view. It will either be "node: author" or "content: author" depending on your distro/version (I'm commerce 7, views 3).

Once you've added the relationship, "User: Uid" will be an available option under contextual filters.


How to save an uploaded image in an admin form? I wrote the following module to upload a background image. My problem is, that my submit function is not called, though the pic is uploaded and showed in the block until the next cleanup is coming.The managed file table shows status 0...what should be 1 as far as i know.

Here is the Code of my Module: Whats the mistake?

function backgroundimage_block_info() {
    // This example comes from node.module.
    $blocks['backgroundimage'] = array(
        'info' => t('Background Image'),
    );

    return $blocks;
}
function backgroundimage_block_view($delta = '') {
    $fid_now=variable_get('backgroundimage');
    dpm($fid_now);
    $file_obj = file_load($fid_now);

    $bg_img_url = file_create_url($file_obj->uri);

    // This example is adapted from node.module.
    $block = array();

    switch ($delta) {
        case 'backgroundimage':
            $block['subject'] ="imagebackgroundblock";
            $block['content'] ="

";

            break;

    }
    return $block;
}
function backgroundimage_admin() {
    $form = array();

    $form['backgroundimage'] = array(
        '#type' => 'managed_file',
        '#name' => 'backgroundimage_image',
        '#title' => t('upload image, huh!'),
        '#default_value' => variable_get('backgroundimage', ''),
        '#description' => t("Here you can upload an image to the background!"),
        '#required' => TRUE,
        '#upload_location' => 'public://backgroundimage/'
    );

    return system_settings_form($form);
}
function backgroundimage_form_submit($form, $form_state) {
    dpm("yeah"); // is not being called!
    $form['backgroundimage']['#file']->status = FILE_STATUS_PERMANENT;
    file_save($form['backgroundimage']['#file']);
}

function backgroundimage_menu() {

    $items = array();

    $items['admin/settings/backgroundimage'] = array(
        'title' => 'Settings Background Image',
        'description' => 'Image upload',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('backgroundimage_admin'),
        'access arguments' => array('administer backgroundimage settings'),
        'type' => MENU_NORMAL_ITEM,
    );

    return $items;
}

?>

Thanks a lot!

You have used system_settings_form_submit() so you can add custom submit handler for your form by adding this code to your hook_menu

function backgroundimage_admin() {
    $form = array();

    $form['backgroundimage'] = array(
        '#type' => 'managed_file',
        '#name' => 'backgroundimage_image',
        '#title' => t('upload image, huh!'),
        '#default_value' => variable_get('backgroundimage', ''),
        '#description' => t("Here you can upload an image to the background!"),
        '#required' => TRUE,
        '#upload_location' => 'public://backgroundimage/'
    );
    $form['#submit'][] = 'backgroundimage_form_submit';
    return system_settings_form($form);

}


AJAX in Form API element returned in another AJAX callback I have a form like this:

$form['my_button'] = array(
  '#type' => 'button',
  '#ajax' => array(
    'callback' => 'my_callback_1',
    'wrapper' => 'some_wrapper',
  )
);

Which works fine (code is very simplified). Now, in the callback, I want to return another button, which also has ajax configured:

function my_callback_1() {
  return array(
    'my_other_button' => array(
      '#type' => 'button',
      '#ajax' => array(
        'callback' => 'my_callback_2',
        'wrapper' => 'some_other_wrapper',
      )
    ),
  );
}

function my_callback_2() {
  return array('#markup' => 'success!!');
}

Now, when I click on the first button, Drupal loads the second button just fine. The problem is, a click on the second button does nothing. Am I missing something?

After a lot of reading, I solved this by returning $form on the AJAX callback, and including the second button on a form rebuild. My code now looks more like this, and it's working fine:

function my_form($form, &$form_state) {
  $wrapper_id = drupal_html_id('some_wrapper');

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  if (isset($form_state['my_flag']) && $form_state['my_flag']) {
    $form['my_other_button'] = array(
      '#type' => 'button',
      '#name' => 'my_other_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      )
    );
  }
  else {
    $form['my_button'] = array(
      '#type' => 'submit',
      '#name' => 'my_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      ),
    );
  }
}

function my_form_submit($form, &$form_state) {
  switch ($form_state['triggering_element']['#name']) {
    case 'my_button':
      //code for when user presses the first button
      $form_state['my_flag'] = TRUE; //show the other button
      $form_state['rebuild'] = TRUE; //this is necessary!
      break;
    case 'my_other_button':
      //code for when user presses the second button
      break;
  }
}

function my_callback($form, $form_state) {
  return $form;
}

I think the problem had to do with a button being outside an actual form. I hope this helps others...


How to pass variables to OpenModalDialogCommand Drupal 8.
Clicking the upload button on Form1 should open UploadForm in a modal dialog.

/**
 * Callback to display a modal.
 */
public function ajaxSubmit(&$form, FormStateInterface $form_state) {
  $op = $form_state->getTriggeringElement()['#return_value'];
  switch ($op) {
    case 'upload':
      $modal = new OpenModalDialogCommand(
        t('Upload file(s)'),
          render(\Drupal::formBuilder()->getForm('UploadForm',
            $this->nid, $this->foo, $this->bar))));
      break;

    // ... other cases.
  }

  $response = new AjaxResponse();
  $response->setAttachments($form['#attached']);
  $response->addCommand($modal);
  return $response;
}

I'm not able to pass the variables to UploadForm. $this-> properties don't appear in UploadForm.

\Drupal::formBuilder()->getForm('UploadForm', $this->nid, $this->foo, $this->bar));

The form also fails if I replace the variables by local variables

$nid, $foo, $bar

But it works when I replace them by

'28', 'foo', 'bar'

The non-ajax version of the form uses a redirect to a form route (my_module.uploadform) and works OK.
Is there a way to pass the parameters to UploadForm?

Solved.
Thanks @kiamlaluno.
I was convinced the variables were OK. But after your comment and a fresh look I saw what I was missing:
$this->nid, $this->foo, $this->bar are optional parameters for the UploadForm formbuilder. I was passing only nid and bar, but missing foo, which messed-up things.
So, instead of:

\Drupal::formBuilder()->getForm('UploadForm', $this->nid, $this->bar) //don't need foo

I needed to call:

\Drupal::formBuilder()->getForm('UploadForm', $this->nid, null, $this->bar)

A bit obvious, I'm afraid...


Trouble setting up a search for a single field I am trying to set up a search that will only search a single field of a single content type. I am currently using search api with database search server module. I set up the search to index only this one field and a bundle filter that only returns results from the specified content type. The problem I am running into is the results.

If I set the field type to integer (it is a zip code I am searching through), it returns every search result regardless of if it contains the integer or not. If I set it to fulltext, it doesn't return anything regardless if i type an exact match to one of the fields it is indexing.

Am I setting this up right? Is there a better way to do this?

You can do this with Views.

Install Views.
Go to Structure>Views then + Add new view.
Set Show [content] of type [Your Content type here] (also tick Create a page) then Continue & edit button.
Under FORMAT select Show: Fields. Then under FIELDS click Add button and add the fields you want to show in the result. Then click Add button next to FILTER CRITERIA and add your zip-code field. On the settings screen of that field tick "Expose this filter to visitors, to allow them to change it".


Drupal and event on bootstrap modal I have a following problem.

I have a bootstrap modal with a form which I submit using jQuery. Upon sussesful Ajax I hide the form in the modal and append a message.

Now, when I close the modal and open it again I would like to have an empty form. Instead obviously I see the message. So I thought that I will use the bootstrap 'hidden.bs.modal' event to trigger the reoval of the message, showing the form and resetting it. The problem is that the event listener is never attached to the modal:

  Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
  //code starts
  $('#feedback-form').submit(function(e) {

    $('#feedback-form').hide().parent().append('

Please wait ...

');
    $.post("email_us.php",form.serialize(), function(data){
        $('#loader').replaceWith('

'+data+'

');
        $('#feedbackModal').on('hidden.bs.modal', function (e) {
                        $('#loader1').remove();
                        $('#feedback-form').show().trigger('reset');
                    });
        });
    e.preventDefault();
    })
  }
}

I do not see any error in the console it simply seems that the 'hidden.bs.modal' event listener is not attached to the modal.

Interestingly. If I execute this part of th code in console:

$('#feedbackModal').on('hidden.bs.modal', function (e) {
                    $('#loader1').remove();
                    $('#feedback-form').show().trigger('reset');
});

and then

$('#feedbackModal').trigger('hidden.bs.modal')

the modal and form behave as intended.

Any has an idea how to solve this problem?

This isn't exactly a Drupal question :)

Why not simply clear the form data as soon as you get to the AJAX success point?

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    //code starts
    $('#feedback-form').submit(function(e) {
      $('#feedback-form').hide().parent().append('

Please wait ...

');
      $.post("email_us.php",form.serialize(), function(data){
        $('#loader').replaceWith('

'+data+'

');
        $('#feedback-form').trigger('reset');
      });
      e.preventDefault();
  })
}

As far as I can see, if you modify the code like this, it will:

hide the form in preparation to post (no change)
post, and wait for success (no change)
show the success message (no change)
clear the form immediately (modified)

Does this solve the problem, or have I misinterpreted what you need in a big way?

To answer the specific question, it's not clear to me what the problem might be, but I'm suspicious that it's caused by the on event handler being attached inside the $post function's success function. Maybe try moving it outside as shown below:

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    //code starts
    $('#feedbackModal').on('hidden.bs.modal', function (e) {
      $('#loader1').remove();
      $('#feedback-form').show().trigger('reset');
    });
    $('#feedback-form').submit(function(e) {
      $('#feedback-form').hide().parent().append('

Please wait ...

');
      $.post("email_us.php",form.serialize(), function(data){
        $('#loader').replaceWith('

'+data+'

');
      });
      e.preventDefault();
    })
  }
}


What format are CCK dates stored in? In what format are CCK dates stored? If it stores dates in the database using a timestamp string instead of a native MySQL datetime format, what implications does that have in regards to storing dates before the unix epoch? Would it mean that CCK date fields would not be able to store something happening in year 1939, for example?

Date module provides three different formats, read about them here: Difference between date, datetime, and datestamp


Access denied: 'view published content' permission When I look into admin/people/permissions: 'View published content' is checked for anonymous users.

Yet the following code:

function test_menu() {
  $items['test'] = array(
    'title' => 'Test',
    'access arguments' => 'view published content',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

returns 'Accessed denied' when I navigate to /test as an anonymous user. I know I can do:

'access callback' => TRUE,

but the other code seems a lot neater. I've experienced this issue a few times before.

Thanks.

A quick look at node_permissions makes me think you should be using 'access content' as your argument, not view published content', as the latter is the proper machine name for the permission.


Problem assigning group members membership types other than default core 7.29
og 7.x-2.x-dev, also tested 7x-2.7

So, I'm going a little crazy trying to get users assigned a membership type other than default in an og.

I can create a new membership type no problem, and add fields. What I can't do for the life of me is find how to assign users to that membership type. The node 1 video made it seem like it shows automatically when adding/editing a user in a group (#overlay=group/node/1/admin/people/add-user), as roles do, but no dice. I realize that video is 2 years old, but it is the most helpful thing I can find on the subject.

Any thoughts/help?

Thanks,

Dan

You may want to use the rules module to accomplish that. It's pretty powerful and if you haven't used it before make sure to add it to one if your most favorite modules list. Here's some good advice that'll get you going  https://forums.acquia.com/acquia-products-and-services/dev-desktop/auto-assign-og-groups-user-roles


Marketplace fee on each product I am trying to create marketplace like etsy, where each user can add as many products as they want.

What i want to do is to globaly set a fee of 5% on each product.

So for example:
User creates product A with price of 10$.
After he clicks save price shown is 11$.

Simply add a Rule upon the event Calculating sell price of Product.  Multiply price by an amount is probably the Rules event you want to be using.


Drupal sends emails to Hotmail but not to other accounts I have a problem when Drupal sends email messages. I use the Rules module for doing it.

When the email is sent to a Hotmail account, the email is sent successfully; with other accounts (e.g. Yahoo, Gmail), the email is not received. The "recent log entries" shows the email as successfully sent, but the account doesn't receive it.

Likely the problem is not in drupal, but in server environment. You could use Drupal SMTP Support module to bypass this.


Can not access admin links I have encountered a weird problem in Drupal 6 in the recent days: I can log in as admin but none of the mysite.com/admin/* links work from GUI.

I still can use drush to enable and disable modules and do other administrative tasks but can not do the same from the admin menu.

None of the other aspects of the site are affected. I cleared all cache, updated the database, performed cron (using drush), and restarted all servers. Alas, no effect. The log messages are not helpful either.  I'm really perplexed and appreciate your help.

It turned out to be a problem with nginx/php5-fpm settings that timeout prematurely. When I use apache (using another port) the problem does not exist.


How can I programmatically get a list nodes that a user can update? I'd like to build a list of nodes which the current user is able to update. This is to be used in a site using Organic Groups.

My first hope was that there would be a Views filter that can check that the content is editable. Alas, no.

My second attempt was to use EFQ:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'suggested_listing')
    ->addMetaData('account', $account)
    ->addMetaData('op', 'update')
    ->addTag('node_access')
    ->pager(20);

would work, but it seems as though OG isn't setting the update column in node_access?

There should be a view filter like that, but you'll need to use a relationship (Access log: User should do it) then add the filter called User: Permission.


Override ctools function I'm using the Multi-Step Registration module to have a wizard in my user registration. The wizard works fine. You can also select a wizard trail to see in which step you are.

As you can see it displays that you can customize it by theming ctools_wizard_trail__step. Now the html code of the wizard is like this:

    Register »
    Geslacht »
    Politiek actief
    .......

This is what I've done so far in the function:

function mytheme_ctools_wizard_trail__step($html) {
    $wizard = $html['trail'];
    $steps = ['', 'geslacht', 'politiek_actief', 'beroep', 'vakgebied', 'berichten_ontvangen', 'nicknames', 'other'];
    for($i = 0; $i < count($steps); $i++)
    {
        $step_name = (string)$steps[$i];
        $wizard_html = (string)$wizard[$i];
        $wizard[$i] = "" . $wizard_html . "";
    }
    $html['trail'] = $wizard;
}

When I dump the $html variable on the first line of the function (before any operations) I get this result:

array (size=1)
    'trail' =>
       array (size=8)
          0 => string 'Register' (length=51)
          1 => string 'Geslacht' (length=51)
          2 => string 'Politiek actief' (length=58)
          3 => string 'Beroep' (length=49)
          4 => string 'Vakgebied' (length=52)
          5 => string 'Berichten ontvangen' (length=61)
          6 => string 'Nicknames' (length=48)
          7 => string 'Other' (length=44)

When I dump the $html variable on my last rule of the function I get this:

array (size=1)
   'trail' =>
      array (size=8)
         0 => string 'Register' (length=81)
         1 => string 'Geslacht' (length=89)
         2 => string 'Politiek actief' (length=103)
         3 => string 'Beroep' (length=85)
         4 => string 'Vakgebied' (length=91)
         5 => string 'Berichten ontvangen' (length=110)
         6 => string 'Nicknames' (length=87)
         7 => string 'Other' (length=79)

It looks the same but my wizard is gone ... . It's not added to my html.. .
What could be the problem of this?

You're not returning any markup from the theme function. The purpose of a theme function is to optionally accept some arguments and return markup. Here's an example of a theme function returning markup.

For more information see Overriding themable output.


Is it safe to manually delete the "field_deleted_*" tables and state API data? I'm in an odd situation where the state data that tracks which fields are deleted has a field in it that does not have its associated field_deleted_data_* table. As result, when cron tries to purge the deleted field data, an exception is thrown because it runs a query on a non-existent table.

Is OK to just delete all the remaining field_deleted_data_* and field_deleted_revision_* tables and then delete the two state API rows from the key_value table, field.field.deleted and field.storage.deleted?

Try deleting them cleanly first with drush eval 'field_delete_field("yourfield")' and run cron afterwards.


How to add selective js on the page load? I have initialized four js files in .info file.Now on a single page if i want to load only two of .js files not all ,how can i do this?

JS included in your theme's .info file will be loaded on every page, there's no option to make them conditional (that I know of).

If you have files that need to be conditionally loaded you should do so in your theme's template.php file (perhaps in a hook_preprocess_page() function), and use drupal_add_js():

function MYTHEME_preprocess_page(&$vars) {
  if ($some_condition) {
    $path = drupal_get_path('theme', 'MYTHEME') . '/path/to/file.js';
    drupal_add_js($path);
  }
}


Field with content entries from a content type I want to add a field (List text) to a content type, using as values the entries of another content type.

Should I use the References module?

No.
Fields can be reused between any content type. In node's field administration page, use the existing field and values you attributes you set to that field will be available in both node types. But you can have different field labels and descriptions.


Programmatically add a translation of month I need to add a custom translation of long form of months. The existing translation must be changed slightly.

One way to do it is via UI, however, not all months are available for translation yet (this is a new site). I would like to write a function in a module that would add all translations of months programmatically (and it would also be possible to use it on other sites). Is there a way to do it?

Use string overrides directly in either your settings.php file or through the string overrides module. See this note for specifics, this also lets you migrate this string overrides snippet from site to site either through simple cut and paste or through the string overrides migrate extension. This also deals with strings not yet known to the locale UI through t().

Example:

 $conf['locale_custom_strings_en'][''] = array(
   'January'      => 'New string 1',
   'February'      => 'New string 2',
 );


Is it possible to add custom entries to the language switcher pointing to the same language? I have a requirement to include Colombia, Peru and Mexico as part of the language switcher. Thing is these 3 countries all speak Spanish so is there a way to cater for this to include them in the language switcher? technically these three languages would have to point to the same spanish sub-domain

Thanks

I think you can use the hook_language_switch_links_alter() to modify the output of the language switcher. I would try to create the needed entries there to maintain the functionality to switch languages properly.


drush updatedb on multiple sites I have a multisite installation with common modules code (all modules are in sites/all/modules). When I update the modules, after that I need to update the database of each site with drush updatedb -l site.com
It is a time consuming task to do this for each site.
Is there a way to batch update the database in multiple sites?

Thanks

Here is a script I wrote for different time consuming tasks to run on a multisite installation

The file has to be in your sites folder.

The script will loop through all folders (except all and default) to run the command choosen on every sites based on their settings.php file

#!/bin/bash

# Get all Drupal sites
sites=`find . -maxdepth 1 -type d -print | grep -v '/all$' | grep -v '/default$' | grep -v '\.$'`

echo "Choose the commande to execute : "
echo "1. update"
echo "2. put sites offline"
echo "3. put sites online"
echo "4. clear all cache"
echo "5. clear css+js cache"
echo "6. clear specific cache"
echo "7. install specific module"
echo "8. disable specific module"
echo -n "Input [1,2,3,4,5,6,7 or 8] ? "
read choice

if [ $choice -gt 6 ] ; then
  echo -n "Extension (module/theme) name ?"
  read ext
fi

# For each site, execute the command
for site in $sites
do
  echo ----------
  echo $site
  cd $site
  if [ $choice -eq 1 ] ; then
    drush updatedb
  elif [ $choice -eq 2 ] ; then
    drush vset --always-set maintenance_mode 1
  elif [ $choice -eq 3 ] ; then
    drush vset --always-set maintenance_mode 0
  elif [ $choice -eq 4 ] ; then
    drush cc all
  elif [ $choice -eq 5 ] ; then
    drush cc css+js
  elif [ $choice -eq 6 ] ; then
    drush cc
  elif [ $choice -eq 7 ] ; then
    drush pm-enable -y $ext
  elif [ $choice -eq 8 ] ; then
    drush pm-disable -y $ext
  fi
  cd ../
done


create a node outside of drupal I have a situation where I need to create a node that is of a custom content type outside of drupal.

Is there anything involved besides inserting an entry into the node table and data into the content type table?

Unless you known exactly what you are doing, don't try to integrate with Drupal at the database level.

Drupal database schema is dynamic. Tables to store nodes information are added and modified when you add fields or change theirs settings. So your database query will need to be checked for every changes. This could easily become a maintenance nightmare.

Any module can, an many do, add custom behaviors on node insertions and updates through Drupal hooks system. Inserting content in the database without using Drupal's API would bypass these added behavior and potentially create inconsistent data.

If you must really do it outside Drupal, you can either bootstrap Drupal in your PHP standalone script to be able to use its API or use the Services module to provides a REST API for node CRUD operations.

To bootstrap Drupal in your PHP script, use the following code. Note that most of Drupal's code expect the current dir to be Drupal's one. Drupal also register its own session handler that may conflicts with yours.

chdir("/path/to/drupal");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Strange disappearing  problem with Drupal 7 In CKEditor, source view, I see
 tags around my paragraphs. That's great, makes sense. However when I view the node, the
 tags are gone, replaced with
 tags, thus killing the margins and cramming everything together. Re-editing the node brings the
 tags back again in CKEditor.

I have tried changing the text format to disable "Convert line breaks into HTML", but of course that just removed both
 and
 tags, making one huge paragraph.

How do I prevent this and preserve the
 tags?

Ah, I found it. In /admin/config/content/formats/filtered_html, I needed to add <p> to the list of allowed HTML tags way at the bottom of the page. I'm not sure how/why this problem didn't show up previously...but this solved it.


How to use user profile fields location fields in a rules component? I have a case where users will register with the site from foreign countries. I'd like to be able to let the admin know to update the geocoding settings for the country that they register from.

I'm working with rules, location and User-location, and Gmap. What I have so far is this:

{ "rules_email_admin_update_geocoding_" : {
    "LABEL" : "Email Admin to update Geocoding",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "site:current-user" ], "field" : "field_location_opt_out" } },
      { "AND" : [
          { "data_is" : { "data" : [ "site:current-user:field-location-opt-out" ], "value" : "0" } }
        ]
      }
    ],
    "DO" : [
      { "component_rules_send_email_to_admin" : {
          "subject" : "Update Geocoding Configuration ",
          "body" : "A new user [site:current-user] has registered with location information, check to see if the user\u0027s address is outside of the US and if the geocoding settings need to be updated to show the user on the map. Go to admin\/config\/content\/location\/geocoding and see if their country is configure. ",
          "from" : "admin@phisigmarho.org"
        }
      }
    ]
  }
}

This sends an email to the admin when the location-opt-out field is false, that is that the user entered location information. The issue is that I can't drill any further into the location information than the fact that the user hasn't opted out. This works ok for new users, but I will need to have another rule when a registered user updates their address. This leaves me with a problem, because I can't check the actual values in the locations fields.

So, what's the next step? can I access those values with a php snippet, and if so, how?

UPDATE: So, this appears to be an issue with how Rules interacts with the Fields API.Rules Fields

Install Countries module add field in your registration page.
when user register you can value of its location by selecting user country use this value in rules


Welcome email after user reset password in first time? When a new user signs up with the website the user receives an email with link to reset the password and when they reset the password first time, they get a welcome email but when in future they reset their password , they will not get that welcome email.How to resolve this.

You can do by using Login one time module

  Rules:

  [user:login-one-time] token on user events.
  [comment:login-one-time] token for node author on comment event.

  User profile - "Send login one time link" button.

  VBO - Create a view and send login links to the view. Checkout View
  Reference for ideas on how to embed views.

  Block - Select a user and send the link. You can use this block in
  nodes as a CCK field using Block Reference.

  PHP - Print a button in a template or directly send the emails using
  the functions described in the README.


How to run the Flags module after the Rules module? As a sequence on this question, I'd like to deduct 2 User Points when a user's first reaction on an Article is deleted (I mentioned my flag 'First reaction' there). I created a Rule 'Reaction removed' with the following settings:

EVENTS: After deleting a comment

CONDITIONS:

Comment is flagged Parameter: Flag: First reaction, comment: [comment], User on whose behalf to check: [comment:author]

ACTIONS:

Grant points to a user Parameter: User: [comment:author], Points: -2, Points category: Reaction, Operation: Delete, Moderate: Automatically approved
Unflag a Node: Parameter: Flag: Commented on a node, Node: [comment:node], User on whose behalf to flag: [comment:author], Skip permission check: false

I thought it looked all right, but it doesn't work, because apparently the comment is always handled as if it's unflagged, even when it's stored in the database as flagged with 'First comment'!

This is the Rules evalution log:

0 ms Reacting on event After deleting a comment.
11.674 ms Evaluating conditions of rule Reaction removed. [edit]
15.543 ms The condition user_has_role evaluated to FALSE [edit]
28.531 ms The condition flag_flagged_comment evaluated to FALSE [edit]  <--- going wrong here
28.547 ms AND evaluated to FALSE.
28.575 ms Finished reacting on event After deleting a comment

What went wrong and how can I solve it?

The problem arises because the Flag module runs before Rules, so it has already removed the flag before Rules performs its test. One way to deal with this is to install Modules Weight which will allow you to adjust the relative priorities of modules so Flag runs after Rules.


Cannot instantiate interface DrupalStreamWrapperInterface I am trying to replace drupal_realpath with realpath. What I did is

$stream_wrapper = new DrupalStreamWrapperInterface();
$file_path = $stream_wrapper->realpath($img_path);

But it gives me this error: Cannot instantiate interface DrupalStreamWrapperInterface. Any idea how do I use DrupalStreamWrapperInterface::realpath?

The error is because you are trying to create an object of a PHP Interface, which is not allowed in PHP. You can only create objects from a PHP Class.

To solve your issue, something like this might work:

$wrapper = file_stream_wrapper_get_instance_by_uri($img_path);
if (is_object($wrapper)) {
  $file_path = $wrapper->realpath();
}


Get number of items in cart of current anonymous user I need to get the number of items in cart of current anonymous customer on the site. I am using Drupal 7 and Drupal Commerce.

To load the current anonymous user cart, you can use commerce_cart_order_load something like this should suffice:

It gets the product count as separate line items and the product quantity including number of items per line item.

// Can leave blank or provide UID
$uid = 0; // anon
$product_count = 0;
$product_quantity_count = 0;

// Load cart order
if ($order = commerce_cart_order_load($uid)) {
  // Let's use the wrapper because it rocks
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // Loop over line items and increment product counter
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    // If line item is a commerce product type
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      // Increment counters
      // Individual product line item
      $product_count++;
      // Number of items of product line item (quantity)
      $product_quantity_count += $line_item_wrapper->quantity->value();
    }
  }

  // Debug output
  drupal_set_message(t('User %uid has %count products in cart with a total of %quantity items',
    array('%uid' => $uid, '%count' => $product_count, '%quantity' => $product_quantity_count)));
}


How to disable "add comment form" from a OG group content? When I'm showing content that belongs to a group I don't want to show the "comment form" to users that don't belong to that group. How can I do that?

Go to the group permission page, and uncheck the comment option for non-members.


How to create field instance with display none programmatically I tried to create some fields and field instance programmatically in .install file.

And I need to set a specail field instance with display none.

I have google, but got nothing.

Does anyone have a solution ?

your question is not very clear.

What do you mean "display none"?

Make your field in the .install file.
Add a CSS file to your module info filefiles[]=mymodule.css
in the CSS file of your module .field-myfield {display:none;}.
clear your drupal cache

EDIT

I think you probably want to look at Field Permissions module.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


How to print formatted contents of Viewfield in a custom template? I am having trouble printing the contents of two Viewfields in my custom node template. They are two separate blocks in the same overall View. I have tried the following, but it did not print anything:

<?php echo $node->field_fieldname1[0]['view']; ?>
<?php echo $node->field_fieldname2[0]['view']; ?>

When I add

<?php print_r($node); ?>

to my template, it returns the following for the two Viewfields in question:

  [field_fieldname1] => Array ( [und] => Array ( [0] =>
  Array ( [vname] => myviewname|block_1 [vargs] => ) ) )

  [field_fieldname2] => Array ( [und] => Array ( [0] =>
  Array ( [vname] => myviewname|block_2 [vargs] => ) ) )

Can anyone direct me on how I can print the contents of these Viewfields in my tpl file?

Thanks!

I used the following code:

<?php print views_embed_view('myviewname','block_1', $node->nid); ?>
<?php print views_embed_view('myviewname','block_2', $node->nid); ?>

And the view's info is printing just fine now in my tpl files. Hope this can help someone in the future.

Thanks for Worldfallz on the Drupal forum for this suggestion!
https://drupal.org/node/2075411#comment-7800227


How to make summary report views im trying to make a report in a view from other view(a table). i've tried view calculator and it's not what i want.

i want it like this :
Total people below 20 years old : xxx
Total Male : xxx
Total Female : xxx
Total people that have * : xxx

Can you make 1 View per report you want. Using Views aggregates and filter conditions you should be able to generate the values you want.

Then make 1 master View and use views attachments to build your single massive report page by showing all these reports in that page view.


Secondary menu links I have a main menu with links:
menu1
menu2
menu3
menu4

When entering the menu1 I want to display a secondary menu with links:
sub-menu1
sub-menu2
sub-menu3

and sub-menu1 to be activated as a default.
Every sub-menu has to have a separate page, because in every sub-page the wallpaper will be different.

When entering the sub-menu2, there will be different content, wallpaper, the chosen sub-menu will be activated and also his parent menu, in this case menu1.

How can I do this?

you can use menu_tree to override your menu :

try this code in your template.php :

function THEMENAME_menu_tree__MACHINENAME($variables) {
$menuTree = menu_build_tree('MACHINENAME');
$output = '
';
foreach ($menuTree as $item)
{
    $output .= '
' . $hasSub;
    if (count($item['below']) > 0)
    {
        $output .= '
';

        foreach ($item['below'] as $subItem)
        {
          $output .= '
' . $subItem['link']['link_title'] . '
';
        }
        $output .= '
';
    }
    $output .= '
';
}
$output .= '
';
return $output;
}


Entity Print Content Modification For Views I have a views that I am printing to PDF using Entity Print. The views is a combination of several entities and as such cannot directly utilize the instruction in the "Modify entity content" section of the documentation:

To modify the content of your entity, you
create a twig template using the 'pdf' view mode name (e.g.
node--article--pdf.html.twig). In this template you can modify the
markup as you normally do with other view modes using {{
content.field_example }} or {{ node.field_example }}.

See screenshot of the view:

I tried this twig template suggestion entity-print--views--machine_name--pdf.html and template variables like {{ content.field_bright_news }} (where the name of one of the fields of a referred entity of the view is field_bright_news) but that doesn't seem to work except I may be missing something.
Is the stated instruction in the documentation applicable to views as well or it's solely meant for actual entities. If yes, what is the correct template and variable pattern for this scenario ?

I don't think that your template suggestion is correct in this case, so {{content.field_bright_news}} may not work.
A few things I can clarify for you are as follows:
{{content.field_bright_news}} - this variable is only available in the template of the content type containing that field, it cannot be used in the view template.
For your quote, it is missing the following:

By default this module only installs the PDF view mode for Nodes. If you have any custom entities on your Drupal site and want to hide the "View PDF" link on those, you must first create a PDF view mode for the entity type. To do this navigate to "admin / structure / display-modes / view" and click on "Add view mode". In the list click the entity type for which you would like to create the PDF view mode. You'll now be asked to name the view mode, you can name it whatever you like but make sure the machine name is just "pdf", which will be automatically prefixed with the entity name. You can now follow the steps in the previous paragraphs for your custom entity.

That is, you must create a display mode for that content type to have a template suggesting as the form
node--content_type--display_mode.html.twig
And that means, {{content.field_bright_news}} can be used in the template suggested above.


preventing a date form element from displaying 'day', 'month', and 'year' labels? I have a D7 form with a date element on it. I want it not to display 'day', 'month', and 'year' elements. I looked at '#display_title' => FALSE but that doesn't work.

Can I disable the display in the form definition, or must I do this elsewhere?

I think the property you're looking for is #title_display, not #display_title. Also you wouldn't set it to FALSE but one of these:

before
after
invisible
attribute

In your case you'd want to set it to invisible:

$form['element']['#title_display'] = 'invisible';

That will render the label, so your form remains accessible, but hide it from display.


Redirect to referring page after form submission Trying to figure out how to redirect a user back to referring page after they have completed our feedback form. So a scenario would be if im on page foo/bar and I click on feedback webform link on that page. I then proceed to fill out the webform and then hit submit I will then be directed back to foo/bar page with confirmation message displayed at top of page. Webform module does give me an option to add in a custom confirmation URL and also the ability to add in tokens. However I have had no success with current tokens as none of them redirect me back to referring page.

Would creating a custom token maybe help with resolving this issue or hook_form_alter? Kind of stuck on how best to approach this.

You can't rely on the referrer header, because clients can refuse to provide one. For this use case Drupal has implemented a query parameter destination. Configure the webform with a default Confirmation URL, like <front>, and then add the current url as destination query string to links pointing at the webform.

For example add a feedback link to nodes:

use Drupal\Core\Url;

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mymodule_preprocess_node(&$variables) {
  $variables['content']['feedback'] = [
    '#type' => 'link',
    '#title' => t('Feedback'),
    '#url' => new Url(
      'entity.webform.canonical',
      ['webform' => 'feedback'],
      ['query' => ['destination' => Url::fromRoute('<current>')->toString()]]
    ),
    '#cache' => ['contexts' => ['url.path']],
  ];
}

This overrides the configured confirmation URL and returns to the referring page after the webform is submitted.

In a page template you don't need the cache context and you can use this Twig only solution, as @PaulH has suggested:

href="/form/feedback?destination={{ path('<current>') }}"


Why is page tpl not getting detected I have a view with page display's page setting as following:

Path: some/path
Menu: No Menu

However it was overridden in templates by page--some--path.tpl.php for styling purposes. This tpl actually overrides page--some.tpl.php which is a base tpl for all pages located at some/* path.

I have now been asked to change this the path to some/path2. I did the same in views page settings. And created a tpl file page--some--path2.tpl.php.

Problem is that this tpl file is not getting detected and Drupal is using page--some.tpl.php as the template.

Why so?

This is the snippet I wrote for  region--login.tpl.php try this once. Hope it meets your requirements.
in template.php

 <?php
 function yourthemeName_theme() {
   $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'yourthemeName') . '/templates',
  'template' => 'region--login',
   'preprocess functions' => array(
   'yourthemeName_preprocess_user_login'
   ),
   );
   return $items;
  }
  ?>


Trigger a Drupal behavior from another module in Javascript? The block_ajax module defines a behavior in its module:

https://git.drupalcode.org/project/block_ajax/-/blob/8.x-1.x/js/refresh_ajax_block_command.js

I want to initiate this call every 60 seconds so the contents of the block can refresh if there is new data from my own script file.

I tried two ways.

The first way I tried was setting up a route for a simple controller that returned an AjaxResponse:

  public function execute() {
    $response = new AjaxResponse();
    $response->addCommand(new RefreshBlockAjaxCommand('.my_block'));
    return $response;
  }

Hitting the route with Drupal.ajax results in 'context.querySelectorAll is not a function', but it appears that the block is replaced (but missing the block wrapper around it, oddly enough, which probably won't work calling it over and over).

The second way is I tried to call it from the browser console with Javascript, but I can't figure out between this answer and the linked Javascript file at the top of the question what to call.

Trying to loop the element and attachBehaviors results in this:

Hitting the route with Drupal.ajax results in
  'context.querySelectorAll is not a function.

This happens when Drupal.attachBehaviors() is passed a jQuery object. It expects an HTML string. So if you are doing this:

var element = $(".some_element");
Drupal.attachBehaviors(element);

You change it to:

$(".some_element").each(function () {
  Drupal.attachBehaviors($(this).eq(0));
});


File (Field) Paths serial token I have an image field type configured to accept an unlimited number of values.

Using the File (Field) Paths module I have set the file name field value to [node:title].[file:ffp-extension-original]

This is fine if you upload one image because it is renamed to my_node_title.jpg for example.

If you upload several images, they are renamed to my_node_title.jpg, my_node_title_0.jpg, my_node_title_1.jpg, my_node_title_2.jpg and so on.

Is there a token I could use or create that would allow me to add a serial value rather than the default _0, _1, _2? For example my_node_title_a.jpg, my_node_title_b.jpg, my_node_title_c.jpg etc.

I'm looking at the Custom Tokens module at the moment but not having much success.

The problem is it starts from 0, isn't it?

If you use that for your path: [node:title]_a.[file:ffp-extension-original]

my_node_title_a0.jpg
my_node_title_a1.jpg
my_node_title_a2.jpg

OR

You can use the [file:original:fid] pattern, it gives serial values but the fid increments for all the nodes, not for each nodes. I mean, if you upload 10 images to your first node and then for your second node if you upload 3 images, second node's images' names are as below:

my_node_title_a11.jpg
my_node_title_a12.jpg
my_node_title_a13.jpg


Why isn't the code in my implementation of hook_form_alter() being called? When I test to see if my form is called by checking for its $form_id, there is no output. Why is it that under the comment form it can't invoke the mymodule_ask_form?

/**
 * @Implement of hook_form_alter()
 */
function mycaptcha_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'comment_form') {
      mycaptcha_ask_form($form);
      echo 'test';
    }
  }

function _mycaptcha_get_ask($key = NULL) {

  $ask = array(
    'test 1' => 'example 1',
    'test 2' => 'example 2',
  );

  return isset($key) ? $ask[$key] : $ask;
}

function mycaptcha_ask_form(&$form) {
  $ask = _mycaptcha_get_ask();
  if (isset($_SESSION['mycaptcha_ask_key']) && $ask[$_SESSION['mycaptcha_ask_key']]) {
    $ask_key = $_SESSION['mycaptcha_ask_key'];
  }

  if (!$ask_key) {
    $_SESSION['mycaptcha_ask_key'] = $ask_key = array_rand($ask);
  }

  $form['mycaptcha_ask'] = array(
    '#type' => 'textfield',
    '#required' => 1,
    '#title' => 'tetst'.$ask_key,
    '#weight' => -1
  );
}

First of all - have you checked that Drupal sees your function at all, and calls it?

Then, have you tried printing out $form_id? As for default D7's content types (article and basic page) comment form ids are not "comment_form", but:

comment_node_article_form - for article
comment_node_page_form - for basic page


How to prompt user to download a file? How to prompt user to download a file in browser from custom module php code?

I tried first the php way

<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
?>

It silently fails. Then I realized there is a "drupal way" to do it.
So I tried

drupal_add_http_header('Content-Type', 'application/octet-stream');
drupal_add_http_header('Content-disposition', 'attachment; filename='.$fname);
drupal_add_http_header('Content-Length', filesize($fpath));

but still not working.
I think one possible reason for failure is that I am not sure at each step which is the correct path I should use.

Should it be
'/home/mysite/public_html/sites/default/files/pdfs/'.$filename.'.pdf'

or just the part that starts in the drupal root
'/sites/default/files/pdfs/'.$filename.'.pdf'

or even just
'public://pdfs/'.$filename.'.pdf'

as I see it in some other threads. I wonder why it has to be so complicated.

Have you tried the http://drupal.org/project/file_force Module ?
Some details from the module's project page:

File Force Download can be used to force the user's web browser to download the file to disk instead of displaying it in the browser window.
Web browsers today are pre-configured to render various types of media directly, such as text files, various image, video and audio formats, PDF documents, and Flash movies. While it is still possible to save such files afterwards by right-clicking on them and selecting "Save As..", it is sometimes desirable to just offer the file for download in the first place. File Force Download solves this issue by supplying a file with certain HTTP headers which instruct the web browser to download the file to the user's disk instead of displaying it in a browser window.

It should be a good starting point for inspiration for your own module.


How to use ungrouped date fields as data for Charts Views? I have a content type with the following date fields:

Start Date
Deadline Date
End Date

Deadline date is programmatically calculated, where as Start and End are based on user input.

There is a page with a table view for open nodes, ones without an End Date. In it, I would like to have a graphical representation of nodes alongside a graphical representation of time left from now until End Date.

I made a chart block view with serials as labels and dates as data, but the only result I got was a flat line with 0. Then tried every format combination listed under the date field without any luck. Although that, post date  as a field seems to return correct results(?).

For a specific node Devel listed the following:

created (String, 10 characters ) 1451882207

field_end_date (Array, 1 element)
    und (Array, 1 element)
    $...->field_end_date['und']
        0 (Array, 4 elements)
            value (String, 19 characters ) 2016-10-27 00:00:00
            timezone (String, 11 characters ) Asia/Riyadh
            timezone_db (String, 11 characters ) Asia/Riyadh
            date_type (String, 8 characters ) datetime

Creating timestamp fields gave the same flat line. So, I am unsure about what the exact issue is. Help would be appreciated on how to reach the desired outcome or about how to debug this if it is not a feature.

I'm using Charts version 7.x-2.x-dev.

I found a partial workaround for this by using hook_views_pre_render.

function hook_views_pre_render(&$view) {
   if($view->name == 'stuff'){
      $results = &$view->result;
      foreach ($results as $key => $result) {
      $now = time();
      $end = strtotime($result->field_field__end_date_[0]['raw']['value']);
      $daysuntil = date("j", $end-$now);
      $result->field_field_end_date[0]['rendered']['#markup'] = $daysuntil;
     }
   }
}

The previous function is  for a chart that displays node serials as x-axis labels and number of days for yaxis, which is calculated as the difference  between now and a end date.


Roster Views with User data plus office content type I'm creating a site that is an intranet portal for a company. All the users will be employees that work in different offices. I am adding several fields to the users to be used within the roster display. ie Cell phone, personal email, etc.

I will also have a content type of Office that will have fields relating to the individual locations. ie Address, phone, wifi code, etc.

I need to be able to display the full roster for any given office location. Views seem to be the way to go but getting the relationship between users and the offices is my problem. I know this is a pretty basic application but not something that I haven't done before.

What are possible ways to tie the office content type with the system users so that I can create a view that would have access to all of the fields from both content types?

Sounds like a perfect usecase for the Group module, whereas you'd use a group type like Offices. And so that you create 1 group (of group type Offices). From then on you have the Group permission system to configure access rules to fit your needs.

And BTW, this can be for either D7 or D8.


How to handle private file uploads and downloads? For a project I'm working on, I need to be able to:

Upload a file as Admin, assigning it to a user (this is working using the "author" field at the moment), attaching it to a node (ie. using the "FileField" field type)
Store the file in a private directory (not accessible by public users)
Allow the Admin and "author" users to download the files

We've setup a test project using Drupal 7 with a FileField on a custom content type. The FileField is set to use "Private" uploads.

What seems to happen is that the files are not accessible by their path on the disk (e.g. http://sitename.com/sites/default/files/filename.pdf) but are accessible by the Drupal private file download path (e.g. http://sitename.com/system/files/filename.pdf) - even when users aren't logged in, the private file download path still allows the file to be downloaded.

What we need to do is:
Stop users who aren't logged in, and aren't the author or admin of the node, from downloading the file from the private path.

We've already got a hook_node_view() in a custom module which stops people looking at the node if they don't have permission (i.e. the $user->uid matches the $node->uid) - it's just the private file path we need to hook and validate (check the user is accurate).

Any ideas what we're doing wrong?

If the whole node should only be visible to the author, then you should either implement hook_node_access() yourself and correctly deny view access or use a content access module (e.g. Content access) to do that for you. Note that hook_node_access() won't prevent that now to show up in listings, for that you need a content access module (or implement one on your own).

Alternatively, if you just want to hide the field, you could use the Field permission module and configure it accordingly.

Both ways should be able to to this because it is something that Drupal can check, it can't know that you prevent access in hook_node_view().


Listing content inside an OG based on a tag name provided in the URL I have a site divided in 4 organic groups:

Product
Corporate
Data
Users

Users belonging to a group are able to post content in that group as well as read it. Every group has its page accessible through the following URLs

example.com/product
example.com/corporate
example.com/data
example.com/users

in which an overview of the latest content published in  that group is shown inside a set of panels.

Every group has an specific vocabulary of 4 terms in order to subdivide content classification a little bit more.

THE GOAL IS:

I want to build some pages with page manager so that when a visitor types an URL like example.com/product/foo a page with the same design as the others is shown but filtering the contents inside that group to those tagged as "foo".

To achieve this I've started creating a page variant that would deal with requests in the form /product/%tag with the condition that %tag is a term in the "product" group vocabulary.

Up to this point, this works. When a user browses to example.com/product/foo the page shows as it should, and when it browses to example.com/product/bar (bar is not in the vocabulary) a "page not found" message is displayed.

Inside the views manager I also created a content pane view with the contextual filter based on term ID that:

When the filter is not available displays all results.
When the filter is available

Specify validation criteria
Validator: Taxonomy term
Vocabularies: corporate, data, product, users
Filter value type: Term name converted to term ID
Transform dashes in URL to spaces...
Action to take if filter doe not validate: Display content of "no result found"

THE PROBLEM:

The preview works well in the view admin page when providing the contextual filters but when I try it on the actual page, the "no results" found content is show.

Is there something I have to do with the "Argument input" option inside the views admin page? Am I trying to solve this issue twice by using page manager and contextual filters (should I use only one approach)?

Ok, answer to my question is that when the filter is not available, I should provide a default value -> raw value from URL -> path component = 2

And check "use path alias" option to avoid using regular paths.

And also argument input = from panel argument (first).


Does $form_state['redirect'] require a rebuild? I'm working on a multi-step form, and one of the last steps is a confirmation page with a 'Continue' and 'Cancel' button. If they hit cancel, I want it to go to a whole other page.

I have a custom submit handler for the cancel button, but the functionality doesn't appear to be working. I have:

function hook_form_cancel_submit($form, &form_state) {
  drupal_set_message('Cancelled');
  unset($form_state['rebuild']);
  $form_state['redirect'] = array('another/page');
}

I don't want the form to be rebuilt after cancellation, but then I wonder how my redirect would get triggered, since it exists only in $form_state?

Form generation reports the following text:

  $form_state['redirect'] is used to redirect the form on submission. It may either be a string containing the destination URL, or an array of arguments compatible with drupal_goto(). See drupal_redirect_form() for complete information.

The function drupal_redirect_form() is called by drupal_process_form(), which calls it after executing the form submission handlers with form_execute_handlers().

if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
  // Execute form submit handlers.
  form_execute_handlers('submit', $form, $form_state);

  // ...

  // If batches were set in the submit handlers, we process them now,
  // possibly ending execution. We make sure we do not react to the batch
  // that is already being processed (if a batch operation performs a
  // drupal_form_submit).
  if ($batch = & batch_get() && !isset($batch['current_set'])) {
    // ...
  }

  // Set a flag to indicate the the form has been processed and executed.
  $form_state['executed'] = TRUE;

  // Redirect the form based on values in $form_state.
  drupal_redirect_form($form_state);

  // ...
}

In short, the form is not rebuild, before redirecting the user to a new page. The $form_state array that is passed to drupal_redirect_form() is the same array passed to form_execute_handler() (the difference is that the form handlers can add or alter values contained in $form_state).


elysia_cron setup for custom callback I have created a custom callback to perform some batch operation.
How can I set schedule for execution using elysia_cron?

Elysia cron has a hook specifically for that; hook_cronapi():

function hook_cronapi($op, $job = NULL) {
  $items['key'] = array(
    'description' => 'string',
    'rule' => 'string',
    'weight' => 1234,
    'callback' => 'function_name',
    'arguments' => array(...),
    'file' => 'string', // External file, like hook_menu
    'file path' => 'string'
  );

  $items['key2'] = ...
  ...
  return $items;
}

Taken from the API.txt file included with the module.


Annotations without class import? The idea of annotations in Drupal 8 is that annotations names map to classes.
E.g. @ViewsRow -> \Drupal\Views\Annotation\ViewsRow.

From other code I have seen (Symfony, Doctrine), I assumed that to make this work, the annotation class needs to be imported, e.g.

use Drupal\Views\Annotation\ViewsRow;

However, this seems not to be the case for many of the plugin annotations e.g. in Views.

Why? Is this a Drupalism, or would we find the same in some places in Doctrine or Symfony? Is it good practice to omit the import?

In the past I disliked the need for such use statements, because they would show up in the IDE as "unused import". However, now I am using the annotation plugin in PhpStorm, so now it recognizes those imports.

Drupal's annotation system is based on the Doctrine PHP library, and not on Symfony like the rest of Drupal.

Doctrine uses a global annotation registry to map classes to files (rather than an autoloader). This page contains the list of classes in that registry.

This issue from 2013 shows the Drupal maintainers' decision to remove the need to import annotation classes.

You wouldn't know this by looking at the official Drupal documentation -- they say the annotation classes are loaded "magically".


Print key value as a class along with the label for a list field? I have a node with a field which is a List (integer). I can print the value in node tpl with the following:

<?php print render($content['field_name']);  ?>

However I also need to style each result differently. For instance one of the options is 'large' and I want to add a background image to every 'large' result.

How can I do this? I was thinking if I could print the key value as a class along with the label the I could easily do the rest with CSS.

You should not actually want to do this in your node.tpl file. Drupal uses a system of (pre)processors to alter variables before they get rendered. That is where the logic should go.

Have a look at this topic that has a lot of explanation and references https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates

Once you have your output ready you should be able to do the styling with CSS.


In Views, how can I display an edit link if a node relationship exists, otherwise display an add link? I have a view of assignments, and want students to be able to post their work from that node. If they already have a work node, I want to display an edit link. Otherwise, I want to display an add link. In a previous version of this view, I used a Views PHP field that queried the DB for a work node matching the assignment, but I am rewriting the view because of a bug and I wanted to revisit this because it seemed a but ugly. Can anyone think of a better way?

I have had a similar situation and I did the following which is probably not the best thing to do - I will use your terms:

When an assignment node is created a work node for each student is created with the field field_submitted set to false
On the view, the field field_submitted is included but excluded from display
I have a php field with this code which displays edit or submit, both are actually sending to the same node but they will give the student some insight about what he should do next:

if(!empty($data->field_field_submitted[0]['raw']['value']))
   echo l(t('edit')/*, ... */);
else
   echo l(t('submit')/*, ... */);


Drupal Hide "Create Content" Page For clever auth users who know you have a drupal site, they can type in "node/add/whatever" into your site and the page, "Create Content" pops up with all the links to the content that user is allowed to create.

I wish to hide this specific page. I found one way, not too practical, though. You would theme the "page-node-add.tpl.php" to redirect to 404, but then you need to manually add page-add themes for each content type for those links to work. Ugh.

I think the best way is to create some theme function to read if the page title is "Create Content" then redirect to 404.

Does anyone have any insight? Code? Cheers!

I put this in a comment already, but here are some more detailed instructions on how to set up permissions to restrict access to content types.  I assume you are using Drupal 7; if you're still on Drupal 6, the exact sequence of clicks will be different, but the basic approach is the same.

Log in as an administrator.
Click People in the nav bar at the top.
Click the Permissions tab (top right of the People overlay).
Click the Roles sub-tab (immediately below Permissions tab).
Add a new role using the text box at the bottom of the overlay.  For example, "editor".
Click the "Permissions" sub-tab immediately to the left of Roles.
Go down the list of permissions and choose which role can do it.  For example, if you want any authorized user to be able to pose comments, check the "Post comments" check box in the Authenticated User column.  And if you want only editors to be able to post book pages, Check "Post book pages" in the editor column and NOT the Authenticated User column.
Click the "List" tab at the top of the People overlay, next to Permissions.
Find the user accounts of everyone you think should be an editor, and add that role to their account.

If you have a lot of users already, you can add the role en masse by checking the box next to the names you want to grant editorial permission to, and then pick "Add a role to the selected users - editor" from the drop-down box in the Update Options part of the overlay.


How to test if user is denied access when her role has no "access content" Wanting to test that only users with "access content" have access:

public function testOnlyAccessContentAccessible() {
  $web_user = $this->drupalCreateUser();
  $this->drupalLogin($web_user);
  $this->drupalGet("foo");
  $this->assertResponse(403);
}

The module under test, relevant hook_menu-entry:

$items['foo'] = array(
  'title' => 'Foo',
  'page callback' => 'foo',
  'access arguments' => array("access content"),
  'expanded' => TRUE,
);

What is wrong here? My drupalCreateUser has not recieved an array with permissions, so it did not receive the "access content" permission either; yet Drupal hands out this permission by default, so I guess this is a permission that is "default" when nothing is posted.

So, how to check that only users with permission "access content" can access a page?

I recommend saving out your permissions using Features and then loading your custom feature in your test. By doing that, you can test out your configuration settings.

If you really just want to turn programmatically create a user that does not have the 'access content' permission, try this before you create your $web_user:

user_role_revoke_permissions(1, array('access content'));

This will revoke the 'access content' permission for anonymous users (role 1). See http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_role_revoke_permissions/7 for more help.


How do I find the user ID  knowing the username, when using drush? That would be much more handy to use Drush rather than executing a SQL query to find a user ID. So I am wondering what drush command can be used that takes a username, and returns the equivalent user ID.


Show prices excluding Tax/VAT but calculate and display only on checkout In case of B2B store I need to display all prices without VAT taxes. But taxes must be shown on cart and during checkout process. What's the good way for this?

I use commerce_vat.

My solution, all replies/comments are welcomed!

Edit rule "Calculate tax" (admin/config/workflow/rules/reaction/manage/commerce_vat_calculate) and add conditions for check if "Entity has field": commerce_customer_billing, commerce_customer_address
For not showing tax on cart (only on checkout): Add condition of type "NOT Data comparison": "Data to compare: [site:current-page:path], Operator: is one of, Data value: cart"
Use hook_commerce_price_formatted_components_alter() for edit labels (incl./excl. Tax) depending on whether the customer is liable for Tax/VAT or not.

Result in checkout process with a customer liable for VAT:


Where are the add to cart form settings? Im just trying to find the settings page for the add to cart form. I cant find it...

Im trying to change the setting when someone adds the same item to the cart twice it will combine it into one line item, rather than creating to separate line items as it is doing now.

I have attempted to add the setting here:

but no luck. still getting multiple line items.

Turn on the Combine options in your Line Item displays and Product displays.

If you use Commerce lisense module please check this issue Commerce license does not combine line items

If not I guess this link can be helpful , you will find example of hook_commerce_cart_product_comparison_properties_alter()


How to add a universal form submit handler to ALL forms? Suppose i need to record all form submissions in a site, i mean all of them.
I would add a new submit handler to be executed after each forms submit handler, like $form['#submit'][] = 'log_submit' , right?

The problem is that some forms may not have the submit handler inside $form['#submit'] array but in $form['buttons'] or $form['#actions'] etc...

How would i add my own submit handler to ALL of these forms, in one hook_form_alter() and in a clean way?

Thanks

You can use hook_form_alter(&$form, &$form_state, $form_id) without traditional if inside. Then it'll work on all forms.

Problems start when submit handlers are attached not to form, but to buttons. If you have to take care about that, you will need to scan recursively form tree, find all elements with ['#submit'] set and attach your handler to them. to do this, write recursive* function. Drupal mixes properties with children elements, so to avoid scanning properties, use element_children(&$elements, $sort = FALSE).

*Of course you can make it iterative, too, should be faster, but recursion is more intuitive approach.


Add class to ul element in views 3 unformatted list using templates or module code? I'm contributing to the Radix theme in D7 for panopoly, which uses Twitter Bootstrap.

I'm seeking out ways to implement as many of twitter bootstrap's awesome capabilities as possible, and thus not have to rely on overriding theme css, and to make it work 'natively' and rely on cleaner CSS.

So, the 'unstlyed' list property in Twitter Bootstrap is a perfect example of this.

...

However, I can't figure out how I would add this class to the views unformatted style by default using the theme.  Is this possible with template files, template.php code or an include file?  I would prefer to do this within the radix theme.  Help!

You could use the rewrite option in views to get the exact html output you need. Rewrite enables you to override the output of this field with custom text or replacement tokens. I use the last field, since the replacement tokens should be above the field you are rewriting. Make sure to go through set the field, label, wrapper html to None

In Views

Click on a Field
Click on Rewrite the output of this field
Add your code with the desired html output

Code

[field_degree]

[field_major]

Output

Certificate

Supervision

OR you can

Click Advanced
Click CSS class
Add the name of your class "unstyled" to the entire view.


Organic Groups Mass Subscribe I'm using organic groups 7.x-2.x, as well as admin_views for administering users. I have a field that I'm able to sort users on depending on what department they are in using Views Bulk Operations at admin/people.

My question involves subscribing people in bulk to a specific organic group. Is there a way to achieve this using Views Bulk Operations?

Users can now be added in bulk to organic groups using Views Bulk Operations out of box. The simplest way to do this is to take the following steps:

Download Admin Views
Edit the people listing page view at
/admin/structure/views/view/admin_views_user/edit
In the view under
fields, select "Bulk operations: User" Under "Modify entity values",
be sure that either "All" or at least "Group Membership" is selected
Save the view if needed
Go to /admin/people and filter the users as
desired Select "Change value" and click Execute
Under "Fields", select "Group membership", and select the group(s) you wish to assign the users to.
Be sure the "Add new value(s) to Group membership, instead of overwriting the existing values" checkbox is checked or your users will lose their existing membership settings.
Click Next to complete the operation.


Create a new entity and set field value With the Rules module, I collect a list of row (text value) from a view, then iterate the list (variable list_item) and add this action:

Create new entity of type xxxx, (variable entity_created);

I add a PHP action that extracts a substring from list_item, convert the substring in a Unix timestamp, and set a field "date" of entity_created.

The rule create only one entity, and not one entity for each item in list_item.

Does anybody know how to create one entity for each item in list_item?

The answer is the one suggested in Creating Entities in a Rules loop creates one first entity only.

After an actions of entity create, or data set, add the "Save entity" Action, and click on the "Force saving immediately" checkbox below on the form. Without selecting the checkbox, the Rules module creates only the first entity.


How can I inject container to a class with constructor having arguments? Fatal error: Declaration of Drupal\migrate_upgrade\MigrateUpgradeDrushRunner::create(Psr\Container\ContainerInterface $container, $options = Array) must be compatible with Drupal\Core\DependencyInjection\ContainerInjectionInterface::create(Symfony\Component\DependencyInjection\ContainerInterface $container)

Below is MigrateUpgradeCommands.php file
where I am creating an instance of new MigrateUpgradeDrushRunner() and passing two arguments $options and $this->logger

    class MigrateUpgradeCommands extends DrushCommands {
    /**
       * Logger service.
       *
       * @var \Drupal\Core\Logger\LoggerChannelInterface
       */
      protected $logger;

      /**
       * MigrateUpgradeCommands constructor.
       *
       * @param \Drupal\Core\State\StateInterface $state
       *   State service.
       * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerChannelFactoryInterface
       *   The logger.factory service.
       */
      public function __construct(StateInterface $state, LoggerChannelFactoryInterface $loggerFactory) {
        $this->state = $state;
        $this->logger = $loggerFactory->get('drush');
      }
/**
   * Perform one or more upgrade processes.
   *
   * @command migrate:upgrade
   *
   * @usage drush migrate-upgrade --legacy-db-url='mysql://root:pass@127.0.0.1/d6'
   *   Upgrade a Drupal 6 database to Drupal 8
   * @usage drush migrate-upgrade --legacy-db-key='drupal_7'
   *   Upgrade Drupal 7 database where the connection to Drupal 7 has already
   * been created in settings.php ($databases['drupal_7'])
   * @usage drush migrate-upgrade --legacy-db-url='mysql://root:pass@127.0.0.1/d7' --configure-only --migration-prefix=d7_custom_ --legacy-root=https://www.example.com
   *   Generate migrations for a custom migration from Drupal 7 to Drupal 8
   *
   * @validate-module-enabled migrate_upgrade
   *
   * @aliases migrate-upgrade, mup
   *
   * @throws \Exception
   *   When an error occurs.
   */
  public function upgrade(array $options = []) {
    $runner = new MigrateUpgradeDrushRunner($options, $this->logger);

    $runner->configure();
    if ($options['configure-only']) {
      $runner->export();
    }
    else {
      $runner->import();
      $this->state->set('migrate_drupal_ui.performed', \Drupal::time()->getRequestTime());
    }
    // Remove the global database state.
    $this->state->delete('migrate.fallback_state_key');
  }

    }

Now file MigrateUpgradeDrushRunner.php

class MigrateUpgradeDrushRunner implements ContainerInjectionInterface {
  /**
   * Logger channel.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  public static function create(ContainerInterface $container, $options = []) {
    return new static(
      $container->get('logger.factory'),
      $options
    );
  }

  /**
   * MigrateUpgradeDrushRunner constructor.
   *
   * @param array $options
   *   Drush options parameters.
   * @param \Drupal\Core\Logger\LoggerChannelInterface $logger
   *   Drush logger.
   */
  public function __construct(array $options = [], LoggerChannelInterface $logger) {
    $this->setOptions($options);
    $this->logger = $logger;
  }

}

Basically, how can I inject Container into MigrateUpgradeDrushRunner so that I can fetch logger.factory service and pass it in the construct ?

Instead of adding $options to your create method you shall add a method to set the options.

Take a look at this code to see how you can inject $logger in your class:

class MigrateUpgradeDrushRunner implements ContainerInjectionInterface {

  /**
   * The logger channel factory.
   *
   * @var LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The options.
   *
   * @var array
   */
  protected $options = [];

  /**
   * MigrateUpgradeDrushRunner constructor.
   *
   * @param LoggerChannelFactoryInterface $logger
   *   The logger channel factory.
   */
  public function __construct(LoggerChannelFactoryInterface $logger) {
    $this->logger = $logger;
  }

  /**
   * {@inheritDoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.factory')
    );
  }

  /**
   * Set the options.
   *
   * @params array $options
   *   The options.
   */
  public function setOptions(array $options) {
    // Do something...
  }

}


How to remove images from body field in views? In the body field of a content type, I have added an image at the start. In my view, I want to show 200 characters from the body field. It also prints the image.
How can I skip the photos from the body field in the view, and print just the text?

Edit the Body Field Rewrite results in your Views and enable the option Strip HTML tags. Use Preserve certain tags if you have other elements within your text you want to show, enter them there.
This option is below the Trim this field to a maximum number of characters you're probably using, you'll probably want to also use the suboption Field can contain HTML.


Auto-add today's date and time to new Entity title upon creation? I'd like to be able to auto-add today's date/time to the title of a particular Entity type when a new entity of that type is created. For instance, if I create an entity called "My New Entity", I'd like the title of that entity to actually be saved as "My Entity - 020513 - 103501" (assuming the entity is created on February 5, 2013, at 10:35:01 am).

Is this possible? If so, how can it be accomplished on a Drupal 7 website?

Thanks!

Option #1

For Drupal 7 you're looking at the Automatic Entity Label module if you're after a particular entity.

  "Automatic Entity Label" is a small and efficient module that allows
  hiding of entity label fields. To prevent empty labels it can be
  configured to generate the label automatically by a given pattern.

Possible option #2

Another option is available if your Entity has actions exposed to Rules.  Simple create a rul that reacts on entity creation, and set some conditions as per usual.  Then, in the actions do the following:

1) Add an action for Set data value

2) Find your entity (node for example) and look for :title under data selector (e.g. node:title)

3) Click continue

4) On the next page, set the data value to be whatever you need with tokens (so your example could be something like as [node:title] - [site:current-date])


Automated translation of interface Long story short: I'm looking for a way to provide translations... the "hard" way. So I don't want to click in the backend to apply new translations or translate it on the "Translate Interface" Page.

I really want to provide it hard coded, and when it's changed, it should get changed in the backend as well.

Since you don't want to use the user interface, the only way to provide a translation of the string used from modules is to set them in the settings.php file.

$conf['locale_custom_strings_it'][''] = array(
  'forum' => 'Tavola di discussione',
  '@count min' => '@count minuti',
);

Replace "it" with language code for which you want to provide the translation. The array index is the string in English, while the array value is the translated string.

Using this method is pretty hard: Each times a new string is translated, the settings.php needs to be edited. There could be also some performance issues, as you are defining a new array row for every new translation; I let you imagine what happens when you have 1000 strings to translate in 5 languages.

When those values are provided, the database is not anymore looked up, as t() contains the following code. (See the first comment.)

  // First, check for an array of customized strings. If present, use the array
  // *instead of* database lookups. This is a high performance way to provide a
  // handful of string replacements. See settings.php for examples.
  // Cache the $custom_strings variable to improve performance.
  if (!isset($custom_strings[$options['langcode']])) {
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
  }
  // Custom strings work for English too, even if locale module is disabled.
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
  }
  // Translate with locale module if enabled.
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
    $string = locale($string, $options['context'], $options['langcode']);
  }
  if (empty($args)) {
    return $string;
  }
  else {
    return format_string($string, $args);
  }