Form API-passing on the NID in a hidden field? So, here's my issue. I have a university course page. I want to display a list of students currently weight listed for the course, and give the option for the student to add their name to the weight list.

I've outputted the current student weight list through a custom template file just fine. I've also made a one button form through a custom module that simply calls a submit function. Then I call that form on my node template. That part works all fine.

Then, all I need for this form to work is the current User's UID (which can be called easily from my form submit function in my module). And the NID that their name should be attached to. Where I'm having difficulty is the NID part. I can't figure out how I can add that to my custom form built through my module with Form API.

Right now, I'm setting a variable and calling that variable in the submit function.The problem there is it will screw up the system if more than one student is looking at different pages and submits it. So there needs to be way that I can set the current NID that the form sits on, then call it through my submit handler.

I've been searching google up and down for this, and I can't figure out how to set a hidden field with the current NID the form is on.

Any help would be greatly appreciated.

Edit: Here is my code currently for reference:

function wl_add_form($form_state) {

 $form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Add Name to List'),
  '#submit' => array('wl_add_form_submit_function'),
);

  return $form;
}

//Add me to weight list functions
function wl_add_form_submit_function($form, &$form_state) {

//dpm($form);
  //Handle the student add
  global $user;
  //get the User ID
  $userID = $user->uid;
  //get the NID from the node variable we set in the node-course template:

  $nid= variable_get($wlNID);
  $node = node_load($nid);
  $count = count($node->field_course_weight_student);
  $node->field_course_weight_student[$count]['uid'] = $userID; // another user
  node_save($node);
  drupal_set_message(t('Your name has been added to the weight list'));

}

Just save the node ID in $_SESSION.

Using variable_set() has another effect, apart saving a value that is valid for all the users: It clears the cache Drupal uses for the Drupal variables, with the effect they are reloaded from the database the next time Drupal bootstraps. Compare the code used by variable_set() and variable_initialize(). (Similar code is executed by Drupal 6.)

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;

  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

As for an example of how to use $_SESSION in a form, see node_filter_form(), the form builder function that handles the form that allows to filter nodes in admin/content/node.

  $session = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
  $filters = node_filters();

  $i = 0;
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__node',
  );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
    if ($type == 'term') {
      // Load term name from DB rather than search and parse options array.
      $value = module_invoke('taxonomy', 'term_load', $value);
      $value = $value->name;
    }
    elseif ($type == 'language') {
      $value = $value == LANGUAGE_NONE ? t('Language neutral') : module_invoke('locale', 'language_name', $value);
    }
    else {
      $value = $filters[$type]['options'][$value];
    }
    $t_args = array(
      '%property' => $filters[$type]['title'],
      '%value' => $value,
    );
    if ($i++) {
      $form['filters']['current'][] = array('#markup' => t('and where %property is %value', $t_args));
    }
    else {
      $form['filters']['current'][] = array('#markup' => t('where %property is %value', $t_args));
    }
    if (in_array($type, array('type', 'language'))) {
      // Remove the option if it is already being filtered on.
      unset($filters[$type]);
    }
  }

  $form['filters']['status'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('clearfix')),
    '#prefix' => ($i ? '
' . t('and where') . '
' : ''),
  );
  $form['filters']['status']['filters'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('filters')),
  );
  foreach ($filters as $key => $filter) {
    $form['filters']['status']['filters'][$key] = array(
      '#type' => 'select',
      '#options' => $filter['options'],
      '#title' => $filter['title'],
      '#default_value' => '[any]',
    );
  }

Its form submission handler sets $_SESSION with the values entered by the user.

  // Apply every filter that has a choice selected other than 'any'.
  foreach ($filters as $filter => $options) {
    if (isset($form_state['values'][$filter]) && $form_state['values'][$filter] != '[any]') {
      // Flatten the options array to accommodate hierarchical/nested options.
      $flat_options = form_options_flatten($filters[$filter]['options']);
      // Only accept valid selections offered on the dropdown, block bad input.
      if (isset($flat_options[$form_state['values'][$filter]])) {
        $_SESSION['node_overview_filter'][] = array($filter, $form_state['values'][$filter]);
      }
    }
  }


Behaviors/JQuery: What's the standard/convention in Drupal 7 for running Jquery code on event *OTHER* than DOM ready? Searching online docs so far and I've found much about Drupal Behaviors running when the DOM is ready i.e. the ready JQuery function.

But what about for example if I want my JQuery code to run once all the images have loaded? Now, I could use the JQuery load function, but this is apparently not recommended to use such Jquery functions JQuery directly in Drupal but work within Behaviors instead - but these are no good to me if they only run on DOM ready event.

Thoughts?

Using .load() on element to attach event handler in your behaviors should not be a problem. Using it directly to window outside a behavior, for instance to wait for all images to be loaded, should be okay too.

As pointed by Clive in the comment, Drupal behaviors are to be used in replacement of $.ready(), not $(window).load(). However, if content (ie. new DOM elements) is added to the page after page load (AJAX calls, content generated from JavaScript, etc.), handlers for $.ready() will not be called and will not have a chance to process the added DOM elements. While the attach() method of all behaviors is also called when this happen. With a parent of the added DOM elements as context.

Behaviors can also have a detach() method which is called when DOM element are removed or before form serialization. This us, for instance, used to properly destroy WYSIWYG editors when their textarea are removed from the DOM and to prepare the POSTed data hen their form are submitted.

Off course, this rely on the JavaScript doing the addition/removal/serialization to properly call Drupal.attachBehaviors() and Drupal.detachBehabiors(). Something that is done by Drupal core (including form handling and the Drupal AJAX Framework) and properly written contrib modules.

I'm not familiar with the load event and its behavior with content added after the first time it is triggered. If it does not fire multiple times, re-registering the handler in a behavior attach() method may be required to ensure newly added image are also processed.


Override html.tpl.php per node type In my template.php file for my theme I have tried the following:

function media_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']))
  {
      // If the node type is "blog" the template suggestion will be "html--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'html__'.$vars['node']->type;

      // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->type;

      // If the node id is "33" the template suggestion will be "page--33.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->nid;
  }

    //Create page suggestion for first part of url-alias
    $url_alias = drupal_get_path_alias($_GET['q']);
    $parts = explode('/', $url_alias);

    $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__alias';
}

This works for page--nodetype.tpl.php, but not for html--nodetype.tpl.php

You may be asking why do you need to override the html.tpl.php template per node type. It is because there is markup that I don't want to include for this particular node.

The name of a preprocess function is based on the theme/template that is being processed. To preprocess the html.tpl.php file you'll need to use hook_preprocess_html():

function media_preprocess_html(&$vars) {
  $node = menu_get_object();

  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
  }
}


How to programmatically render a view pager? I'm trying to figure out how to render a view's pager programmatically. I'm renderering my view programmatically as follows:

$viewname = 'example_view';
$viewdisplay = 'block';

// get the view machine id
$view = Views::getView($viewname);
// set the display machine id
$view->setDisplay($viewdisplay);
$view->render();

$renderer = $view->rowPlugin;
foreach ($view->result as $index => $row) {
  $view->row_index = $index;
  $vars['content']['view_results'][$index] = $renderer->render($row);
}

So now I need to render the pager, but not having any luck. I've tried something like:

$pagerrenderer = $view->pager;
$vars['content']['view_pager'] = $pagerrenderer->render($view->pager);

but then end up with the following error:

  Recoverable fatal error: Argument 1 passed to pager_query_add_page()
  must be of the type array, object given, called in
  /www/projectname/docroot/core/includes/pager.inc on line 246 and defined
  in pager_query_add_page() (line 311 of core/includes/pager.inc).

Can anyone point me in the right direction?

The object returned from $views->pager() is an object implementing ViewsPluginInterface and extending PagerPluginBase. If you look at the parameters PagerPluginBase::render() accepts, you will see they are:

  $input: Any extra GET parameters that should be retained, such as exposed input.

If you look at Full::render(), you have an idea of how that parameter is used.

  $tags = array(
    0 => $this->options['tags']['first'],
    1 => $this->options['tags']['previous'],
    3 => $this->options['tags']['next'],
    4 => $this->options['tags']['last'],
  );
  return array(
    '#theme' => $this->themeFunctions(),
    '#tags' => $tags,
    '#element' => $this->options['id'],
    '#parameters' => $input,
    '#quantity' => $this->options['quantity'],
    '#route_name' => !empty($this->view->live_preview) ? '<current>' : '<none>',
  );

In any case, you don't pass to the method of that object the object itself.


add comment form in views I've created a views from comments. I want to have add comment form at the button of my views (in footer). so I installed "views_php" module and add "Global: PHP" to footer and write this code to print add comment form in footer.

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);

but the problem is that I don't have comment_body or any other custom field in the printed form. actually just author, subject and save button.

I tried this code too:

print drupal_render(drupal_get_form("comment_form", (object) array('nid' => $data->nid)));

or

print drupal_render(drupal_get_form("comment_node_news_form", (object) array('nid' => $results[0]->nid)));

but none of them worked properly!

<?php
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);
?>

Works for me. Make sure that your Content: Nid field is ABOVE the Global: PHP field, otherwise (when it's below it) $row->nid is not available as a variable.

Update
After reading your Q more carefully, since you want it in the footer then you need to specify the node id of the form. (Under what node this comment will be stored) For Example: /node/1
<?php
$comment = new stdClass;
$comment->nid = 1;
$form = drupal_get_form('comment_form', $comment);
print render($form);
?>

If you want /node/5 you change this line to $comment->nid = 5;
OR
If you want this to be dynamic, the nid to be based on the page you're viewing. Then use
<?php
if ($node = menu_get_object()) {
$comment = new stdClass;
$comment->nid = $node->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);
}
?>

Note: The form will not render/show on views preview, but it will show up when you visit the node.


How do I implement the login, register and "Forgotten password" forms? I'm trying to implement the three Drupal 8 user forms : login, register account and forgotten password forms.

I'm creating custom pages in my module for each one of them because I want to display content around those forms, change titles, hook the forms.

I'm having a hard time to do it, especially to get those forms in order to send them to the template and render them.

Here is what I ended up doing in my controllers :

# Login form
public function content() {
  $formBuilder = $this->formBuilder();
  $form = $formBuilder->getForm("Drupal\user\Form\UserLoginForm");
  return [
  '#theme' => 'weber_login_form',
  '#login_form' => $form,
  ];
}

# Forgotten password form
public function content() {
  $formBuilder = $this->formBuilder();
  $form = $formBuilder->getForm("Drupal\user\Form\UserPasswordForm");
  return [
    '#theme' => 'weber_password_form',
    '#password_form' => $form,
  ];
}

# Register form
public function content() {
  $entity = \Drupal::entityManager()
  ->getStorage('user')
  ->create(array());

  $formObject = \Drupal::entityManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity);

  $form = \Drupal::formBuilder()->getForm($formObject);
  return [
    '#theme' => 'weber_register_form',
    '#register_form' => $form,
    '#link' => NULL,
  ];
}


How do I make a horizontal user login block for the top user region? I'm not sure why but Drupal doesn't provide for a horizontal user login with the register or forgot password links. How do I do this?

There are many many ways to do this, there is even a screencast and a module to do this. I would personally do this from the theme layer using css, or if I was using Fusion as a base theme, I would do this from the block configuration (thanks Skinr!)

I'm adding some links that will help you out.

http://drupal.org/project/userloginbar

http://ericlondon.com/changing-user-login-block-horizontal-layout

http://www.youtube.com/watch?v=XMyOX6v-k3Y

http://www.victheme.com/blog/drupal-7-creating-horizontal-login-bar-without-module


How to create view of taxonomy terms and then once clicked on taxonomy term another view will be opened displaying all content having that term? I have a taxonomy called "Destination Type". There are 4 terms in it (Historical, Leisure, Wildlife,Cultural).
I have created one content type called "Destination" with taxonomy field "destination_type".
Now I want to create a view of taxonomy "destination type" which is I am able to create. Once user click on any of the term in that view say Historical, then the next view should open displaying the list of all destinations with destination type as historical.

This is how I want the result same as "Jump right in, Things to do" in http://www.gotobermuda.com/

I am stuck here. Please help me out with this

Thank you

I get it working. It was not that hard :)

First I create the view of taxonomy term. In that view I add contextual filter "Taxonomy term : term ID".

And in the next view I add contextual filter "Content: content_type_name"

Thats it. Got the desired result.


How to create related links list in Views So for Content Type 'Level 3' I have added a field called 'Related Links' which uses Entity Reference and autocomplete so a user can select multiple pages that are related.

I've been now trying to render these pages as links using Views, however I'm really stuck as to what settings I should be using. I need Views to get the Related Links for the current page on which it is displaying the block, and then display a linked Title of each of the pages that have been specified in the 'related links' field.

Create a new view showing content, check "create a block".

Click in advanced and, in relationships, add "a bridge to the content entity that is referencing content via your_field_name". The identifier will be something like: "Content referencing Content from your_field_name"

Then add a contextual filter with a relationship to the filter you just created. Select provide default value (Content ID from URL) when filter value is not available.

You can also filter nodes by type to make the view more efficient.

Save your view and add your block to show in the corresponding pages through the block display manager, context or display suite.


Webform file upload not working after hook_from_alter I have used the following form alter to do some adjustments to my form but after the file upload stops working. I cant seem to find out why. This is the module code.

Any help would be much appreciated.

if ($form_id == 'webform_client_form_3'){
    //image btn
    $form['actions']['submit']['#type'] = 'image_button';
    $form['actions']['submit']['#src'] = drupal_get_path('theme', 'MY_THEME').'/images/submit2.png';
    $form['actions']['submit']['#attributes']['name'][] = 'op';

    //palceholders
    $form['submitted']['forename']['#attributes']['placeholder'] = t('Forename');
    $form['submitted']['surname']['#attributes']['placeholder'] = t('Surname');
    $form['submitted']['post_code']['#attributes']['placeholder'] = t('Post Code');

}

I fixed this by forcing the the 'op' value to

 $form['actions']['op'] = array( '#type' => 'value', '#value' => 'Submit', );


Help with view filters I have a view using one content type: fee_schedule
The view contains fields for species, keywords (hidden), and the title.

The filters need to show ALL species except when searching by keywords.  The keywords field and the title field are combined using Global Combine fields filter that is exposed.

Here's the issue:  When someone uses the exposed species drop down, it works as expected.  It shows the 'All' species and which ever species they selected.  But when they put in keywords (like 'bulk') then it still shows All species (even though these species do not have 'bulk' as a keyword), along with the species that do have the keyword 'bulk'.  When searching using keywords, I need the view to display ONLY the species with the keyword.  When searching by species, I need it to show the content with All species and the specific species they selected.

Here's the link to the view: https://vdl-dev.umn.edu/services-fees

I am using and/or filtering as follows:

Content Published: yes AND
Content Type: Fee Schedule AND
Global Combined fields filter exposed (title and keywords) AND
Content Species (each specific species but not All)

OR

Content Species (All is only selected)

Maybe I can't do what I need to do using views.  Any help much appreciated.

Your description is very confusing, I hope I was able to understand your problem in the end.

You've framed it as if you're applying the exposed filters and then looking at the views results. But in the end you're looking back at the Exposed filters.

The module that can help you is Views Selective Filters.

  you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.


Site building process: what is the relationship between CCK, Views, Panels, Blocks and Taxonomy? A beginner question. I need to understand the relationship between the top Drupal structure modules: CCK, Views, Panels, Blocks and Taxonomy, i.e., when building a website, what is the general steps that the site builder should consider regarding using those modules? What comes first? What's next?.

Let's consider a site that categorizes IDEs (integrated development environments) and provides detailed informations about each IDE. How would be the mentioned modules implemented with this use case? What would be this websites building process?

Thanks.

Taxonomy and CCK are both used to customize content types. This first thing you usually want to do when building a site, is to figure out how the content types should be defined. With Drupal 7 you have entities instead which provides a more flexible way of defining data structure, but the idea is the same.

Once you have defined your content types, views, panels (or context) comes into play. Views is really good at making listings of different types, like the latest articles, nodes post by user X etc.

Panels can be used to piece things together, but as it's a very complex tool, it can also be a bit overkill to use. It was originally created out of a frustration with the Drupal block system, with all it's limitations. It if you want to use panels to manage blocks, you might consider using context instead as it provides the same functionality but is more lightweight. What panels is good at making lots of pages with very different layout. It has one advantage over context, and that is a more tight integration with views, allowing to use views not defined at blocks as blocks (panel panes).

So to sum up.

Define content types.
Create list/displays with views.
Piece it together with panel/context.


Automatically load the URL from link field into a script I have a content type "Team" to add team members. In this content type I have a link field (called "LinkedIn") which holds the URL to the team member's LinkedIn page.
What I want is to use the URL from the link field and use it with a script (provided by LinkedIn). The script looks like this:

<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="linkedin-profile-link.com" data-format="hover"></script>

I have created a simple text field for the content type "Team" and in a team member node of that content type I copied above code into it and inserted the URL from the "LinkedIn" link field. This works but I would have to edit more 100 team member pages.

How could I automatically load the URL from the "LinkedIn" link field into this script (it needs to be added into data-id="link comes here") and display on every team member page? Can this be done with Display Suite? Or do I need to write a module?

You could use a field template in your theme.

Call it something like field--field-linkedin-url.tpl.php (whatever you have called your field. I'm assuming field_linkedin_url for my example. Notice the _'s are converted to -'s in the file name.

In the template put the following html:

<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="<?php print render($items); ?>" data-format="hover"></script>

It shows something like this:


How to remove a stylesheet provided by a contrib module? The new version of Field Group has a new stylesheet included by default that makes my theme look hideous.  Deleting the stylesheet from the module's folder fixes the problem but then I will have to delete it again when Field Group is updated again.

What's the right way (= not modifying the module's code directly) to do this?

I think using hook_css_alter() in a custom module/theme would be the easiest solution:

function MYMODULE_css_alter(&$css) {
  // Get the path to the module
  $path = drupal_get_path('module', 'field_group');

  // Remove the unneeded files from the css array
  unset($css[$path . '/field_group.css']);
  unset($css[$path . '/field_group.field_ui.css']);
}

There are also other CSS files in the Field Group module:

horizontal-tabs/horizontal-tabs.css
multipage/multipage.css

In case you're look to remove absolutely all the CSS that Field Group introduces.


Secondary submit function for form input button I want to have buttons for remove selected field from form.

    $form['questions']['buttons'][$counter] = array(
        '#type' => 'button',
        '#name' =>'button_'.$counter,
        '#value' => t('Remove'),
        '#submit' => array('my_mod_remove_submit'),
    );

Submit function:

function my_mod_remove_submit($form, &$form_state) {
    drupal_set_message('<pre>'.print_r($form_state, 1).'</pre>');
}

But it seems that this function is never invoke.

The problem with your code is the default value for the form field attributes. In the case of the "button" form field, these are the default values:

#name => 'op'
#button_type => 'submit'
#executes_submit_callback => FALSE
#ahah['event'] => 'mousedown'

Those are also the default values for Drupal 7.

If you want to use a submission callback for a button, then you need to change the form field definition to the following one:

$form['questions']['buttons'][$counter] = array(
  '#type' => 'button',
  '#name' =>'button_' . $counter,
  '#value' => t('Remove'),
  '#executes_submit_callback' => TRUE,
  '#submit' => array('my_mod_remove_submit'),
);

As alternative, instead of using a "button" form field, you should use a "submit" form field.


How to implement redirect to custom 404/403 pages? Hello Drupal community.

What I am trying to do is if error 404 or 403 occurs it redirects to a custom page instead of showing standard error message.

I tried to write “/error/404” on the “Base site settings” page and created a content with the same alias but it didn’t work.
So when I try to access a page with some random url it still shows me a standard error message but not the content with “/error/404” alias.

Is my understanding of this functionality wrong? Should I try another approach?

This is build in to Drupal and the simple way to do this is to create separate pages for both error codes and add your own wording as necessary.

Then go to the error pages section of site settings at /admin/config/system/site-information and add the path of your custom error pages.


Switching file system from private to public makes all inline image paths broken I built a site with private file system initially, but now want to switch to public so that I can use performance enhancements like css and js minification as they are not available for private file systems.

The problem is that switching to public changes the file path and breaks all the inline image paths. Any ideas how to do this properly?

Just as an example, with private file system paths show as
mysite.com/system/files/myfile.jpg
this is what was stored by the body field for inline images. These change to
mysite.com/sites/default..../myfile.jpg

There's no miracle for that, you've to replace all path in the database. Fortunately MySQL has a replace function that will be useful for you.

First, you've to find every table/field that can contain inline image, if you're using Drupal 6, you'll look at node and node_revision for Drupal 7 it's more something like field_data_body and field_revision_body.

And finally you have to apply this query (for Drupal 7)

UPDATE field_data_body SET body_value = REPLACE(body_value, 'system/files/', 'files/');

Perhaps you should customize a query a little, but the main idea is there.


Showing a message for specific content type I'm trying to show a message for specific content type through a new module, on Drupal 8.3.0. (I'm a beginner.)

This is part of the code I am using.

File test_module.module (updated code, still not working)

/**
 * @file
 * Implementation of hook_node_view();
 */

function test_module_node_view($node, $view_mode) {
  if ($view_mode == 'full' && $node->type == 'test_content') {
      /*Message with current date and time*/
      $current_time = time();
      drupal_set_message(t('Hello! Today is '.format_date($current_time,'medium')));
    }
  }

As far as I know, this should work, but it doesn't and I don't know why. The message is not showing for a node of content type "test_content". How can I fix this? Is there another way to alter nodes of custom content types?

(Test_content_example is a node of type 'test_content', so there should be a system message displayed, but there's none.)

$node->type is a reference to the node type config entity - it's not a string.

You can use NodeInterface::getType() instead, e.g.:

if ($view_mode == 'full' && $node->getType() == 'test_content') {

}

Incidentally you could also use $node->bundle(), or even $node->type->entity->id(). But getType() is probably most appropriate for your specific needs.

You also have the function signature wrong - it should be:

function test_module_node_view(array &$build, \Drupal\node\NodeInterface $node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)


Webform submit button disappearing if I change it from default I have a weird issue with the webform module, whenever I modify the submit button (change text, add class) it doesn't show up on the page anymore (nor in the source code). If I delete it, it is back to default (the label in the OPERATION column says customize again) and it works, but it disappear if I change it again.

I didn't do any weird modification beside creating a Twig template for it. But since it works when I leave it to its default value I doubt the issue lies there.
Hopefully one of you guys can help me.

Here is the YAML code:

markup:
  '#type': markup
  '#markup': |
    <h2>
      Je publie une offre d'emploi
    </h2>
job:
  '#type': textfield
  '#title': job
  '#title_display': invisible
  '#placeholder': 'Fonction recherchée*'
  '#required': true
  '#required_error': 'Fill in a valid job'
  '#pattern': '^[a-zA-Z]*$'
company:
  '#type': textfield
  '#title': company
  '#title_display': invisible
  '#placeholder': 'Nom de la société*'
  '#required': true
  '#required_error': 'Fill in a company'
  '#pattern': '^[a-zA-Z0-9]*$'
job_description:
  '#type': textarea
  '#title': 'job description'
  '#title_display': invisible
  '#placeholder': 'Description de la fonction'
  '#required': true
  '#required_error': 'Fill in a description'
contract:
  '#type': select
  '#title': contract
  '#title_display': invisible
  '#options':
    CDD: CDD
    CDI: CDI
  '#empty_value': 'Type de contrat*'
  '#required': true
  '#required_error': 'Choose a contract type'
job_schedule:
  '#type': select_other
  '#title': 'job schedule'
  '#title_display': invisible
  '#options':
    'Full time': 'Full time'
    'Part time': 'Part time'
  '#empty_value': 'Travail à temps...*'
  '#required': true
  '#required_error': 'Select a schedule'
location:
  '#type': textfield
  '#title': location
  '#title_display': invisible
  '#placeholder': 'Lieu*'
  '#required': true
publication_date:
  '#type': date
  '#title': 'publication date'
  '#description': 'Date de publication*'
  '#title_display': invisible
  '#description_display': before
  '#prepopulate': true
  '#required': true
  '#required_error': 'Select a publication day'
  '#min': today
  '#max': '+2 months'
  '#step': '1'
end_date:
  '#type': date
  '#title': 'end date'
  '#description': 'Date limite*'
  '#title_display': invisible
  '#description_display': before
  '#required': true
  '#min': '+2 weeks'
url:
  '#type': url
  '#title': URL
  '#title_display': invisible
  '#placeholder': 'URL: RH ou Plateforme pour postuler*'
  '#required': true
  '#required_error': 'Fill in a valid URL'
phone:
  '#type': tel
  '#title': phone
  '#description': 'Mes informations (pour &ecirc;tre contact&eacute; par BioWin)'
  '#title_display': invisible
  '#description_display': before
  '#placeholder': 'Numéro de téléphone*'
email:
  '#type': email
  '#title': email
  '#title_display': invisible
  '#placeholder': 'Adresse email'
  '#pattern': '^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,10})+$'
actions:
  '#type': webform_actions
  '#title': 'Submit button(s)'
  '#submit__label': Envoyer
  '#submit__attributes':
    class:
      - cta

If you have a custom twig template for your webform the custom submit button needs to be referenced differently than the default.
Default Submit Button reference:
{{ element.actions }}
Customized Submit Button reference:
{{ element.elements.actions }}


Show drupal login on page load I want to display the login form in a popup when a user is not logged in (meaning Anonymous).

I read this tutorial, but when I try nothing happens, so I think maybe it's because I am on Drupal 7? How is jQuery called in Drupal 7?

It would be a good idea to see this podcast.


How can I “Link to the Content” for teaser view mode of custom content type module? I've created a module that's add a content type to my site and I now want to understand how can I Link a Plain text fields to the Content in Teaser view mode programmatically in my module?
I currently can Link to the Content any Plain text field in:

Home>Administration>Structure>Content types>Content types name>Manage
display

Teaser Manage display page, see below image:

and I want to understand how can I get access or implement this property (feature) in my module, I try to achieve this by adding below code to my module:
#core.entity_view_display.node.teaser
field_version:
  type: string
  weight: 2
  label: inline
  settings:
  third_party_settings: {  }

To no avail.
Thank you for any help.

This is the setting link_to_entity: true:

field_version:
  type: string
  weight: 2
  label: inline
  settings:
    link_to_entity: true
  third_party_settings: {  }


How to obtain the machine name and field type of the fields of a content type filtered by those created by the user? I have a content type News to which I added the following fields:

Label | System Name | Type
Image | field_image | Is a image
Related content | field_related_content | is a Paragraph
Date | field_date | Is Datetime type

What I'm trying to do with a custom module is, I want to get the machine names of each field and the type of field that I defined.

Is it possible to obtain data from only those that I generated?
That is, for example, the created fields, or the update field or those that come by default do not appear, in some way filter the ones that I defined as the user in the content type.

For example, after some form of processing the type of content, only result in:

$result = [

  'field_image' => [
     'type' => 'image',
   ],
   'field_related_content' => [
    'type' => 'paragraph' // i don't know if the type is Entity reference revisions in reality
   ],
   'field_date' => [
    'type' => 'datetime'
   ]

];

Thanks.

If you mean the fields configurable in UI, then you can get them through EntityFieldManager::getFieldDefinitions:

$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'article'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

$result = [];
foreach ($fields as $key => $definition) {
  $result[$key] = [
    'type' => $definition->getType(),
  ];
  // if the field is a reference field get also the target entity type
  if (in_array($result[$key]['type'], ['entity_reference', 'entity_reference_revisions'])) {
    $result[$key]['target_type'] = $definition->getSettings()['target_type'];
  }
}

Entities have base fields defined in code and bundle fields defined in configuration. Drupal doesn't keep track whether a bundle field is configured by you or is from another source. A field can be pre-installed by a module, then deleted and added in UI again and Drupal wouldn't be able to tell the difference.


List of authors of articles in a view I am trying to create a page which lists the users who are an author of a node type of article.

I figured I would approach it by creating a view based upon article. So the view started out listing all articles. Then I set up a relationship to users where the user is the author of the article, and in the fields, I just have it output the author's name (user name).

Now I have a list of all of the authors, but it repeats. So you see John Smith a hundred times, if he wrote 100 articles.

How do you make it so that John Smith only shows up once? If I could edit the mysql, I would just use group by uid (so the user only shows once), but in drupal views, it will list that author as a heading for a group, and then list all the articles he was in (so in my setup, it would show his name followed by a listing of his name many times).

This is in Drupal 7

you are almost there. Just set "Use aggregation" to yes. Also, make sure there is not other field in "sort criteria".


Superfish menus getting clipped in blocks I'm showing a Superfish block with a selected menu in the Homebox module.

The problem is that child menus are getting clipped in the left and right and using browser console I'm not able to remove this clipping either by z-index or using overflow-x/y css properties.

How to make it work?

The div enclosing the Quick Links Staff block has "overflow" set to "hidden". Now if I disable it then the sub-menus show correctly but now the block height drops :

If you can't remove it with z-index: 4; then it might mean that your menu does not have a background; thus, it's transparent.

So add a background to your menu ex: background: white;


I have WYSIWYG and CKEditor 3.6.6.1 and want to install the latest CKEditor 4.6.1 My goal is to paste images (best if copied from word together with text) directly without uploading them first.

I got a D7 site with WYSIWYG installed. The module tells me it uses the CKEditor 3.6.6.1 library. In fact, there is no CKEditor module installed, but in the libraries path I see a ckeditor folder.

I tried to install the module pasteFromWord, and I found it didn't work with my a local copy of my site. So I looked around, and I found there is a newer version of CKeditor (4.6.1) rewritten with lots of features like embedding pictures, and it is open source too. There is only an older version of CKEditor as a Drupal 7 module, and it is driving me nuts to install anything that works.

I read about problems with WYSIWYG and I disabled it, but I cannot uninstall it, so I cancelled the whole directory under modules. I installed the latest Drupal CKEDitor (Dev) but all I see in my text field is htmlcode in full html mode. There are no editor icons. I put higher values for the memory settings in settings.php, restarted the server, cleared the cache, tried all sorts of thing suggested in Why does the Wysiwyg module and Ckeditor library not show the CKEditor when editing a node?

All tests are done as user1. By now, I get a simple text field in plain and filtered HTML mode; in full HTML, the text box body simply vanishes.

In Mozilla the Console gives:
TypeError: a(...).on is not a function
 js_8iXNyfjLJ1tJPju6nAtk8ETos8oLn9Arp0f2Z5uBPaQ.js:850:1412
TypeError: CKEDITOR.dialogCommand is not a constructor
 plugin.js:4:43
in http://localhost:8080/drupal7bis/sites/all/modules/ckeditor/ckeditor/plugins/SimpleImage/plugin.js which is one of the few plugins I enabled so far (nearly all are installed though because indeed I took the full package) and it reads:
CKEDITOR.plugins.add( 'SimpleImage', {
    icons: 'simpleimage',
    init: function( editor ) {
        editor.addCommand( 'simpleimage', new CKEDITOR.dialogCommand( 'simpleimageDialog' ) );
        editor.ui.addButton( 'SimpleImage', {
            label: 'Add a image',
            icons: 'simpleimage',
            command: 'simpleimage'
        });

    CKEDITOR.dialog.add( 'simpleimageDialog', this.path + 'dialogs/simpleimage.js' );
}

});

When I disable this plugin, only the first error remains. The body does not vanish any more in full mode, but still no editor appears.
There are no recent records in watchdog...

As far as I know, you need to use the dev version of the WYSIWYG module in order to use CKEditor 4.x. You also need to grab the 'full build' of CKEditor and not a stripped down one. You do not need the CKEditor module if you are using the WYSIWYG module. WYSIWYG looks for editors in the given paths (usually libraries) - you have to go get it from ckeditor.com.

The second thing you are describing is adding custom or non-core plugins to CKEditor, which is not as straightforward. "Paste from Word" should be available though once you get WYSWIYG and CKEditor 4.x setup in Drupal 7.

I wrote a plugin integration once for CKEditor 4.x under WYSIWYG. I do not recall needing any module other than WYSIWYG and the full CKEditor library for getting WYSIWYG to show up. You shouldn't need any other CKEditor modules. But if you are looking to add other plugins on ckeditor.com - you need to get comfortable with the WYSIWYG API in order to properly integrate it if someone else hasn't done so already.

The reason your CKEditor may not be showing on the edit page is likely due to a JS error - I am going to guess either because you are not using WYSIWYG dev branch, or CKEditor is not the right version, or CKEditor is not installed in the correct path. Please add the error from the browser console to the original question along with any watchdog errors.


Views contextual filters url position I was wondering if there was a way to change the url position of a view contextual filters. normally, they are at the end of the URL after the view-name but i would like to have them after the language.

ie: example.com/fr/filter1/filter2/view-name

Views in D8 uses for contextual filters routes and you can't put a route parameter first in a route pattern, see Content type slug in route, how?. What you can do is aliasing. I don't know if there is a module for this, but you can build a custom path processor to change inbound and outbound the position of the route parameters in the path so that the View route does work.


How to alter each article's comment setting by PHPMyAdmin After I updated my site, I found out that all the node comments are set to "disabled."   I then went to the specific content type setting page, and changed the default comment setting to read/write, but the nodes of that content type are still disabled. If I change the comment settings for each node, that would be a too cumbersome work. Is there a way to change each node comment setting using a SQL command?

Comment settings for each post are stored in the node table. You can run the following, or similar, query:

UPDATE node set comment = 2 WHERE type = 'foo';


Commerce Search API with Custom field search I have a Custom search form with multiple fields on my front page. After clicking on submit button, user would be routed to search result page. (Ideally, a Commerce search view). On search result page, all facets blocks are enabled.

Products are mapped with Commerce Stores (cmp_store). I have used field collection for Store so Seller can add multiple stores. Each store has Zip code associated with it.

I am getting zip code in my search facets.
But if User has not entered zip code then I want search result based on User's current location + 25 kms radius. Sorting should be location based.

I guess I have to alter the search query. Not sure how to alter query.

How can I do that ?

I have added related fields to the index configuration page under the "fields" tab. First have added the store then the zip code.


Jquery update "intterupts" Admin Menu Drupal 7 system. minimalistic, almost no modules installed and the site works fine. The problem:

From the moment I've installed the module Jquery Update, There is no more Dropdown by the Admin Menu module... Please help.

Navigate to

admin/config/development/jquery_update

and set the Default jQuery Version to 1.8 or higher

and the Alternate jQuery version for administrative pages to 1.7 (1.5 and lower has issues with views and other modules)

Then clear your Drupal and browser cache if need be.

If you don't see these settings in jquery update ui then install the latest dev version of jquery update.


Display default image if the image isn't set Case

A custom image field has been added to the user entity, this field contains a default image for users, which should display if an user doesn't add an image. This field is used on multiple templates across the site.

Problem

Only at the user's profile page is the default image displaying when the image is not set (if set will show the image).
Node templates and other entities will not display the default image. I tried to display the field with theme_image() with no success.

Question

Why won't it display the default image?

When I dump the information about the fields attached to the current user, the field_picture is an empty array if the user has no image set. When the user does have an image set it will return this

Setup

Field name: field_picture
Field type: picture
Field module: default image field module.

try: make sure in the field settings you have set BOTH default images.  There is one specific to that instance of the field, and one everywhere else it is used. The second is further down the screen:

IMAGE FIELD SETTINGS

These settings apply to the Image field everywhere it is used.


How can I override JavaScript settings used by a contributed module? I am using the Fivestar module for rating purpose in my project.
In that module there is a function called fivestar_add_js(), which is used to add the necessary terms to Javascript. The function is given below:

function fivestar_add_js() {
  static $js_added = FALSE;

  // Add necessary javascript only once per page.
  if (!$js_added) {
    $settings = array(
      'titleUser' => t('Your rating') .': ',
      'titleAverage' => t('Average') .': ',
      'feedbackSavingVote' => t('Saving your vote...'),
      'feedbackVoteSaved' => t('Your vote has been saved.'),
      'feedbackDeletingVote' => t('Deleting your vote...'),
      'feedbackVoteDeleted' => t('Your vote has been deleted.'),
    );

    drupal_add_js(drupal_get_path('module', 'fivestar') .'/js/fivestar.js');
    drupal_add_js(array('fivestar' => $settings), 'setting');
    $js_added = TRUE;
  }
}

In that function I need to replace the word from vote to rating.
How can I do this?

As those strings are passed to t() the faster way to rewrite those strings is to overwrite then in the settings.php file, using something similar to the following code (write only the code for the Drupal version you are using):

// Drupal 6.
$conf['locale_custom_strings_en'] = array(
  'Saving your vote' => 'Saving your rating',
  'Your vote has been saved' => 'Your rating has been saved',
  'Deleting your vote...' => 'Deleting your rating...',
  'Your vote has been deleted.' => 'Your rating has been deleted.'
);

// Drupal 7.
$conf['locale_custom_strings_en'][''] = array(
  'Saving your vote' => 'Saving your rating',
  'Your vote has been saved' => 'Your rating has been saved',
  'Deleting your vote...' => 'Deleting your rating...',
  'Your vote has been deleted.' => 'Your rating has been deleted.'
);


Why is an entity reference view field only showing one view result? I have a form field on a node create form that is an entity reference, referencing a view that displays all of the appropriate results. The view displays users with a relationship to a content field on the user, so the fields returned are all content. There is also an argument that takes the logged-in user ID. On the node create form, the field in question, when set to show unlimited results, only shows the last result from the view. I feel like I've gone over any technical reason this could happen, now I'm wondering if this is a bug with user views, or elsewhere. I haven't found anyone reporting this yet in my searches, so I thought I'd post it here.

I was having this issue as well, and it came down to the view returning a different entity_id than the one(s) I thought it should be returning. This happens because of incorrectly formed relationships.

A way to check this is to add a "dpm($options);" (if you're using the devel module) in the entityreference_options_list function of entityreference/entityreference.module file (just after the $options are returned from entityreference_get_selection_handler) to see what options it is retrieving from the view.

I started a new Entity Reference view that just returned the entities that I wanted, and then I built my relationships backwards from there to finally get the correct number of entities in my form.

I hope this helps!


Install Drush on shared hosting with SSH access? I have SSH access on shared hosting and I followed this guide to install the composer: https://getcomposer.org/download/

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

I got the composer.phar installed/downloaded into custom dir /composer/composer.phar

And it works if you run it php composer.phar.

Then I ran php composer.phar require drush/drush:7.x to install drush. And it installed in the /composer/vendor/bin.

Now, if I run php composer.phar drush I get error:

[Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "drush" is not defined.

I set paths PATH=$PATH:~/composer/vendor/bin and PATH=$PATH:~/composer/

If I run just composer or drush I get The program 'composer' is currently not installed. To run 'composer' please ask your administrator to install the package 'composer'.

you can also install manually as long as you have ssh access
# get drush latest 8 version
# drush 8 works with D8, D7 and D6
# https://github.com/drush-ops/drush/releases
wget https://github.com/drush-ops/drush/releases/download/8.4.2/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;


Change contact form to email based on selection? I am attempting to change the email a custom contact form is sent to based on what selection the user makes when filling out the form. Is there a way to do this in Drupal 8?

There isn't a way to make behave like its D7 incarnation without some custom code. You might, however, find this issue on d.o. useful; it contains a patch that adds a customizable block which lets you select a contact form (and thus recipient) to use.


Theme a specific block id I am looking for a simple and effective way to implement template for specific block IDs.

From what I read in Author information lost after saving node and Drupal 6 Template Suggestions, I came up with the following code, which doesn't seem to work:

function mytheme_preprocess_block(&$vars) {
  array_unshift($vars['template_files'], 'block-' . $vars['region'] . '-' .   filter_xss($vars['id']));
}

From the Drupal documentation it should block-module-delta.tpl.php.

Delta is the block ID, that's ok
Module? What's the module here it's a custom block created by adding a block.

Use Firebug to inspect the generated HTML to get the block name|module !


Views Pager, Can I change Items per page dynamically as provided input? Is it possible to send Items per page limit in query string of view page url and get records according to that?

I think this might help. I normally use hook_views_query_alter in order to alter my view results.


drush language importing untranslated strings I am having 2 environments. A staging and a production one. I want all string to sync the strings, so that whenever a new string comes to staging it is available for translation in production. For this reason I've used drush_language module.

Export via

drush language-export-translations --statuses='not-translated'

This provides a .po file where part of it you can see:

msgctxt "tripping_context"
msgid "Giannis test translations"
msgstr ""

When i run an import on prod via

drush language-import-translations  --langcode="sv"

No new strings are picked up.

Anything wrong I am doing here?

The statuses flag is saying to export untranslated strings, so you are importing an empty file.
Or are there any steps you missed to describe?


My core Comment module is gone Recently I lost comments and everything related. In the module list I see "Comment (missing)". All I did before:

CK editor update
Installed the Better Formats module.

Manual updating the core from 7.27 to 7.28 didn't help. All comment module files are in the folder they suppose to be (modules/comment/). But Drupal doesn't see the module.

Any help would be appreciated.

If the comment module files are there in /modules/comment but not displayed in Admin > Modules it suggests the folder isn't readable by the webserver user.

Check the permissions are correct on the /modules/comment folder to allow read access.

For example:

# Run from Drupal root
# Comment module folder ensure readable
chmod 755 modules/comment
# Recursive chmod on files to ensure readable
find modules/comment -type f -exec chmod 644 {} \;


Add JavaScript into a specific content type I would like to know what is the best way to add a JavaScript file into a specific page basing on the content type. For example, I want to add this:

<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>

So far, what I have done is using this way to add into my specific content type. For the  map_page content type, I adde the below two line of code in page--map_page.tpl.php.

drupal_add_js("http://maps.google.com/maps/api/js?sensor=false", 'external');
$scripts = drupal_get_js();

Is there any other better way? if possible can give some example, currently not really understand well...

I can't comment on the proper Drupal 7 equivalent, but in Drupal 6 sites I do this in a template_preprocess_page.

I will have some logic to make the decision (either based on arg() or page_manager_get_current_page() from panels), and then prepend $vars["scripts"] with the external script.  I prepend so that I don't run into dependency trouble with any local scripts.

I will also sometimes set up a new region called $global_scripts for thinks like Google API and SWFObject that I want to load from a CDN, and this gets printed out before $scripts in the page template.

To be honest, though I normally have all JS on all pages so that the files get cached.


Manually enter cck field data into database I have 1 content type and one cck text field.
if i create node and enter title and text field data and click to save save button its create node and enter data into node and content_field_table perfectly, but if i update cck field data manually into database its not shows update node data.

I can't say I'd advise manually inserting data into the database (there are a lot of API functions for CCK that will help you to do this), but that's for another question.

To make sure the node is reloaded from the database after you've inserted your record(s) just run this code:

$node = node_load($node->nid, NULL, TRUE);

The third argument to the function is $reset, which if TRUE will force the node to be built again from the database, not from the static cache.


How do I enable the WYSIWYG editor on fields? I added couple of Text fields on a content type in Drupal; however, only the in-built "body" fields is WYSIWYG editor enabled. I am using FCKEditor as the WYSIWYG editor (installed under the Wysiwyg module).

How can I get WYSIWYG editor enabled on custom added field?

Click Configure of your CCK field and choose Filtered text (user selects input format) under Text processing. This configuration will show input format selection you need to choose. As long as you configure properly your WYSIWYG module the editor will show.


Adsense tokens "[adsense:XxY:SlotID]" in node content aren't being replaced by ads I've added adsense tags in my node body/content and I'm using Full HTML as text format.

For this Full HTML ipnut format I've enabled "replace adsense tags".
I've also given it the highest "Priority" so that it is done before anything else related to formatting node content.

In the end, adsense tokens are printed as is "[adsense:XxY:SlotID]" and no ads. From developer console I can see one error that states:

TagError: adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them.

I'm quite sure that if these tokens were replaced by ad markup that error wouldn't show up in the developer console.

And to be honest, I'm not sure which modules is responisble for formatting adsense tokens into adsense markup i.e. which modules provides.

Wow, finally solved. Since pages are rendered via Panels the solution was to check "Clean" option from Panel content manager to the node body which removes "dangerous" markup.

In other words it seems like node body doesn't respect text format settings when rendered via Panels. Or at least not all of it without checking this option.


Send POST data to payment gateway on form submit I am running drupal 6 and currently working on payment gateway integration module. I have a basic form in my module which will collect billing information from the user. In the form submit handler, I need to create certain parameters and send the post data to the payment gateway URL. How do I handle this? Any help is appreciated.

Check drupal_http_request().

  Performs an HTTP request.

  This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.


How do I render a field value including its format? I'm reading a field value and its format from the database. How would I render that value with the format?

While you could spend a lot of time dissecting how the Field API works, you really should be using the Field API directly to render field content instead of querying the database yourself. There's a lot of encapsulation and abstraction added to fields that will awaken the Old Gods if bypassed.

Using the Field API, if you want the whole formatted field, complete with label and all values, you want to use field_view_field():

$nid = 1;
$node = node_load($nid);
$output = field_view_field('node', $node, 'field_foo');

// $output is a render array, so it needs to be rendered first
print render($output);

If you just want to display the formatted value of one item in a field, you need to use field_view_value(), which is a little more involved:

// Must load field content for entity before using field_view_value()
$fields = field_get_items('node', $node, 'field_foo');

// $index corresponds to the value you want to render. First value = 0.
$index = 0;
$output = field_view_value('node', $node, 'field_foo', $fields[$index]);

print render($output);

If you want to use a formatter other than the default specified for the field instance, pass it using the $display parameter in either field_view_field() or field_view_value():

$display = array('type' => 'my_formatter');
$output = field_view_field('node', $node, 'field_foo', $display);


alter password reset url I'm trying to alter the password reset link (user/password) to my own language specific URL, but I can't find how I can do this.

How can I change it?

Render user_pass form in your custom url.
drupal_render(drupal_get_form('user_pass'));

OR

In template.php

function mymodule_theme(){
// custom user-password.tpl.php
    $items['user_pass'] = array(
        'arguments' => array('form' => NULL),
        'render element' => 'form',
        'template' => 'templates/user-pass',
    );
    return $items;
}

In user-pass.tpl.php:

php global $base_url;

div class="forgotPassword"
Forgot Password

php
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['name']);
    print drupal_render($form['actions']);
?
/div


I am not able to assign a group to a node while creating it We are using Drupal 7.39 and Services 7.x-3.12 .

We are also using organic groups 7.x-2.7 and while creating a node of type attendance (which is a group content). We are not able to assign a group to it.

We are passing the following parameters:

{
  "type": "attendance",
  "title": "Testing Attendance",
  "field_attendance_status":{
  "und":{
    "tid":3
  }},
  "og_group_ref":{
    "target_id":16
  }
}

I have tried posting group content but didn't work in all field widgets (select, checkbox or auto complete)

I see there exist an issue with that field og_group_ref take a look at that question have an answer with a patch hope to solve the issue.


Generate menu links for a view with contextual filter and parameters in the path I have a view with a contextual filter, and a few tabs corresponding to a taxonomy. In my module.links.menu.yml I have something like this:

mymodule.apple_view:
  title: 'List of apples'
  route_name: view.fruit_view.page_1
  route_parameters: { fruittype: 'apple' }
  menu_name: main

So I have my tab "List of apples", but the URL has the form http://localhost/it/fruit_view?fruittype=apple (which works), but I'd rather have it as http://localhost/it/fruit_view/apple (which also works). I suppose there may be a parameter for .link.menu.yml to achieve this, but I cannot find the full documentation. I checked the documentation and the source, but that didn't help. Any suggestion?

Never mind - solved it. In the view definition, I changed the path from /fruit_view to /fruit_view/%fruittype, and I got the URLs as I wanted them. I also had to remove the menu voice defined in the view, but that's not a problem, since I have to redefine the filtered ones anyway.


How to specify subdirectory for uploads in files dir when adding file field to content type via module? This question is related to: https://drupal.stackexchange.com/questions/39884/how-to-create-file-field-instance-based-on-file-field-info-in-custom-module

If I don't specify directory I can upload file.

However if I try do it I am getting error:

  The upload directory public://osw_majatkowe_m for the file field
  field_osw_majatkowe_m_file could not be created or is not accessible.
  A newly uploaded file could not be saved in this directory as a
  consequence, and the upload was canceled.

osw_majatkowe_m is my content type stored in $type variable.

Code:

    $instance = array(
            'field_name' => $ct_info['file_field_name'],
            'entity_type' => 'node',
            'label' => 'Plik',
            'bundle' => $type,
            'required' => false,
            'settings' => array(

                'file_extensions' => '',
                'file_directory' => $type,
                'uri' => 'public://'.$type,

            ),
            'widget' => array(
                    'type' => 'file_generic',
            ),
    );

    field_create_instance($instance);

I want to have files for content type is seperate directory in sites/default/files.

It seems to me that your directory does not exists (or at least is not writable).
You can make a function to test/create your custom folder:

function create_directory($folder) {
   // Constructs a URI to Drupal's default files location given a relative path
   $dir = file_build_uri($folder);
   // Checks that the directory exists and is writable.
   // Indicate if the directory should be created if it does not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only (FILE_MODIFY_PERMISSIONS)
   $res = file_prepare_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
   if (!$res) {
     watchdog('file system', 'The directory %directory does not exist or is not writable.', array('%directory' => $dir), WATCHDOG_ERROR);
   }
   return $res;

}

Then call this function with $type as parameter: create_directory($type);


2nd block not showing up in D7 I'm building a module with several blocks. But only one is showing up in blocks list.
Calendar shows up in block list but could you see why I cant see my 'frontdoor' block ?

function businesshours_block_info() {
    $blocks['calendar'] = array (
        'info' => t('Little calendar'),
        'status' => true,
        'visibility' => 1,
        );
    $blocks['frontdoor'] = array (
        'info' => t('The Front Door'),
        'status' => FALSE,
        'visibility' => 0,
        );
    return $blocks;
}
function businesshours_block_view($delta) {
    $block = array();
    switch ($delta) {
        case 'calendar':
            $block['content'] = businesshours_block_contents($delta);
            $block['subject'] = t('toto');
            return $block;
            break;
        case 'frontdoor':
            $block['content'] = businesshours_block_contents($delta);
            $block['subject'] = t('front');
            break;
    }
    return $block;

}
function businesshours_block_contents($delta) {
    switch ($delta) {
        case 'calendar':
            return array('#markup' => '
' . _build_calendar() . '
');
            break;
        case 'frontdoor':
            return array('#markup' => '
' . _build_frontdoor() . '
');
            break;
    }
}

Thx in advance.

Remove the return $block in case 'calendar'
function businesshours_block_view($delta) {
$block = array();
switch ($delta) {
    case 'calendar':
        $block['content'] = businesshours_block_contents($delta);
        $block['subject'] = t('toto');
        break;
    case 'frontdoor':
        $block['content'] = businesshours_block_contents($delta);
        $block['subject'] = t('front');
        break;
}
return $block;
}

NOTE: Also check your visibility
Possible values are:

BLOCK_VISIBILITY_NOTLISTED: Show on all pages except listed pages.
'pages' lists the paths where the block should not be shown.
BLOCK_VISIBILITY_LISTED: Show only on listed pages. 'pages' lists the
paths where the block should be shown.
BLOCK_VISIBILITY_PHP: Use
custom PHP code to determine visibility. 'pages' gives the PHP code to
use. Most modules do not provide an initial value for 'visibility' or
'pages', and any value provided can be modified by a user on the block
configuration screen.


How can I send email to user that is not logged in since 30 days? I am using Drupal 7, and I want to send email to registered users who have not logged in to the site since 30 days; for example, an email saying:

  Hello user, you are not login since 30 days.

Is there any way?

You can use the Rules module to do this.

Make a rule that that is triggered when a user logs in. Make this rule schedule sending this e-mail in 30 days. Let the identifier of the task be something like 30-days reminder for [account:uid]. This way, if the user logs in within the next 30 days, the scheduled task will be overwritten - pushing the 30 days e-mail.

Make sure to activate the Rules Scheduler module.


How to grant user User Points equal to certain field's value / calculated value? I've a content type 'Content' with the field 'Value' (an integer). Every time a Content has been published, I'd like to grant the Content's author some User Points, equal to the value in the 'Value' field.

I tried solving the first part of my problem with the Rules module like this:

*Event: A node has been published

*Conditions: Content is of type 'Content'

*Actions: Grant points to a user: ...

However, it's impossible to pick node:field-value in the Points section. I also tried:

*Event: A node has been published

*Conditions: Content is of type 'Content'

*Actions:

 - Calculate a value: `[node:field-value]` "+" 0. (Variable name = result)

 - Grant points to a user: ...

But then, the variable 'result' is not available. How can I solve this issue?

I finally found a solution! I completed the second scenario (the amount of User Points is calculated) successfuly! Apparently, the User Points module didn't know that the calculation was an integer. Therefore, I had to add an extra action Convert data type: Target type: Integer, Value to convert: [result], Rounding behavior: Always down. I called it 'total' and granted the user this amount of User Points.


What do I do after I merge feature files with a remote server? I'm having real trouble getting my head around the Features module. Would someone be able to help me understand it a little better? Perhaps describe it in laymans terms?

Here's the scenario I am working on right now:

I've made a change to some mini-panel and want to move those changes to a remote server with Features.

I create that feature and add the mini-panel and download the files. This part seems fine - I can even view my changes in the file's code. I then merge these files onto my remote server.

It's here I get a bit stuck. Now what do I do?

When I find my Feature in /admin/structure/features it's overridden. What do I do next to update my mini-panel on the remote server?

You will have to revert the feature, So that the configurations in the remote server would be same as that in the code. Feature overridden means, the config in the Code and that in the server is not the same. So by reverting the feature you make the code and the db config the same. Please be cautious while reverting the feature, Sometimes the changes which you have done directly in the server would be lost. It'd be best if you test reverting the feature in your staging environment first.


What advantages does Features offer in deploying changes What advantages does using features to manage deploying changes (versus keeping code updated and data fresh)?

The Features way (near as I can discern):

Features takes configuration (which is ‘content’) re-envisions it as code and builds a module for it, and then pushes it up where it continues to live as an object that has to be maintained as code forever.

The next time the developers update their code, (where the best would include updating their dev database to a fresher copy of production), they get these configuration changes that they too have to manage in perpetuity.

The not really doing anything special way

The original developer updates the configuration on production, (after ironing out these changes in development), then we are done worrying about that configuration change, forever.

The next time the developers update their code, (where the best would include updating their dev database), the configuration changes are included.  No one ever has to worry about overrides and reverting ever.

Obvious Caveat:

If the original developer changes 103 individual settings, remembering and setting them all would be nightmarish.  In this case I would understand using a configuration packager, which is more or less how Features is used, to set the production system to match. But then what?  I don’t understand keeping that project alive after you have updated the settings on prod to match what you did in development.  Features as a fire and forget config missile, I get... as code... I don't get maintaining it after the fact.

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

I started out this post open to Features, after it was regaled by some incredibly trustworthy Drupal gurus.  I had a bad feeling about it, but hoped it would wane.  After writing this, again find myself frustratingly opposed to something everyone else seems to think is the best thing since sliced servers.

The features ideals I can’t wrap my brain around:

I have always approached Drupal with a philosophy less eloquently described by one aforementioned gurus as: “Content comes down, code goes up.”

In Drupal 7, configurations for the system and modules is stored in the database.  The dotted line I've drawn in my perception demarcates content from code is right on that line; code is stored in files managed in Git, content is entered into the UI and stored in the DB.

Using Features for Structure:
On my gut feeling about exports and features, another Guru said: “It’s going to end up in a file one way or another”.

I didn't argue at the time because I wasn't seeing his perspective and wasn't comfortable calling him on it (guru vs. marginally experienced flounder).

I've never thought about it because I wasn't using the paradigm he was thinking about (developer).  I had always just imported the structure, because my brain is always in a different paradigm (site builder) when I’m working with structure.

I haven’t ever done it the way he described.  It is actually clever, and I can see using that method in certain cases.  I realized later when my brain was back in developer mode that I have done something similar this, in a different sort of way; I use Form Builder to build rough forms quickly, then drop them into my code, I don’t export them, because Form Builder gives you access to the code for their construction as you build them out.

This makes me hesitant to say “Features is teh Ahhsumz”

So what am I missing?

You seem to have mentioned the use-case of Features only as a configuration packer, probably with strongarm, or with structure - where you would not use the code once it is run and has made its changes in the database.

But one of the important uses of Features is ctools exportables, such as Views, rules, etc... Here, the settings are much more complex than '103 configuration options' and if you are dealing with multiple developers, a staging site and then production, you can't imagine doing all of this manually on all different servers and instances.


View to display content type and media type Drupal 8
Say I have 1 content type and 2 media types users can create
Content type: Post
Media Type: Picture
Media type: Movie
How can I create a view that pulls all 3? As far as I can see you can only create views that show content, or media but not both in the same view.
I wasnt to create a feed displaying all 3 types of all users on the site.

If there are no relationships among the three entity types, as you have indicated in comments, you could use attachments or blocks. (I'm assuming you want a page that displays all the information.)
Attachment Solution:

Create your View with a page display of one of the entity types.
In the same View create two attachment displays, and use overrides to base them off the other entity types. Attach them to the page display.

Block Solution:

Create your View with a page display of one of the entity types.
Create additional, separate, Views of each of the other entity types, with block displays
Use the block configuration system to place those blocks on the page display


Show Media Preview Image on Views I want to show the Preview Image from Media Youtube videos in Views. But I can't figure out how to display them in views. Is it supported? How?

Figured it out: visit admin/config/media/file-types and pick the file type you want to edit (Youtube media are Videos). Pick one of the file displays (Small, Big, Original) and enable the Youtube Preview Image display. Finally, pick an image style in the dropdown menu.

Then, visit the Manage Display tab. If you previously chose the Small file display, for example, edit the Display to make sure the File will be shown.


Views: how to make an OR condition between filters and contextual filters I have been able to separate Views filters into groups and apply an OR condition, following this article: http://www.webomelette.com/drupal-views-filters-and-or-logic

I also understand how to use the hook_views_query_alter() to make a few contextual filters act with an OR statement between each contextual filter.

What I can't figure out is this: how do I make the conditional between the REGULAR filters and the CONTEXTUAL filters? After altering the query, this is what I've able to create:

WHERE
(
  ( (og_membership_node.gid = '8' )
    AND (node.status = '1')
    AND (node.type IN  ('event'))
    AND (field_data_field_event_type.field_event_type_tid = '12')
  )
  AND(
  ( (node.status = '1')
     AND (node.type IN  ('event'))
     AND (field_data_field_event_type2.field_event_type_tid IN  ('11', '10')) )
  )
)

and I want it to be:

WHERE
(
  ( (og_membership_node.gid = '8' )
    AND (node.status = '1')
    AND (node.type IN  ('event'))
    AND (field_data_field_event_type.field_event_type_tid = '12')
  )
  OR(
  ( (node.status = '1')
     AND (node.type IN  ('event'))
     AND (field_data_field_event_type2.field_event_type_tid IN  ('11', '10')) )
  )
)

To give some background of what I am trying to do: I am using Organic groups, and I want my view to show events, Global, Regional and Chapter events. However, if the event is of type Chapter, I want to only show Chapter events which are in the same group as the page content.

I had manually edited the query to move the regular filters associated with the Chapter filter into the contextual filter group, with this:

foreach($query->where[1]['conditions'] as $condition) {
  $query->where[0]['conditions'][] = $condition;
}
unset($query->where[1]);

There is a module for that (albeit a sandbox module). Download Views arguments in filters. As it is a sandbox module you will have to use git.

With this module you add your contextual filter as a global null contextual filter. Then in your normal filter's section, you refer to your contextual filter via the format %N (%1 etc). In this way you bring your contextual filter down to the normal filter section in views, and you can now apply the conditional clauses there, as well as the other filter logic.


Fieldsets for site builders In Drupal 7, it's possible to group fields for a content type with fieldsets, vertical tabs and so on.

Where are this options in Drupal 8? I didn't find something in the Manage fields or Manage form display tab.

That functionality is provided by the Field Group module.

  Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

There is a Drupal 8 version available.


How to invalidate cache when a config entity is added/deleted? In a MenuLinkContent entity I've a list_string field populated with a $key => $value array of a custom config entity. When I add or delete a config entity the values in my field are not updated until I rebuild the cache.

I think I should set a cache tag, but I can not figure out where I should add the tag and which tag should I use.

Edit: The array is created in a static method on my entity class.

public static function getConfigList() {

  $entities = SvgIcon::loadMultiple();
  $config_list = array();

  /** @var SvgIconInterface $entity */
  foreach ($entities as $entity) {
    $config_list[$entity->get('id')] = $entity->get('label');
  }

  return $config_list;
}

The field is defined via hook_entity_base_field_info().

function svg_icon_menu_link_entity_base_field_info(EntityTypeInterface $entity_type) {

  $fields = array();

  if ( $entity_type->get('id') !== 'menu_link_content' ) {
    return $fields;
  }

  $fields['svg'] = BaseFieldDefinition::create('list_string')
    ->setLabel('SVG sprite')
    ->setDescription('Select the SVG sprite file.')
    ->setSettings(array(
      'allowed_values' => SvgIcon::getConfigList()
    ))
    ->setDisplayOptions('form', array(
      'type' => 'select',
      'weight' => 0,
      'settings' => array(
        'display_label' => TRUE
      )
    ));

  return $fields;
}

List fields support an allowed_values_callback setting, if you use that, then you don't need to worry about cache invalidation.

See https://api.drupal.org/api/drupal/core!modules!options!options.api.php/function/callback_allowed_values_function/8.2.x and


views exposed filters : how to trigger the submit on options click How to trigger the submit on select options click?

This would require for the end-user one click instead of two.
The button could be removed or hide.

Check out the Better Exposed Filters module.

Also, this related post: Where is the "auto submit" option?


Views Module: Related Content by Title Only How to make a "Related Content View" but only by titles.

I know how to do it by taxonomy terms and such I don't want that. I only want it to be related by the terms in the titles of the articles.

For example, lets suppose I have an article with the title: "Stackexchange Drupal Help by Awesomeness People"

I want to make related content View with other articles having title with the words "Stackexchange", "Drupal", "Help", "by", "Awesomeness" and "People"...

I just want related content filtered with the words from titles, to show other articles with this same words. If possible excluding words with less than 5 characters.

I'm trying this for days now, I think this is impossible, or at least I can not do it.
Thank you in advance

The way I achieved this was by using the Apache Solr module https://drupal.org/project/apachesolr

It has a "More Like This" feature that makes it easy to show related content, see the documentation for that module.


Themekey & Organic Groups I have a case scenario in which different organic groups can have different themes. Using "Themekey" I allow the user to select a theme when the group node is created and it works fine. When the user is on the group's home page the right theme is selected but when you click on any content (i.e. group content type) that belongs to that group the theme goes back to the default theme. Is there anyway to apply the parent group theme to all content automatically?

Thank you.

I managed to achieve the desired result by using "OG Theme" Module. It adds a field to GROUP pages from which you can select a different theme for each group. Themekey is quite awesome and I will still use it to do mobile version.


Pre-populate default values into a form to edit a new entity In a Drupal 7 site, I have created a new entity called "atomyx_portal_metadata". This entity works great in all respects. I allow people to define their own entity types (much as you can create your own node types).

While allowing someone to fill out a form to enter values for such an entity type (much like filling out the form for an article for example), I use the following code:

// Get the metadata blob for this job
$metadata = atomyx_portal_metadata_load($job->mid);

// Save the metadata entity in our form array so we can pick it up in the validation routine
$form['metadata'] = array(
    '#type' => 'value',
    '#value' => $metadata,
);

// Add form elements for all attached fields
field_attach_form('atomyx_portal_metadata', $metadata, $form['container'], $form_state );

The "field_attach_form" call correctly adds all necessary form elements for editing the form, and I can validate and save those values correctly in the database afterwards. However, the form elements do not contain the default values defined in the field definition and I don't seem to be able to figure out how to correctly fill in the default values of all fields into the form.

I assume I could do this by looping over all fields myself, and trying to figure out with help of the field api what the default value for that field in the given entity-type is, but that seems like a very ... un-field-api-ish way to do it.

Is there something I'm missing? Is there a call in the field attach api that would allow me to have the fields filled in with default values correctly?

Any and all hints greatly appreciated!

I think I found what the problem was. From the documentation and Drupal code it became clear that what I did in the form ought to be correct: field_attach_form should properly load all fields.

Which led to the fact that it must be the creation of the entity that is incorrect and not the actual form loading of the entity fields.

While examining the entity class I use, I came to the conclusion that the example code I used to build this entity wasn't complete. Upon first creating an instance of the entity, the code should not only save the entity data itself, but it should also call field_attach_insert. Just as it should call field_attach_update whenever the metadata entity exists already but is saved again (updated).

Upon adding this, the field_attach_form call now "magically" loaded the proper default values into the form.

Eureka.


limit information in menu_tree_all_data If I am using the menu_tree_all_data command, how can that be modified to just get some data, not all?  in other words I want to get all of the menu items, but not all of the information, eg
updated: "0",
load_functions: null,
to_arg_functions: null,
access_callback: null,
access_arguments: null,
page_callback: null,

which I don't need.  Thanks

I wrote a function to get rid of unwanted elements

function removeUnwanted($j)
{
    unset($j['link']['load_functions']);
    unset($j['link']['tab_parent']);
    unset($j['link']['router_path']);
    unset($j['link']['page_callback']);
    unset($j['link']['page_arguments']);
    unset($j['link']['title_callback']);
    unset($j['link']['title_arguments']);
    unset($j['link']['theme_callback']);
    unset($j['link']['theme_arguments']);
    unset($j['link']['access_callback']);
    unset($j['link']['access_arguments']);
    unset($j['link']['tab_root']);
    unset($j['link']['to_arg_functions']);
    unset($j['link']['in_active_trail']);
    unset($j['link']['delivery_callback']);
    unset($j['link']['description']);
    unset($j['link']['localized_options']);
    $j['link']['href'] = drupal_get_path_alias($j['link']['href']);

    foreach ($j['below'] as $key => $r) {

       $j['below'][$key]= removeUnwanted($r);

    }
    return $j;
}


How to pick the most expensive shipping rate I have a Drupal 7 site with Drupal Commerce e-shop. For most of the products I charge a flat rate, in 3 tiers, some products cost € 5 to ship, some € 6 and some € 25, implemented as three flat rate shipping services.

I have set up rules to apply the correct shipping rate. These rules check for the presence of applicable products and - if found:

Delete all shipping line items from an order
Apply shipping rate to an order

I've set the weight of the rules so they are evaluated cheap-to-expensive. I figured the expensive shipping would then replace the cheap shipping.

I get both though. My check-out form shows:

-- Article listing --
Subtotal    € 20
Shipping    € 6
Shipping    € 25
Order total € 51

Instead I just want to charge € 25 for shipping.
Is the current behavior the expected behavior? Is my current approach wrong and misguided?

seems like your 6€ shipping rate does not have a maximum, so it gets listed again ?


How to display articles based on group combinations of various group types? I looked at the group module. Defining permissions based on user and entity memberships would suit my needs very well, but sometimes I would need a combination of various group memberships to define if a user is able to see an article.

Example:

There are two group types: site and department.

The user is a member of the group "Paris" and the department "sales". The article is a member of both groups as well.

The user should only see articles which are member of BOTH groups. He should not see the articles which are member of the group "Paris", but not member of the group "sales".

Is this possible?

I think your understanding of membership is not correct. So first a clarification:

Users can be member of one or more groups.
Content, such as articles, can be assigned (= belong to) a single group.

With that in mind, you may want to try an approach like so:

Create a group type of, say, Regional departments (a single group type should be enough for your case).
Create various groups, of group type Regional departments, named something like so (with names that should be self explaining):

Paris - Sales
Paris - Support
Paris - Accounting
Paris - R&D
Paris
Nice - Sales
Nice - Support
Nice - HRM
Nice

For any user, create group memberships depending on their region (Paris or Nice), and depending on their (what you call) departement (Sales, Support, etc). Special case: for each user, also create a group memberships depending on their region (Paris or Nice).
Whenever you create content (articles), you assign it to the appropriate group. Special case: if you assign it to (e.g) group Nice, then any Nice departement has access to it.

That's really it. But on top of that, you can optionally:

Change to which group an article belongs (e.g from 'Paris - Sales' to 'Nice - Sales', eg when sales territories get reorganized).
Grant or revoke access for selected user(s) to specific content (articles), simply by changing their group memberships (e.g if a user gets tranfered to another departement).


how to insert the See All link in a drupal view block i created a  News block that display only 3 lasted news, and i want create a button "See All News"
how i can do it ?

In the footer section of the view add a global text area with the link of the See all news.

STEP 1:

STEP 2:

STEP 3:

Once you are done adding a field in the footer, save the view and the See all news link would work as expected.

For creating the Read more link

Go to the body field of the news.
In the Rewrite Result, you have a checkbox "Trim this field to a maximum length".
Once you check the checkbox, you have the option to "Add a read-more link if output is trimmed.".
Add the Read more text and use the [path] token for getting the path of the node.
Save the view and the Read more link would be there for all the news that you have.

Adding an image to help you in a better way:


How to determine if user X has access to operation Y on node Z How can I programatically determine whether a certain user has "view" (or any other operation) permission for a given node?

I'm trying this, but it doesn't seem to be calling the node access hooks, and it's overall pretty ugly:

$node_grant_storage = \Drupal::service('node.grant_storage');

$current_user_has_access = is_a(
  $node_grant_storage->access(
    $node,
    'view',
    \Drupal::currentUser()->getAccount()
  ),
  'Drupal\Core\Access\AccessResultAllowed'
);

Ideally I'd like something to return a boolean and not a class (I have no use for the "neutral" option here, I just want to know if a user went into the node/X page, would they get a 403 or not).

This was easier than it seemed:

$current_user_has_access = $node->access();

This function has an optional parameter where you can pass an arbitrary user account, which defaults to the logged in user (suits my purpose).


How to create a redirect for specific domain? I'm using Domain Access and Redirect modules. Both work well.

But Redirect module only allows me to create redirects from relative path which affects as follows all my domains.

So how to create domain-specific redirect?

You can do this by using Domain Redirect module.

  This module allows the creation of an internal Drupal path that will
  direct the user to a unique path based on the domain that the user is
  in. The link is based at the path "/domain-redirect/12345" where
  "12345" is the redirect ID that is stored in the database.

OR

Try to use Domain Default Redirection module.

  This small module provides a redirection feature instead of providing
  the default domain contents in the Domain Access suite.


How to check which enabled modules are really used? Is there a module or something else that you can use to check if all enabled modules on a site are really used?

I've searched the internet but with no results ...

It sounds as if you're installing modules on a production site willy-nilly, just to try them out.  I suggest you stop doing this.  While people like me earn some of our living from helping the owners of such garbage piles sort through their wreckage, I'd rather get paid for building stuff than for cleaning up.

Instead:

Set up a staging site for testing stuff. Only deploy on the production site if it is proven useful.
Keep a log of everything you deploy on the production site, with details about when and why. Log also when you disable and uninstall, so you don't forget and make the same mistake twice.

The above is absolutely essential if more than one person runs the web site - but I've found it helpful even if there is only a single webmaster that does it all.

There is really no way of keeping tabs on "what you really use" automatically or semi-automatically. Configuration management is just one of the tasks a webmaster is supposed to do as part of a honest day's work.


Save node via ajax continuously I'm trying to save a node (with the normal node form) via an ajax callback. The first save works. But after that I want to return the same node form again so that the user can update the values and save the node again. But this second save attempt fails. I always get a message like "this form has already been submitted". Are any solutions for this problem? Or shall I write a custom JS menu hook which saves the node programmatically?

Here are the relevant parts of my module

function MYMODULE_form_finding_node_form_alter (&$form, &$form_state){
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'MYMODULE_finding_node_form_submit_ajax',
    'wrapper' => 'finding-form-wrapper'
  );
}

function MYMODULE_finding_node_form_submit_ajax($form, &$form_state){
  $form_id = '#' . str_replace('_','-',$form['#form_id']);
  $commands = array();
  $commands[] = ajax_command_remove('.l-messages');
  if(form_get_errors()){
    $commands[] = ajax_command_replace($form_id, '

');
    $commands[] = ajax_command_replace('#finding-form-wrapper', drupal_render($form));
  }
  else{
    $node = $form_state['node'];
    $form_state = array();
    $form_state['rebuild'] = TRUE;
    $form_state['build_info']['args'] = array($node);
    $form = drupal_build_form('finding_node_form', $form_state);
    $form['#id'] = str_replace("_", "-", $form_id);

    $commands[] = ajax_command_replace($form['#id'], drupal_render($form));
  }
  $commands[] = ajax_command_prepend('.page', '

' . theme('status_messages') . '

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

So I managed to figure it out myself. It just seems that you need to build up the whole new form state manually and then rebuild the form with that state again. Here's my modified code for the ajax submit handler. But if anyone still has a better solution please post your answer here.

function MYMODULE_finding_node_form_submit_ajax($form, &$form_state){
  $commands = array();
  $commands[] = ajax_command_remove('.l-messages');
  if(form_get_errors()){
    $commands[] = ajax_command_replace(NULL, drupal_render($form));
  }
  else{
    $node = $form_state['node'];
    $new_form_state = array();
    $new_form_state['build_info']['args'][] = $node;
    $new_form_state['no_redirect'] = TRUE;
    $new_form_state['input'] = array();
    $new_form_state['values'] = array();
    $new_form_state['method'] = $form_state['method'];
    $new_form = drupal_rebuild_form('finding_node_form', $new_form_state);

    $commands[] = ajax_command_replace(NULL, drupal_render($new_form));
  }
  $commands[] = ajax_command_prepend('.page', '

' . theme('status_messages') . '

');

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


Drupal Ubercart to Commerce Migration: any solution for uc_file (file downloads)? I've recently upgraded a Drupal site from 6 to 7, and now want to migrate from Ubercart to Drupal commerce. The Ubercart upgrade has been completed already just in case.

Ubercart has a module called uc_file that allows files to be assigned to products.

The module has three tables:
1. uc_files: contains the file id (fid) and the name of the file
2. uc_file_products: contains fid, feature product id (fpid), something called pfid, and some other fields for the description, etc.
3. uc_file_users: contains fid, uid, fpid, fuid (?), and other fields.

Has anyone migrated these tables, and if so, what approach did you take? The most important data I need to migrate is the actual line item purchases, so the users will be able to access their purchased downloads.

I have commerce_migrate_ubercart installed, but it doesn't appear to handle the Ubercart File Downloads, which is the entire store.

Well as it turns out, no code was needed.

In case anyone runs into this issue, here's what you need to do:

Download the dev version of commerce_migrate_ubercart and apply the payment patch if it hasn't already been applied.
Disable all Ubercart modules
Carefully follow the instructions in the README.txt file. You'll
want to migrate every available table starting with products, and
working your way to payments (transactions). Save the database early
and often along the way.
Download/configure commerce_file and commerce_license.
Be sure you are able to go end-to-end with your cart and download privileged files in your user/uid/my_files tab.
Download/enable commerce_vbo_views and views_bulk_operations
Edit the rule "Activates licenses of an order", and add the event "After updating an existing commerce order".
Go to your Store's order list page, select the desired order states
that have completed orders, then select all rows in the table, then
click modify order values, and just set the exact same state as
selected before. What we're after here is to force a re-save of the
order to trigger our rule.
You should now be able to view a user and click the "Files" tab to see their downloads assuming permissions are correctly set and the migration worked.
Edit the rule again to remove the added event and you're done.

Easy peasy :)


Drupal JS add noscript after every  tag I'm looking for a way to add the noscript tag after every  tag. Even the file tags. I cannot have alternatives as the client I'm doing this for has made this mandatory for 508 purposes. I believe the software they are using is failing the 508 scan because of this.

Example below.

Your browser does not support Javascript

Your browser does not support Javascript

Use the html.tpl.php of your theme to add the noscript tag using the $scripts array.

$scripts = str_replace("\n", "\n<noscript>Your browser does not support Javascript</noscript>\n", $scripts);

Note : html.tpl.php will apply this for all pages of your theme.if you want to do it for specific content type pages or specific pages then use the specific template.See Drupal 7 template suggestions for more information.