Why is redirect after login not working? I use Ctools Modal to show the login form to users in an overlay. If a user enters right data then he is logged in and the page is refreshed.

The code:

function login_overlay_menu() {
  $items['login-overlay'] = array(
    'title' => t('Sign in'),
    'page callback' => 'login_overlay_callback',
    'page arguments' => array(),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  return $items;
}

function login_overlay_callback($js = TRUE){
    ctools_include('modal');
    ctools_include('ajax');
    $form_state = array(
      'ajax' => TRUE,
    );
    $output = ctools_modal_form_wrapper('login_overlay_form', $form_state);
    if (isset($_GET['destination'])) {
        $output[] = login_overlay_redirect($_GET['destination']);
    }
    else {
        $output[] = ctools_ajax_command_reload();
    }
    print ajax_render($output);
}

function login_overlay_redirect($path) {
  global $user;
  if (isset($languages[$user->language])) {
    $options = array('language' => $languages[$user->language]);
  }
  return ctools_ajax_command_redirect($path, 0, $options);
}

The Catch:

It works well for right data entered at first attempt. However, if a validation fails, then the form is rebuild inside the overlay. and then if the user submits the form, he is logged in but the page is not refreshed (which is very important).

When I debugged the JS code I found that the value of Drupal.settings.ajaxPageState.js changing is the only difference before and after the validation fail.

Before: it is an object containing list of all js files loaded for that page.
After: it is an empty array. (Array[0]).

THE QUESTION:
I am not even sure if this is what causing the error. However if it is, then what may be causing this to happen? OR if not then what may be causing the page refresh to fail?

You can use this hook:

/**
* Implements hook_user_login().
*/
function my_module_user_login(&$edit, $account) {
 // $edit is empty with one time login
 if (!empty($edit)) {
   $_GET['destination'] = 'some-url';
 }
 // Or the form id is the password reset form
 if ($_POST['form_id'] != 'user_pass_reset') {
  $_GET['destination'] = 'some-url';
 }
}


How to "unhook" a hook from a module? I want to use the email_auto_login module. However it implements a hook_mail_alter which I don't want.

/**
 * Implements hook_mail_alter().
 */
function email_auto_login_mail_alter(&$message) {
  $user = user_load_by_mail($message['to']);

  // Don't add tokens for admin, anonymous or blocked.
  if (!isset($user->uid) || $user->uid == 1 || $user->status == 0) {
    return;
  }

  $token = _email_auto_login_generate_token($user);

  foreach ($message['body'] as &$body) {
    $body = _email_auto_login_add_token($body, $token);
  }
}

Is there a way to remove the hook without modifying the above code? I'm running Drupal7.

You should be able to do it with hook_module_implements_alter(&$implementations, $hook) in your module. Simply test $hook and if it is the hook you don't want implemented, unset($implementations['email_auto_login']).


How to auto-yes "drush features-revert-all" ... via terminus On a local machine

drush features-revert-all

will convert all features to codebase definition.
On a local machine ...

drush -y

will auto-yes any command.
On a local machine

terminus -y command

will auto-yes as well.

But when combined, even

terminus -y drush -y yoursite.dev -y features-revert-all -y

... will still ask for a key-press.

How can it be forced to run non-interactively?

You need to add a -- separator to your command. The options for Terminus come before this marker, and the options for Drush come after.

In other words:

terminus -y drush site.dev -- features-revert-all -y

Explanation:

In programs that support it, -- means "all of the options that come after should be treated as arguements". The command terminus drush passes all of its arguments through to Drush.


Issue with menu caching in Drupal 6 I have implemented hook_menu_link_alter so that a menu link is altered for some authenticated users, but not for all. My implementation of hook_menu_link_alter changes properties of the link (HTML attributes), not the destination of the link. The thing that I'm changing is adding an HTML class and other attributes for some users, and not for others. A 3rd party JavaScript that is also loaded reacts differently depending on the attributes.

In Drupal 6 I must clear the cache so that the menu links are rebuild and so that the changes that I have in the hook are applied.

However, that also means that the modified link in stored in the cache. So if another user then logs on who doesn't need the change, then this user also sees the change because it was cached?

I know that a solution could be to have 2 menu's and use PHP code to decide which one is shown to which user, but this is not what I want. I'm building this in a generic module that is available from drupal.org, so I don't was to go duplicating menu's in other people's websites.
Another solution could be to rebuild the menu cache after every logon, but I fear that this is quite resource intensive.

Does anybody have advice on how this can be handled?

Your idea to rebuild the menu cache on each login would certainly be resource intensive, but it would moreso just not work either as the cache is system wide and isn't somehow custom cached across page loads of a user, so, once someone logged in, it would be rebuilt and then accessible to both that as well as any other currently logged in user.  Then, when the next user logged in, it would be rebuilt for all to use by everyone logged in, etc etc etc.

But, you could rather easily as you intimated do this with php inside a new page callback, eg, something along the lines of...

if ( /* users we are looking for is TRUE */ ) {
  // use our new callback
} else {
  // call original callback
}

By doing it inside the callback, you wouldn't be duplicating menu paths, eg, not having module/callback1 and module/callback2 but rather module/callback in itself would do things differently based upon your new logic...much like how going to user as an anonymous user presents a login page, but going to it once logged in presents your profile.

ADDITION:

Given additional commentary, you most probably could overload/overuse the capabilities of hook_translated_menu_link_alter() to accomplish this, eg, something like:

function YOURMODULE_menu_link_alter(&$item, $menu) {

  if ( /* whatever is true for your $item */ ) {
    $item['options']['alter']=TRUE; // Flag this link as needing an alter at display/run time.
  }

}

and then

function YOURMODULE_translated_menu_link_alter(&$item) {

  if ( /* whatever is true for your $item */ ) {

    // do whatever you want to do to it, eg...

    if ( /* this is a special user */ ) {
      $item['localized_options']['attributes']['class']='foo';
    }

  }

}


Create a user and set the password How can I set up the user password when I create a new user using the Rules module?

You can do it by PHP rule action,
first create a function in your custom module
as example

function _yourfuction_user_change pass($account,$pass){
    user_save($account,array('pass'=>$pass));
}

Then in your rule in action section select php action and in it's field
enter

 _yourfuction_user_change pass($account,'111111'); //your password=111111 and $account = available account parameter in field

and another solution is create your on action


How to use an user profile custom field using Rules? Working with Drupal 8.4.5 and Rules 8.x-3.0-alpha3 and Typed Data 8.x-1.0-alpha1

With Drupal 7 Rules, we may use an user custom field for data comparison (address or vocabulary for example). And it was easy to create the condition Entity has field with a select list to choose the right field (cf screenshot) :

Now, in Drupal 8 Rules, the procedure has changed and I did not manage to reproduce this simple condition Entity has field since the Field select list has disappeared and custom fields are hidden in the Data selector suggestions (cf screenshot)

So my question is : how to use my custom field in a Rule (simple data comparison, for example)? What is the new way to write user:field_custom?

Surprisingly, the help text within Entity has field condition says : ...To make entity fields appear in the data selector, you may have to use the condition 'entity has field'...

It seems like an infinite loop to me?

Furthermore, "More useful tips about data selection is available in the online documentation" and there we have documentation about Drupal 7 Rules.

Ultimately, I need to create a Rule in Drupal 8 to automatically give an user role when a new account is saved, depending on a custom field value.

The question below is quite similar.

How to custom field has a value with the Rules module?

EDIT : I found an alternative for my specific need with the module Auto User Role (still in dev version). It seems to work nicely (only when saving a new user, not after editing an user, so the custom field is required at creation)

... since the Field select list has disappeared and custom fields are hidden in the Data selector suggestions.

The above is a partial quote of your question. IMO that's not correct. Instead it should say "... since the Field select list does not appear yet and custom fields are not shown yet in the Data selector suggestions".

And similar to the (my) answer to the question you linked to: those or some of the things that are still missing in the most recent D8 version of Rules. Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.


Allow authenticated users to fill out fields in nodes that only they can see Is it possible in Drupal 7 to allow users to fill out their OWN values for particular fields in a content type?

For example, we want our authenticated users to be able to save nodes to a dashboard. For each node they save there are 5-7 fields we want to make available for the user to enter data into...but ONLY that user should be able to see the notes.

On their dashboard, using Views, they will then see a list of their saved nodes in tabular format with columns that include the data they filled out for each of those fields, as well as the other information that comes from the nodes that the authenticated user can't edit (ie. the title, etc.).

Is this possible?

you can use field permission to set limit to each field
https://www.drupal.org/project/field_permissions

In field permission,
You can set fields that can edit by an authenticated user and can only edit by an admin role, etc.


How can I inject a different service in an existing one, i.e. exchange one already injected service by an own one? The basic authentication provider service uses the user.auth service:

basic_auth.authentication.basic_auth:
    class: Drupal\basic_auth\Authentication\Provider\BasicAuth
    arguments: ['@config.factory', '@user.auth', '@flood', '@entity.manager']
    tags:
      - { name: authentication_provider, provider_id: 'basic_auth', priority: 100 }

I wrote an own service my-user.auth (extending UserAuthInterface) and want my service to be injected into the basic authentication provider instead of the user.auth. How can I do this?

Create a ServiceProvider in your module. And then replace the argument using Definition::replaceArguments like so:

<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the language manager service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('basic_auth.authentication.basic_auth');
    $definition->replaceArgument(1, 'NEW_SERVICE');
  }
}

Please note:

  Note that if you want this service alteration to be recognized
  automatically, the name of this class is required to be a CamelCase
  version of your module's machine name followed by ServiceProvider, it
  is required to be in your module's top-level namespace
  Drupal\your_module_name, and it must implement
  \Drupal\Core\DependencyInjection\ServiceModifierInterface (which
  ServiceProviderBase does).

Relevant article: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services


Use 'Search Api Attachments' file extractor in my own custom 'Search Api' processor plugin I'm writing a custom processor for search api that will search body content of nodes for links to pdfs and extract the content from them to be indexed. It's meant to be able to do the same thing search api attachments can do, it just searches for links inside bodies instead of just grabbing what's in an entity reference or file field.
I'm using the drupal 7 search api attachments bf plugin as an example, but with Drupal 8 it's handled a bit differently

I currently have this file in a custom module located in /src/search_api/processor/BodyFieldAttachments.php

<?php

namespace Drupal\search_api_attachments_bf\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * @SearchApiProcessor(
 *     id = "bodyfield_attachments"
 *  label = @Translation("Body Field Attachments")
 *  description = @Translation("Allows file links inside body fields to be indexed")
 * )
 */
class BodyFieldAttachments extends ProcessorPluginBase{
    /**
     * {@inheritdoc}
     */
    public function getPropertyDefinitions(DatasourceInterface $datasource = NULL){
        $properties = [];

        return $properties;
    }

    /**
     *  {@inheritdoc}
     */
    public function addFieldValues(ItemInterface $item){
        $node = $this->getNode($item->getOriginalObject());
        $body = $node->body->value;
        $files = $this->getFilesFromBody($body);

    }

    protected function getFilesFromBody($text){
        $files = array();
        if (isset($text) && !empty($text)) {
            global $base_url;
            // Parse href attributes in <a> links.
            preg_match_all('/href=[\'"]([^\>\'"]*)[\'"]/', $text, $matches, PREG_SET_ORDER);
            foreach ($matches as $match) {
                // Determine if the file is local. Absolute URL could be local.
                // Beginning double slashes is implicit for the current page's protocol
                // but just apply http.
                if (substr($match[1], 0, 2) == '//') {
                    $url = 'http:' . $match[1];
                }
                elseif (substr($match[1], 0, 1) == '/') {
                    $url = $base_url . $match[1];
                }
                else {
                    $url = $match[1];
                }

                $parse = parse_url($url);
                // Get absolute URL to the file location.
                $path_files = file_create_url('public://');
                if (isset($parse['host']) and $parse['host'] == $_SERVER['HTTP_HOST']) {
                    $uri = 'public://' . str_replace($path_files, '', $url);
                    // Convert back things (such as %20 back to a space).
                    $uri = urldecode($uri);

                    if (file_exists($uri)) {
                        $files_load = file_load_multiple(array(), array('uri' => $uri));
                        $file = reset($files_load);
                        if ($file) {
                            $files[] = (array) $file;
                        }
                    }
                }
            }
        }
        return $files;
    }
}

I have search api attachments installed and I do see that it has FilesExtractor class that handles file extraction but I'm not sure how to call upon it from my plugin and get it to use the config that's in place for Search Api attachments. Would I just create an instance of the FilesExtractor class and use one of its methods? Or is there some proper way to tap into it?

I was able to use the search api attachments file extractor by extending it.

The FilesExtractor class itself was a processor plugin. So I was able to access all the functionality by using

class BodyFieldAttachments extends
\Drupal\search_api_attachments\Plugin\search_api\processor\FilesExtractor

instead of

class BodyFieldAttachments extends ProcessorPluginBase

Then I could just override the specific functions that need to be overwritten while having access to all the functionality the search api attachment plugin had.


How to get a dropdown list with content of other content type I have a content type trainer where i have the fields trainer_name, trainer_tel and trainer_email.

I have a second content type club where i want a field that is a dropdownlist with all the trainer names of content type trainer.

How can i do this?

You need to use Entity Reference module..

Project page says

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field

  Four widgets:

  Two implemented on top of the Options module (Select and
  Radios/Checkboxes),

  Two autocomplete widgets (one with one text field per entry, one
  tag-style with comma- separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.)

  A "Rendered entity" formatter, that renders the references entity
  using a configurable view mode

  Integration with Views (for both forward and backward references)

  Integration with Entity Metadata (and as a consequence with Search API
  and the like)

  Integration with Devel generate

  Integration with Feeds and Migrate (>= 2.3) for painless data import


Creating a dynamic contextual filter list I would like to make a grouping of articles based on the year and month.  In other words something like

April, 2013
March, 2013
February, 2013
January, 2013

Each would be a link to the articles section and provide a contextual filter (/articles/2013/1 for January 2013).

I've tried playing with the views module to create this view.  I selected only the posted date and then formatted it to show only the Month and Year.  Then I turned on aggregation to group the results together, but it appears aggregation is using the entire date (including the day).  I also tried grouping by the posted date in the table settings but there doesn't appear to be a way to rewrite the results of the group header.

Is there a way to do this with views or some other module?

I have personally done the contextual filter part of it and can confirm it works very well and is easy to setup.

Simply add a contextual filter for "Content: Created year" and "Content: Created month" and then set the Path of the view to "/articles". I use basic validation for the contextual filters and have also setup something for no results so the users aren't presented with a blank page.

I'm not quite sure what you're asking for with the other part of the question.

I think the easiest way of going about this is to create a separate Views block and add a field that contains the post date. You can then use a custom Date format to display the post dates the way you want them. "F, Y" should do it.

Turn on Aggregation and make sure it's grouping the results together and you should be good to go. You can now use the rewrite as link to accomplish what you need. You may need to add a couple of other hidden fields to get all the parameters you need.

UPDATE: I realized there is a problem here. Views aggregation works on the raw SQL data only which is what I think your original problem was. This means that group by date doesn't actually work as you mentioned earlier. There are a couple solutions I came across http://drupal.org/node/388140, http://drupal.org/project/views_date_format_sql, and http://groups.drupal.org/node/40356.


How can I easily verify if a core or module update has not broken anything? When I update drupal core or even a couple of modules, I'm always afraid if something breaks. What easy way is there to test a site if anything has broken? Its not feasible for me to test a site that has over 1000 pages.

In general Drupal core updates should not break Drupal core. If you upgrade stable community modules to a newer stable release -- again you should not encounter regression error problems.

That being said and long as your not the edge with alot of modules it shouldnt be such a huge worry -- but I similar worries. Backup, Backup, Backup always.

I doubt you have 1000s of unique pages. There are tools like Selinium, or JMeter or Java's The Grinder that let you script interactions with a webpage for known results. You could script your set of possible necessary functionalities on a handful of generic pages.

There's no way around testing if you really have to test and assure error-free site usage.


How do I convert AddressField "Administrative Area" abbreviation to full name The Address Field module automatically converts administrative area (i.e., State/Province) abbreviations to full names on node display.  I need to do this in my own custom module but can't find the function that the Address Field module uses to do this.  How can it be done?

As mentioned earlier, there's no function in addressfield that does this, it's hard coded and not re-usable.  Instead, there's a function in addressfield_tokens module which DOES do this.

Using this function isn't really good practice because it's not an official hook (so it could change at anytime without notice), but as long as you're aware of what's going on and you use the proper checks that the module exists, it's the most flexible way to make this happen.  Here's how to use it:

First, ensure that addressfield_tokens.module is installed.  Then you can use this function from line 338 in the .module file:

_addressfield_tokens_state($country, $state)

You need the $country because abbreviations are sometimes the same for different countries.  So, if we wanted to find the full name of California, we would do this:

$california_fullname = _addressfield_tokens_state('US', 'CA')
return $california_fullname;


What is the alternative for user_check_password in drupal 8 What is the alternative for user_check_password(), How I can verify a plane password with a user account?

$uid = \Drupal::service('user.auth')->authenticate('testusername', 'testpassword');

if ($uid) {
// do stuff
 }


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

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

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

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

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

(myth is the name of my theme)

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

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

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

Thanks in advance for your assistance.

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

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

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

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

I hope this helps.


Localize nearest store to a zip code in Drupal 7 I just want to let the user enter a ZIP code, and return the nearest store from the database. I have read and I am trying Module Location + Gmap (for visual input), but I think that this module stores all data in a database. Wouldn't it be more reliable to go through a service like Google GeoCode or something? I would appreciate insights from people who has managed this problem before, as somehow I am confused with many different options available in the contributed modules.

Need to use set proxmity in views and Dependencies modules are
Geolocation Field, Views.


How to replace 'reply' link with button? I want to replace the 'reply' link with button. As an intermediate solution I styled the link as a button with CSS, but I want it to be a real html 'button' element. The reason is, I do not want the reply links being visible to search engines, instead of it, I want to handle clicks on buttons with javascript.

I only found this 10 year old discussion on drupal site:  https://www.drupal.org/node/33170.

I created a custom comment.tpl.php and tried to modify the $links['comment']['#links']['comment-reply'] array, but without success.

There are two methods below. Both are equally effective except the second one requires that the <button> element be taken out of the list of links and put elsewhere in the template. This is either annoying or awesome depending on what outcome you're going for.
Method 1: Override MYTHEME_links()
In Drupal 7, you can turn the comment "Reply" link into a <button> element by overriding core's theme_links() function. It isn't pretty, but it's effective.
Add the function below to your theme's template.php file (replace "MYTHEME" with your theme name). Clear your cache for the change to take effect.

function MYTHEME_links($variables) {
  $links = $variables ['links'];
  $attributes = $variables ['attributes'];
  $heading = $variables ['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading ['level'];
      if (!empty($heading ['class'])) {
        $output .= drupal_attributes(array('class' => $heading ['class']));
      }
      $output .= '>' . check_plain($heading ['text']) . '</' . $heading ['level'] . '>';
    }

    $output .= '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class [] = 'first';
      }
      if ($i == $num_links) {
        $class [] = 'last';
      }
      if (isset($link ['href']) && ($link ['href'] == $_GET ['q'] || ($link ['href'] == '<front>' && drupal_is_front_page()))
         && (empty($link ['language']) || $link ['language']->language == $language_url->language)) {
        $class [] = 'active';
      }
      $output .= '
 $class)) . '>';

      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

      elseif (!empty($link ['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes.
        if (empty($link ['html'])) {
          $link ['title'] = check_plain($link ['title']);
        }
        $span_attributes = '';
        if (isset($link ['attributes'])) {
          $span_attributes = drupal_attributes($link ['attributes']);
        }
        $output .= '' . $link ['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Breaking it down...
This bit of code:
      if (isset($link ['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= l($link ['title'], $link ['href'], $link);
      }

was changed to
      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

Of course you'll need to customize the output with whatever you need, whether it be a <form> wrapper or onclick attribute.
Unfortunately we can't use theme('button'...) because that would give us an input element. Of course we could change that by overriding theme_button() but that would affect all input elements on the site, and you would still need to override theme_links() in order to call it.
Method 2: MYTHEME_preprocess_comment()
If you don't mind taking "Reply" out of the links list altogether, this method will also work. It uses the comment preprocessor to unset the link, but not before taking the value of the URL and stuffing it into a new variable.
Again, add the function below to your theme's template.php file (replace "MYTHEME" with your theme name).
function MYTHEME_preprocess_comment(&$variables) {
  if (isset($variables['content']['links']['comment']['#links']['comment-reply'])) {
    $variables['reply_url'] = $variables['content']['links']['comment']['#links']['comment-reply']['href'];
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

Then add this (or a variation of it) wherever you would like it to appear in your copy of comment.tpl.php:
<?php if (isset($reply_url)): ?>
<button onclick="window.location.href='<?php print $reply_url ?>'">Reply</button>
<?php endif; ?>

Clear your cache for the change to take effect.


How to remove the grid from a zone in Omega I have an Omega subtheme that I am working on, and a request has come in to have a zone and all regions within the zone not be gridded.  By not gridded, I mean that I need the zone and all regions inside it to not be bound by any of the widths that 960.gs imposes.  Just having the full width wrapper around the zone is not sufficient for that the requested layout.

I am not sure what the best way to do this is.

Inside template_process_zone() I can remove the grid classes from $variables["content_attributes_array"]["class"]  and inside template_process_region() I can remove them from $variables["classes_array"].  This is a little messy because it assumes prior knowledge of all the grid classes (or at least the patterns), but it mostly managable.

The problem is that I can't see how I can figure out what zone I am in from within a region.  I want to avoid hardcoding region names in the template_process_region() for those to degridify.

I could also override the grid with CSS for a particular zone, but there are a lot of rules to override to future proof any changes.

Is there a well tested solution to this or other options that I am not considering?

Could you elaborate on what it means not to be gridded inside a zone? If you just make a single region inside the zone that is as wide as the zone, then you could lay out content in the region however you want. Your CSS would just have the zone or region class as a prefix to anything else in that region.

Or, are you trying to get rid of the gutters? If so, you could make a custom grid of some number of columns with zero-width gutters. Then you have to add padding and margins yourself to your content. I have a site with an Omega grid-based layout with zero-width gutters, and do some non-grid-based layout inside certain regions.. For instance, I have pairs of images side by side inside the right sidebar. They are not aligned with the grid columns.


Views: get image-field with global php im using Drupal 7 and views 3.

in a global-php-field i tried to show the image from field_artengalerie_term_bild. But

print $row->field_artengalerie_term_bild; shows the nid only. then i tried this:

print $data->field_field_artengalerie_term_bild[0]['rendered'];

but it doesnt output the image.

With print_r($data); i get this:

 [vocabulary_machine_name] => artengalerie [field_artengalerie_term_bild] => Array ( ) ) ) ) [field_field_artengalerie_term_bild] => Array ( [0] => Array ( [rendered] => Array ( [#theme] => image_formatter [#item] => Array ( [fid] => 648 [uid] => 1 [filename] => standardbild.jpg [uri] => public://default_images/standardbild_7.jpg [filemime] => image/jpeg [filesize] => 19607 [status] => 1 [timestamp] => 1369566211 [type] => image [field_file_image_alt_text] => Array ( [und] => Array ( [0] => Array ( [value] => standardbild_7.jpg [format] => [safe_value] => standardbild_7.jpg ) ) ) [field_file_image_title_text] => Array ( ) [image_dimensions] => Array ( [width] => 400 [height] => 266 ) [is_default] => 1 [alt] => [title] => ) [#image_style] => thumbnail [#path] => Array ( [path] => taxonomy/term/118 [options] => Array ( [entity_type] => taxonomy_term [entity] => stdClass Object ( [tid] => 118 [vid] => 10 [name] => hjgjhghg [description] => [format] => [weight] => 0 [vocabulary_machine_name] => artengalerie [field_artengalerie_term_bild] => Array ( [und] => Array ( [0] => Array ( [fid] => 648 [uid] => 1 [filename] => standardbild.jpg [uri] => public://default_images/standardbild_7.jpg [filemime] => image/jpeg [filesize] => 19607 [status] => 1 [timestamp] => 1369566211 [type] => image [field_file_image_alt_text] => Array ( [und] => Array ( [0] => Array ( [value] => standardbild_7.jpg [format] => [safe_value] => standardbild_7.jpg ) ) ) [field_file_image_title_text] => Array ( ) [image_dimensions] => Array ( [width] => 400 [height] => 266 ) [is_default] => 1 [alt] => [title] => ) ) ) ) ) ) [#access] => 1 ) [raw] => Array ( [fid] => 648 [uid] => 1 [filename] => standardbild.jpg [uri] => public://default_images/standardbild_7.jpg [filemime] => image/jpeg [filesize] => 19607 [status] => 1 [timestamp] => 1369566211 [type] => image [field_file_image_alt_text] => Array ( [und] => Array ( [0] => Array ( [value] => standardbild_7.jpg [format] => [safe_value] => standardbild_7.jpg ) ) ) [field_file_image_title_text] => Array ( ) [image_dimensions] => Array ( [width] => 400 [height] => 266 ) [is_default] => 1 [alt] => [title] => ) ) ) )

how i have to write my code print $data->field_field_artengalerie_term_bild[0]['rendered'];to get the image.

regards

I had the same problem and very simple solution for it I found just need in output write

 print render($data->field_field_artengalerie_term_bild);

always my solutions is shortest ;)


How declare my service via dependency injection in construct? i have a class

  Paybox

This class is declare as a service.

In my controller class, i inject this service like this :

public function __construct($payboxService) {
    $this->paybox = $payboxService;
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('paybox_services'),
    );
}

This declaration work fine, but i see sometime this in the constructor :

public function __construct(Paybox $payboxService) {
    $this->paybox = $payboxService;
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('paybox_services'),
    );
}

They add the Type Paybox before $payboxService.

The 2 method work.

Can someone explain me the difference ? and what is the right way for inject the service ?

Both code snippets work indeed, the second one uses type declaration:

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

You can use type declaration to force specific arguments in your methods parameters. If, for instance, someone should create a new class from your first code snippet and inject something other that your Paybox class your class will not throw errors. In the second example you are enforcing the first parameter to be of type Paybox. If something else is passed PHP will throw errors. If you make your code available as an API for other people they can see what kind of parameters are required without checking the full logic of your encapsulated code.

Furthermore, your IDE will play nice with type hinted parameters providing you with suggestions and better doc block generation.


Troubles with external configuration I'm working in the creation of a custom profile.

When the installation is already finished, on the configuration module /admin/config/development/configuration appears the following warning

  The staged configuration cannot be imported, because it originates
  from a different site than this site. You can only synchronize
  configuration between cloned instances of this site.

All my configuration based on new changes is exported to

  web/profiles/DISTRIBUTION_NAME/config/install

using the following sh file

ddev exec drush cex
find ./web/profiles/DISTRIBUTION_NAME/config/install/ -type f -exec sed -i -e '/^uuid: /d' {} \;
find ./web/profiles/DISTRIBUTION_NAME/config/install/ -type f  -exec sed -i -e '/_core:/,+1d' {} \;

rm -f ./web/profiles/DISTRIBUTION_NAME/config/install/core.extension.yml ./web/profiles/DISTRIBUTION_NAME/config/install/update.settings.yml ./web/profiles/DISTRIBUTION_NAME/config/install/file.settings.yml

so, what i'm doing wrong or what else is missing?

The problem was about a relative path in the file:

  web/sites/default/settings.php

$config_directories['sync'] = 'web/profiles/DISTRIBUTION_NAME/config/install';


Features can export everything? Built all blocks, menu, taxonomies, view etc in Drupal CMS on localhost machine, but I need to export everything to the live server. Is it possible to use features or just export sql?

The Features module allows you to export all the configurations in code (instead of DB). It is very usefull when you have 2 separated versions of database, in example one for your localhost or test installation, and one for your live/production website.

However, if you want to deploy the local database to the live server too, it is not necessary to export everything with Features.


Get the published date of a node I would like to get the published date of my node. On the site I created a news block with a view. In the view I added a field and customised it by the rewrite results with "published on {{ created }}". But sometimes I create the news the day before, then it shows the created date, but I will like to have the published date.

What's the name for the published date? {{ publish_on }} didn't works.

There isn't a published date out of the box.

You can try using Publication Date module.

  The Publication Date module adds a "Published on" date for each node,
  containing the date when it was first published.


What would cause a Drupal site to display a 500 error or a blank page depending on browsers? After moving a site to the final server, I cannot anymore access the site. When I go to the home page, I get a WSD on Firefox, and a 500 error on Google Chrome.

As it is a shared hosting, I cannot access the Apache error log, and I am wondering if anyone experienced that before. How did you find your way out of it?

The article about The White Screen of Death (Completely Blank Page) is a good place to start.

Depending on your shared host, you can often get access to logs if you poke around your control panel, or they sometimes are copied into your home directory.

Since you explicitly mentioned shared hosting, your best best is to open a trouble ticket.  They can tell you exactly what is wrong fairly easily.

If it is a true 500 error, then my guess is that one of these two lines in the .htaccess is causing the problem.

Options -Indexes
Options +FollowSymLinks

You can try commenting them out one at a time and see what happens.  I suspect that your host has AllowOverride set to None and one of those is trying to set a non-default value that the host has set.


Add title for sections in a view so I am trying to create a view via Drupal 8 Structure->Views, and I am setting up this view to display certain shops in certain areas, I would like titles above each type of location of shops, so I would like u.s.a stores to have a title, and canada stores to have a title, is this possible in the view creator? for example:

Or should I create separate views, then sort in the twig files, example stores - can, stores - usa

Please let me know, thanks!

If you want a title for each type of view, I would click the add button for a "header" then click on Global text and enter in the Title you want for that view.

UPDATE:

Also, if you are looking to put in a title for each entry you could look into making that a content type that the view pulls from. It can pull the Title of each entity.


How to get links of translated node edit page in the secondary tabs In D7, if a node is translated, let say in French and if you are in the entity.node.edit_form page then you could find 2 secondary tabs: [French] and [English] pointing to the edit_form of each language.

To achieve this in D8, I looked at the derivatives, but they are loaded once during cache clear and can't evaluate the current entity.

Following the 4k4 comment I have tried to subclass LocalTaskDefault
But I am stuck with the following problems:

1-How can I create a route for a defined language (eg: a route to edit a french node)

2-In .links.task.yml: should I create as many tabs as there are languages (I don't think so)

Here is my .links.task.ymlfile

translated_node_tabs:
  class: Drupal\mymodule\Plugin\Menu\TranslatedNodeTab
  title: 'Translated nodes'
  base_route: entity.node.edit_form
  route_name:  entity.node.edit_form

And here is the very beginning of what I have understood from the 4k4 advice

class TranslatedNodeTab extends LocalTaskDefault {
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return [
        'route'
    ];
  }
  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    $current_node = $route_match->getParameter('node');
    if ($current_node instanceof NodeInterface) {
      $nid = $current_node->id();
      return [
          'node' => $nid
      ];
    }
    return [];
  }
}

Add a derivative for each language:

/mymodule/src/Plugin/Derivative/TranslatedNodeTabDeriver.php

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;

class TranslatedNodeTabDeriver extends DeriverBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = [];
    foreach (\Drupal::languageManager()->getLanguages() as $language) {
      $lang_id = $language->getId();
      $this->derivatives[$lang_id] = $base_plugin_definition;
      $this->derivatives[$lang_id]['title'] = $this->t('Translate @language', ['@language' => $language->getName()]);
    }
    return $this->derivatives;
  }

}

and then you can get the language id with $this->getDerivativeId() in the plugin class:

/mymodule/src/Plugin/Menu/TranslatedNodeTab.php

<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Routing\RouteMatchInterface;

class TranslatedNodeTab extends LocalTaskDefault {

  /**
   * {@inheritdoc}
   */
  public function getOptions(RouteMatchInterface $route_match) {
    $options = parent::getOptions($route_match);
    $options['language'] = \Drupal::languageManager()->getLanguage($this->getDerivativeId());
    return $options;
  }

}

/mymodule/mymodule.links.task.yml

translated_node_tabs:
  class: Drupal\mymodule\Plugin\Menu\TranslatedNodeTab
  deriver: Drupal\mymodule\Plugin\Derivative\TranslatedNodeTabDeriver
  base_route: entity.node.canonical
  route_name: entity.node.edit_form


Accessing Drupal array values I'm noobing my way through countless websites trying to find an answer to accessing a value in a Commerce field array.

I somehow managed to throw together the following code to retrieve a value for a workflow rule I'm writing:

$product_id = $current_line_item->commerce_product;

The result is: array(1) { ["und"]=> array(1) { [0]=> array(1) { ["product_id"]=> string(2) "14" } } }

I can't figure out how to get any deeper into the array than that. I need to return the product_id value in this array.

Can anyone guide me on the best way to do this?

Devel is super useful to help you figure out these type of things.

Once enabled, you can write dpm($product_id) and it will print out a nice organized structure of the array.  From there, you can click on any item and it will show you how you can access the item like ['und'][0]['product_id'] in your example.

Depending on what exactly you're trying to do, there may be different ways to get the info you need.


Restrict admin from disabling userprotect I've installed the user protect module on a site to allow another user to have complete admin access to the site, without the ability to edit my own administrator account. The problem with this it, they need to be able to access pretty much absolutely everything else, except for the ability to circumvent user protect.
At the moment, it is set up to stop them from editing my user, which works fine, unfortunately they are easily able to simply disable user protect.

What can I do to let them do almost everything except lock me out? So they shouldn't be able to disable that module, and they shouldn't be able to change their own permissions to be able to access that module.

Create another custom role, and add all of the permissions they will need, to that role. Leaving out the ability to administer user roles, and such.

It probably sounds tedious, considering you'll be adding back almost all of the same permissions that admin has. But, that "almost" is important and makes all the world of a difference with regard to security of your website.


#2013 error when starting the dev desktop My computer (a Mac) froze while I was working on a site, and I had to switch it off by holding onto the on/off button. When I tried restarting the dev desktop, it kept giving the "Process start timeout" error; when I tried accessing the database, I got the following message:

  #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 61
  phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

Do you have any idea on how I can resolve this?

I've found a solution, but now I keep getting this message:

  The specified file temporary://fileJ75lqi could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

Your first error seems to be related to a problem with port numbers/bind address of the MySQL server; see this post for a bunch of suggestions for a fix.

The second error is a permissions issue; you need to give your web server user write permissions over the "sites/default/files" folder, for example using the following command:

chmod -R 755 /path/to/root/sites/default/files

If you don't know how to do it I'd really advise getting someone who does to help you, that's messing about with POSIX permissions and you need to know what you're doing or things can go horribly wrong.


Use Javascript to Incrementally Add a Numer to a Selected Class I am dynamically generating content using Drupal. I am running javascript that places a div before another div. The code works fine, and looks like this:

  $(function() {
    $('.views-row-1 .content .body').insertBefore('.views-row-1 .content .field-name-field-image-one');

   });

My issue is that because the content is generated dynamically, the class "views-row-#" changes incrementally. For example, if I have 3 elements of content on the page, Drupal will create the class views-row-1 for the first one, views-row-2 for the second, views-row-3 for the third.

What I have done (which is not ideal) is written out a line of code for each piece of content like so:

  $(function() {
    $('.views-row-1 .content .body').insertBefore('.views-row-1 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-2 .content .body').insertBefore('.views-row-2 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-3 .content .body').insertBefore('.views-row-3 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-4 .content .body').insertBefore('.views-row-4 .content .field-name-field-image-one')
   });

I will never know how many pieces of content there will be because it's dynamic, so I'm looking to have the javascript add the number to the class. Is this even possible?

I don't think you really need to add the number to the class; the elements that you're targeting also have the .views-row class on them so you can use a bit of contextual jQuery to get the job done in a couple of lines:

$('.views-row').each(function(i,e) {
  $('.content .body', e).insertBefore($('.content .field-name-field-image-one', e));
});

I haven't tested that but I can't think of a reason why it wouldn't work.


Are there general css paths for drupal Is there a specific drupal way to focus on one specific part of a nodes element in the css path? For example if I change the H2 element within my theme css it changes all H2... How can I change one specific one on the page. The object is to be able to focus on particular elements to make them unique... If this is possible how do I write the style declarations?

Drupal allows your site to have many Themes installed. Themes can define their own HTML structure to make your site look a certain way. Drupal has a few themes the ship out-of-the-box.

Depending on the theme you use it may or may not contain HTML classes or ids in the source to easily target specific items on the page. Typically, themes and Core html is fairly darn flexible.

Looking at the Zen Theme HTML and CSS markup you can see it has fairly specific rules to get at and theme alot of the content from Zen and also core drupal themes: Useful CSS selectors to add to your stylesheets


How do I use paging in a content type containing a paragraph? I created a content type with just one multivalue field which turns to be an "entity type revisions" (i.e. Paragraphs).

I would like to have paging working on this setup (when number of Paragraphs exceeds some quantity) but just creating a view with paging does not work as the "pageable" content is the content type itself, not its fields.

Having Paragraphs as a standalone content type is a no-go as I do not want to have them scattered in the content section.

How can I achieve this?

Build a view for paragraphs and place it in the content type with an EVA display  (Entity Views Attachment).

To do this add a EVA display, connect it to the node entity (content) and bundle (content type) in the Entity Content Settings, select as Arguments the ID of the entity the view is attached to and add a contextual filter for the parent id.

Now the view appears as field in the content type and you can use the pager from the view for the paragraphs inside of the field.


save node after paypal payment success In my projects, Whenever Authenticated user create new content(page) they should redirect to paypal for done payment when they click save. Once Payment Success Node should be save otherwise its should not save.

Please help me for Fix this concept.

Thanks in Advance

Get the response from Pay-pal if the response code is 200 save the node otherwise don't save it.

for example :

if ($responseCode == 200){
  //node_save($node);
}
else {
  print "payment failed";
}

https://www.drupal.org/node/1207878
check this for more info only for condition to check the payment status.


How to search by taxonomy terms I created a taxonomy called tags.  I added terms to the vocabulary list.

Then I created a content type called News Item.   You can apply tags to News Items.

I created a view to list News Items.

How do I set up a search box that let's people search News Items by tags?  they should be able to search by multiple tags.  So if the search words are "tutorial learning-resource", then show all news items that have both the tags tutorial and learning-resource.

How do I do this?

If I understand well, I think that you can do this with Views, so you can expose a filter related with Taxonomy: Term ID related with your Vocabulary. Remember that you can use the operator 'Contains' if you want to be more laxed in the search.


Views result sorting using arguments Is there any option available in Drupal views to sort views result using the arguments provided (contextual filters)

I am trying to integrate a search functionality using views. My problem is that contextual filter will list only matching results, I need all the results but it should sort according to the arguments passed using contextual filters. Is that possible?

I.E.   I pass the following string to a contextual NID argument:
1099+1100+1102+1098+1101+1097

I expect the order of the nodes in the view to be the same as the order as passed in through the argument.

This is what helped for me.

https://stackoverflow.com/a/2474164/28672

Using the second option to generate the view manually then modifying the array in the result property.

And this is the code I used to sort the results to the argument

 // Sort the view based on the argument now we've generated it.
  $results = $view->result;
  $view_argument_array = explode('+', '1099+1100+1102+1098+1101+1097');
  $new_result_order = array();
  foreach ($view_argument_array as $nid) {
    foreach ($results as $result) {
      if ($result->nid == $nid) {
        $new_result_order[] = $result;
      }
    }
  }
  $view->result = $new_result_order;


How do you change the LDAP DN for a user? We are using LDAP integration on a Drupal 6 system (with the "LDAP authentication" module).

During initial log-in, the user account will be created and the DN (Distinguished Name) for that user will be set automatically.

Now, due to some structural changes, the DN for some users will change slightly.

Is it possible to somehow change the DN that is used by Drupal, or to force some kind of "re-authentication" of Drupal Usernames with the Active Directory? Or do I have to edit the ldap_dn in the database?

If memory serves me the DN will get auto updated next time they log in.  No editing necessary.


Show specific gmap in block based on node id I am trying to show a gmap for a specific location, using the content: mapping coordinates for gmap in a view in drupal 7. The map itself shows fine in content for the page view, but if i clone it to block it shows all maps for that content. I cannot figure out how, without using php, to filter by the current node.

For example, node id 2 has coordinates so show the map for that node in the view for the block. and only node 2, not nodes 3,4,5,7.

I am really trying to do this using views and block and not php code in blocks.

Add an argument to the view, the argument is the node ID, then you'll be able to retrieve fields and information only for the viewed node.

Example: http://through-my-eyes.be/portfolio/events/2011/04/07/drupal-government-days-2011


How to hide the submit button on a node add/edit form page within which a entity reference select list has no valid option? Registration content type has a required entity reference field. The widget of this field is a select list, the options are populated with a views entity reference display output. I want to hide(unset) the submit button if the views entity reference display returns no value.
I've asked a question here for reference, I'm suggested to post a new question.

You can do this by using hook form FORM ID alter .

Once hooked in you find the $form item for the drop down list.  It'll be somewhere like

$form['field_my_entity_ref']['und']['#options']

So you should be able to make a check on the values in that array and if there are none then make the Submit button disabled .  My guess is

if ( count($form['field_my_entity_ref']['und']['#options']) < 1 ) {

   $form['#submit']['#disabled'] == TRUE;
 }

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#disabled

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7.x


How to define multiple cronjobs within single module? What would be a good way to define two (or more) cronjobs without creating multiple modules?

As far as I know, in order to define a new cronjob, a hook_cron needs to be used like following:

function example_cron(){}

However, I have come to the point where I need to create new cronjob (in order to set different launch times using Ultimate Cron).

At first I looked at Ultimate Cron module and it's hook_cronapi hook as in documentation. However, that and other hooks doesn't really work - https://www.drupal.org/node/2842834

How should I implement it without creating additional modules and using hook_cron's?

As commented in that that issue and various others before, custom cron jobs are defined using config entities, in the same way that ultimate cron defines the default cron jobs.

Just export what you have by default, copy one and adjust the callback/cron configuration, then import it again or define them in your config/install folder for a new module.


highlighted and help regions I'm teaching myself Drupal theming, so naturally, one of the first things to think about with my (Zen) sub-theme are regions. However, the documentation is lacking in its explanation of the meaning of a couple of the defaults.

On the Assigning Content to Regions page, it says:

  Drupal 7 adds Highlighted and Help as default regions. By default, the textual content of the Help region is the same as the $help variable was in page.tpl.php for Drupal 6.

This is very bad copy, because it never actually states what these regions are for. And although the meaning of most of the regions (content, header, footer, the sidebars, etc.) is pretty obvious, I'm a bit fuzzy on the precise meanings of Highlighted and Help. Is Help the place where system messages (like the "theme cache is being rebuilt on every page view" message I get while I develop) are printed... or is that what Highlighted is for?

Basically:

$messages is where your system messages are put via drupal_set_message()
$help is created from http://api.drupal.org/api/drupal/modules%21help%21help.api.php/function/hook_help/7
and I have never used the mission statement stuff but apparently that's what the highlighted region is used for now and is described in greater detail in http://drupal.org/update/themes/6/7 which has a lot of information on the d6 -> d7 theme changes.


call external form in ajax callback I have two forms (A & B) in custom module. Form A containing three fields(each field is dependent drop down) and Form B containing only one field (markup field to show data).
The problem is that when I change either field from Form A then its dependent fields within form A an also markup field from Form B should be updated via ajax.

Here is the callback function used in FORM A. After calling, it returns fields from Form A. But I want it also return field of FORM B.
(One Callback to render two forms at a time)

<?php
 function mymodule_ajax_callback($form, $form_state) {
     return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#key_wrapper", render($form['keys'])),
            ajax_command_replace("#display_wrapper", render($form['display'])),
        ),
     );
 }
?>

You can use..

function custom_conditional_form($form, &$form_state) {
  $form['form1']['drupal_love'] = array(
    '#title' => t('Do you love Drupal?'),
    '#type' => 'radios',
    '#options' => array('yes' => t('Yes'), 'no' => t('No')),
  );
  $form['form1']['how_much_love'] = array(
    '#title' => t('Great! Tell us more:'),
    '#type' => 'textfield',
    '#states' => array(
      'visible' => array(
        ':input[name="drupal_love"]' => array('value' => 'yes'),
      ),
      'required' => array(
        ':input[name="drupal_love"]' => array('value' => 'yes'),
      ),
    ),
  );
  $form['form1']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}


Allow only certain user type to create account I have to add new role, for users than can create accounts for others.

I create new role and add create profile content permission.

But when I am anonymous link 'clear new account' still appear and I can create account. I want only certain role to create account, not everyone.

Could somebody give me any advice?

To disable account creation by anonymous:
At admin/user/settings check "Only site administrators can create new user accounts"

Allow the account-creator role to administer users:
At admin/user/permissions -> user module -> administer users

Use a module such a Protect Critical Users if the account-creator role should not be able to touch the superuser (user1).


Send "Views PDF Display" generated PDF by mail as attachment TLDR: How to send Module "Views PDF Display" generated PDF by mail as attachment without another deprecated module ?

I have a Drupal site with the Views PDF Display module on it.

I can generate a custom PDF for my order, and all is nice, except for one things. I need to send those PDF one by one by mail as attached file for the past year of commands, and i looked around for a while without seeing an answer.

I found that one the module page, they talk about two modules that does that, but the fact that both modules are 7 years old and thus not covered by security policy is a 'no'

Other idea to generate all PDF from the last year is just not possible as it will be too much PDF for the server to handle

Do you have any idea for me to retrieve those PDF from the views and to send them by mail as an attachment ?

I tried a couple of things with views directly, but I had no luck, so I turned to curl. You can create your pdf display and give it a path. Hit that path with curl to download the file that will be generated by your view. My example below is pretty simple, but you can pass arguments with the url just like you would normally.

 $pdf_page = "http://yourplace.net/pdf";
  $pdf_file = fopen('/tmp/my.pdf', 'w');
  $ch = curl_init($pdf_page);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_FILE, $pdf_file);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($pdf_file);

I tested this with a pdf display built on Views PDF and it worked well. Maybe someone has an answer that utilizes views directly instead of using curl.


How to add Jquery Validation to Custom form and set error to field? I want to implement client side validation using jQuery on my custom form.

I have enabled clientside validation contributed module

I have successfully attached custom js file using following code:

 $form['#attached']['library'][] = 'custom_form/cl-validation';

And in the JS file I have written below code:

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

        var selectedCountry = ''

        $("#country").change(function(){
          selectedCountry = $(this).children("option:selected").val();

        });

        $('#user-number-value').keyup(function(){
              $(this).val($(this).val().replace(/(\d{2})|([a-z]{2})\-?/,'$1-'))
        });

         $("input#user-number-value").focus(function() {
            if(selectedCountry == undefined || selectedCountry == '') {
                $('#user-number-value').va('')
               // I want mark country dropdown as red and show a error
            }
        });

    }
  };
})(jQuery, Drupal);

I am not getting how to do this using jquery and stop form submission.

Any help?

If the form field is empty you need to stop propagation of the parent form. This should be what you need.

 countryValidation = function() {
    // Lets use a function so we can check the field
    $country = $('#country');
    if ($country.val() === '') {
      return false;
    } else {
      return true;
    }
  }

  $('#user-number-value').on('focus', function(){
    if(countryValidation() === false){
      // If the field check comes back false on focus lets add a class
      $('#country').addClass('invalid');
    };
  });

  $('#country').on('change', function(){
    // This will remove the class when the user fixes the error
    if(countryValidation() === true) {
      $('#country').removeClass('invalid');
    } else {
      $('#country').addClass('invalid');
    }
  });

  $('form').on('submit', function(e) {
    if(countryValidation() === false){
      // when the field comes back invalid lets add the class
      $('#country').addClass('invalid');
      // this will prevent the form from submitting
      e.preventDefault();
    };
  });


Delete node: Remove header, footer and rightbar in delete node page I want to remove the header, footer and rightbar in a delete node page (node/.../delete). How can this be reached?

I already tried editing page--node--delete.tpl.php, but this does not work.

Please follow suggestion from this link for page https://www.drupal.org/docs/7/theming/template-theme-hook-suggestions

If you have created a page using views then you can call template for views like (page--viewname.tpl.php).

if you go with the content node, You need to call template like (page--node--nodeid.tpl.php)


how to submit a text field input from a user in a views filter form to a javascript ? I am trying to fetch the user entered text value precisely a zip code which will be taken as input in the views exposed filter form and this value should be sent to the Java script function and I have this java script function which calculates the required LAT LON based on the zipcode and gives back the result.
The problem is I can use the drupal_add_js function to add the js file and also pass the value of zip code (I think so I am not sure though) I am wondering if I can send the zipcode value entered by the user only on form submit to the js file i.e can I send the value of zipcode to the js file only when the user submits the views exposed filter form by pressing the apply button?

I know that we can add a js file and send the values using drupal_add_js function but just not sure if this can be synced with the form submission button ?
 how can this be done?  please help me in this, any pointers in this regard are appreciated.

got it I never used Jquery before and jquery is magic it when used with drupal behaviours as magic just listens to click or any event you want it to listen to and passes the value and you can retrieve it using $(# id of the field).val()[.val() is a function to retrieve the value].


Where can I view different form modes? I created a simple content type and a form mode for this content type. Where can I view this form mode after creating it? I see no option for form modes when creating a content type.
I would have expected an option to be presented when clicking on "Add Content" to select "Add xy content with xy form mode"? Raised it as an issue here https://www.drupal.org/node/2530086

You can try these modules.

https://www.drupal.org/project/form_mode_control https://www.drupal.org/project/form_mode_manager

I prefer form_mode_control. Form_mode_manager create a view form mode for all content types.

These modules can be restricted with permissions. But I prefer https://www.drupal.org/project/field_permissions; it is more acurated by field.


How do I hook the stock status message to the product page? I have a Commerce Demo site that uses the off canvas flyout cart and I am using the Commerce Simple Stock module to stop items being sold if they are out of stock.
The module changes the stock number and prevents the item being loaded to the cart if already purchased. It sends user/status messages and removes the add to cart button using commerce_simple_stock_form_commerce_order_item_add_to_cart_form_alter().
This hook doesn't work for the Commerce Demo form.
The theme hook for the Add to cart button in Commerce Demo is commerce_cart_flyout_add_to_cart_button().
The stock status messages show on the admin pages but not on the product page itself.
How do I hook the stock status message from the module to the product page?

System Messages are printed to the page via a block (Block: Messages, Category: System).

If the messages block isn't aren't appearing on a particular page:

Check to make sure the block is added to a region in the active theme for the page in question.
Check to make sure any visibility settings for the block are configured correctly for the target audience
Make sure that your theme actually renders the region that you added the block to.

If you're still not seeing the messages block:

Create a static custom block (something that should always appear) and place it in the region.
Test with the block added to a region you know is rendering, i.e. the main content region.
Inspect the source html of the page to make sure the html is actually missing and isn't just being hidden by css.
Enable twig_debug and verify that the page is built with the templates you think it is. Check each template (Page, Region, Block, potentially others, but it would likely be one of these that's the issue) and make sure the template is properly rendering what it needs to.


How to change Omega subtheme's layout for a view I sense this can be done with Context etc, but it doesn't feel right to issue a few more modules for the job of a few lines of code.

Something like the following has to fit this:

function mytheme_omega_layout_alter(&$layout) {
  if (arg(0) == 'node' && is_numeric(arg(1))
      && $node = node_load(arg(1)) && $node->type == 'article') {
    $layout = 'article';
  }
  else if ($view = views_get_current_view() && $view
      && $view->name == 'term_content' && $view->current_display == 'term_page') {
    $layout = 'term_page';
    print '<pre>';
    print_r($view);
    print '</pre>';
  }
}

The problem here is, views_get_current_view() looks like it doesn't play well in this hook. I couldn't find any documentation.

I'll send best of my karma-pack to any contribution:) Cheers!

Wow wow, little bit syntax failure with the wrong function caused a disturbance in the force.

Here is how:

function mytheme_omega_layout_alter(&$layout) {
  if (arg(0) == 'node' && is_numeric(arg(1))
      && $node = node_load(arg(1)) && $node->type == 'article') {
    $layout = 'article';
  }
  else if (($view = views_get_page_view())
        && $view->name == 'term_content' && $view->current_display == 'term_page') {
    $layout = 'term_page';
  }
}

PS: This is going to the community wiki as the internets don't have an answer about it!


How do you properly use "Fetch entity by id" in Rules in order to access its fields? I am trying to set up a RUle that loads and node (Fetch entity by id) and then, on another action, I want to access fields of the fetched entity. However, while I see the loaded node on the data selector of the next actions, I cannot seem to access its fields, only its "normal properties".

Any ideas?

I got to this question whilst searching for a different solution to my own problem, but I think I know what's wrong anyway, even if it's 2 years old, it might help someone in the future :P

I think you have to add a condition to determine the type of Entity you are looking at, either by using 'Entity has field' or 'Data comparison' to determine what content type you are looking at. The reason you only see the 'normal properties' by which I assume you mean NID, Author, Title etc, is because it cannot guarantee it has the fields you want, until you determine what content type it is


Default images also as user selected image functionality I have a content type with a taxonomy and based on that taxonomy, I want to have a default image to show unless the user wants to upload a different image. I'm not sure how to go about this functionality. Is there a module that should one could recommend or any suggestions?

I have used this to display taxonomy images https://www.drupal.org/node/1224916 and it works great but it doesn't give the user the option to upload their own pic.

Representative_image

  Allows you to define representative image or media fields for entities
  like nodes, taxonomy terms and the like. These can then be used in
  Open Graph meta tags (via tokens); or as fields in views. The media
  module is also supported. A default image can be defined for those
  entities without images.


Token filter does not show image field with FlexSlider formatter I want to display a gallery with the FlexSlider formatter in a Body field.

I installed the Token and Token filter modules and enabled "token filter" in text formats (admin/config/content/formats).

On my content type (admin/structure/types/manage/[content_type]/display) I enabled the "Token" display mode in "Extended display parameters".

For the Token display mode (admin/structure/types/manage/[content_type]/display/token) I set the FlexSlider formatter for my image field (field_gallery).

I added a node with the [node:field_gallery] token in the Body field but the token is being replaced with nothing.

How can I make an image field using the flex slider field formatter work with the token filter module?

My solution.

Install custom_formatters module.

Create a view with FlexSlider formatter:

    $view = new view();
    $view->name = 'field_slider';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'node';
    $view->human_name = 'Slider';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['use_more_text'] = 'more';
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['exposed_form']['options']['submit_button'] = 'Apply';
    $handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Reset';
    $handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Sort by';
    $handler->display->display_options['exposed_form']['options']['sort_asc_label'] = 'Asc';
    $handler->display->display_options['exposed_form']['options']['sort_desc_label'] = 'Desc';
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['expose']['items_per_page_label'] = 'Elements';
    $handler->display->display_options['pager']['options']['expose']['items_per_page_options_all_label'] = '- All -';
    $handler->display->display_options['pager']['options']['expose']['offset_label'] = 'Skip';
    $handler->display->display_options['pager']['options']['tags']['first'] = '« first';
    $handler->display->display_options['pager']['options']['tags']['previous'] = '‹ prev';
    $handler->display->display_options['pager']['options']['tags']['next'] = 'next›';
    $handler->display->display_options['pager']['options']['tags']['last'] = 'last»';
    $handler->display->display_options['style_plugin'] = 'flexslider';
    $handler->display->display_options['style_options']['optionset'] = 'gallery_in_text';
    $handler->display->display_options['row_plugin'] = 'fields';
    /*  */
    $handler->display->display_options['fields']['field_gal']['id'] = 'field_gal';
    $handler->display->display_options['fields']['field_gal']['table'] = 'field_data_field_gal';
    $handler->display->display_options['fields']['field_gal']['field'] = 'field_gal';
    $handler->display->display_options['fields']['field_gal']['label'] = '';
    $handler->display->display_options['fields']['field_gal']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['field_gal']['click_sort_column'] = 'fid';
    $handler->display->display_options['fields']['field_gal']['settings'] = array(
      'image_style' => '',
      'image_link' => '',
    );
    $handler->display->display_options['fields']['field_gal']['group_rows'] = FALSE;
    $handler->display->display_options['fields']['field_gal']['delta_offset'] = '0';
    /*  */
    $handler->display->display_options['sorts']['created']['id'] = 'created';
    $handler->display->display_options['sorts']['created']['table'] = 'node';
    $handler->display->display_options['sorts']['created']['field'] = 'created';
    $handler->display->display_options['sorts']['created']['order'] = 'DESC';
    /*  */
    $handler->display->display_options['arguments']['nid']['id'] = 'nid';
    $handler->display->display_options['arguments']['nid']['table'] = 'node';
    $handler->display->display_options['arguments']['nid']['field'] = 'nid';
    $handler->display->display_options['arguments']['nid']['default_action'] = 'not found';
    $handler->display->display_options['arguments']['nid']['exception']['title'] = 'All';
    $handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
    $handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
    /*  */
    $handler->display->display_options['filters']['status']['id'] = 'status';
    $handler->display->display_options['filters']['status']['table'] = 'node';
    $handler->display->display_options['filters']['status']['field'] = 'status';
    $handler->display->display_options['filters']['status']['value'] = 1;
    $handler->display->display_options['filters']['status']['group'] = 1;
    $handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
    /*  */
    $handler->display->display_options['filters']['type']['id'] = 'type';
    $handler->display->display_options['filters']['type']['table'] = 'node';
    $handler->display->display_options['filters']['type']['field'] = 'type';
    $handler->display->display_options['filters']['type']['value'] = array(
      'page' => 'page',
    );

Go to the custom formatters settings, create new formatter for Image field:
Format: PHP
Field types: Image
Formetter (php):

  print views_embed_view('field_slider','default', $variables['#object']->nid);

Or import this:

    $formatter = new stdClass();
    $formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
    $formatter->api_version = 2;
    $formatter->name = 'gallery_views';
    $formatter->label = 'Gallery views';
    $formatter->description = '';
    $formatter->mode = 'php';
    $formatter->field_types = 'image';
    $formatter->code = 'print views_embed_view(\'field_slider\',\'default\', $variables[\'#object\']->nid);';
    $formatter->fapi = '';

Then go to the Token tab (admin/structure/types/manage/[your_content_type]/display/token), set the Gallery views formatter. Now it works.


How to list articles in user node On the user node page, how to automatically show the articles posted by the user?

In short, the Views module can be used to do that. This question and answer from the main StackOverflow site covers the same issue, including a link to a tutorial with more details.

Start by installing the Views module. Create a new view to list content. Under the Advanced section for the view, add UID as a contextual filter. From there, you can either create a block display or a page display, to output the view. If you add a page display, you could have it appear as a tab on the user's page, by setting it as a "Menu tab."


How do i use views with a custom entity? I defined a custom entity with a few bundles.  Is it possible to display these using Views?  How do I do that?

If you used entity API module, then this is done pretty much out of the box, see my blogpost on Integrating entities with Views for more details.

If you didn't use entity API module or don't want to, you can make the views integration yourself using hook_views_data.


What is the suggested workflow for migrating (CMI) configuration from dev -> stage -> production? We had a drupalcamp a few months back and someone asked about managing deployments with the new config (CMI) system. One possible ideal workflow would involve keeping the config in version control and still being able to migrate configuration between team members.

The best that we in the room were able to figure out (partially based on the presentation at DrupalCon Portland) was:

Tell version control to ignore active config directory.
Copy all Configuration over to staging directory and commit to version control.

And use settings.php to reverse active/staging directory between the 2 environments. However, while figuring out a deployment workflow from one server to the next was complex but doable, what is the suggested workflow from multiple local environments (ie multiple developers) into dev (or between each other) - A possible issue would be every team member would be sharing the same or similar environment so how do changes on one teammate's machine come over?

After talking a bit with CMI maintainers, the discussion on what's the best approach isn't finished but the following is what makes the most sense at the moment.

Trying to keep it terse for now, will try to expand based on questions/when the referenced issue is resolved with an official answer.

So, first, the facts...

As already mentioned, there's the active and staging directory. Active is fully managed by Drupal, making changes directly in there (direct or indirect by switching to a different location) is not supported.
Staging is where Drupal looks for configuration to import and doe otherwise not care about it.
The import process is important, configuration changes can affect a site in a certain way and needs to be checked for validity. You can't change the field type of a text field to an entity reference, for example, that just doesn't work.
The config import always needs to run on all configuration, you can't import a single view or node type. It was tried, but trying to cope with dependencies, removes/renames and so on resulted in an very complicated system and it didn't work.
The only way to re-install default configuration, is to re-install that module. Which means that it would first try to remove all configuration (like fields). So that's not really an option. Manual, specific changes in update functions are possible but too tedious for this I think.
As the features module describes, it will be focused on providing re-usable functionality, not continuous deployments of configuration. This is what it was designed for in the first place.

Given that, the recommendation right now is to put the staging directory into version control. Each developer has then full control over what he puts there, either by copying the whole active directory over, or just a specific configuration file. The staging directory changes are then committed, pushed to production and the configuration import is run (in the UI or with drush).


Display a message during form submission and prevent multiple submissions During a form submit I would like to display a message that the server is busy processing the submission. In some cases a user has to wait for several seconds. This message should disappear automatically and submitting the form again should be prevented.

This can be achieved by creating an AJAX form. If you fear that the max execution time of the server will be a problem you should look into batch operations as mentioned by Kevin.

An easier alternative is to add a custom JavaScript file and react on the form submission.

Alter the forms you want to behave as requested in a custom module. Use the #attached property to add your custom JavaScript file (in your custom module directory).

$form['#attached']['js'][] = drupal_get_path('module', 'MODULE_NAME') . '/MODULE_NAME.js';

Then add something like the following to your JavaScript file:

(function ($) {
  Drupal.behaviors.formSubmitFeedback = {
    attach: function (context) {
      // Get the forms we want to modify by form ID.
      var $forms = $('#form_id_x, #form_id_y'),
        submitCount = 0;

      // Make sure the form is only submitted once.
      $forms.once('submit-feedback').submit(function(e) {
        if (submitCount) {
          e.preventDefault();
        }
        else {
          var $submits = $forms.find('input[type=submit]');
          // Hide all submit buttons so that they can't be clicked twice.
          $submits.hide();
          // Add a class to the form so we can do some specific styling.
          $forms.addClass('submit-wait');
          // Add a wait message with throbber after the submit buttons.
          $submits.after('
' + Drupal.t('YOUR MESSAGE') + '
');
          // Make all input fields (except the submit buttons) readonly.
          $forms.find('input').not($submits).blur().prop('readonly', true);
        }
        submitCount++
      });
    }
  };

})(jQuery);

This piece of code hides the submit button and cancels later submits.
A message is added to the DOM with a Drupal throbber (depending on your theme). You may need some CSS to make it look nice. There will be a 'submit-wait' class on the form after submission.


How to sort by a fields content? so I have a content-type called "Team Member" and I'd like to sort for the field "last_name".

I currently get all the nodes using:

nids = db_select('node', 'n')
->fields('n', array('nid', 'field_last_name'))
->condition('type', 'team_member')
->orderBy('n.title','ASC')
->execute()
->fetchCol();

So currently, they are sorted using the title. How can I now tell it to sort using "last_name" field? I just don't see what exactly db_select needs to know here.

Im on D7.

You shouldn't query the database directly for entity data, there are APIs for that.

In this case you need an EntityFieldQuery:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'team_member')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_last_name', 'value');

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}


Why doesn't "Allow multiple values" in Views' Contextual Filter work? I'll try to explain this as simply as possible...

I'm using the Views Datasource plugin to create a JSON view to output a restaurant list.

We need to be able to filter the list via several fields - We'll just use "Cuisine" as an example.

I setup a contextual filter and when I browse to the view with "/sushi" at the end of the URL, I get only the results with Sushi in the Cuisine field. This is working correctly.

However, the Cuisine field can hold several types, such as "asian," or "carryout," or whatever.

Now, when I select "Allow multiple values," I SHOULD be able to browse to the view with "/sushi+asian" and get anything with either Sushi or Asian in the cuisine.

Instead, I get NO results.

I'm running out of hair to pull out - Anyone got any ideas? I'm at a total loss.

-- UPDATE --

Here's some SQL Query stuff - I've stripped everything but the WHERE clause as this is the only place where anything changes.

### WITHOUT MULTIPLE VALUES CHECKED ###

// Ran "/restaurants/all/$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

// Ran "restaurants/all/$+$$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$+$$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

### WITH MULTIPLE VALUES CHECKED ###

// Ran "restaurants/all/$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

// Ran "restaurants/all/$+$$/all"
WHERE (( (field_data_field_price_0.field_price_0_value = '$+$$' ) )AND(( (node.status = '1') AND (node.type IN  ('franchise')) )))

Obviously the query isn't changing regardless of whether I tell it to allow multiple values - How do I get this to take values separated by a + and make them ('$', '$$')?

Try using commas instead of plus signs, i.e. sushi,asian,italian since some apache configs do not support plus signs. Slashes should only be used between different contextual filters like cuisine and street, etc.

Also, make sure to check that the operator between filters is set to and not or. hth.


how to show message in popup when user register to site? I just want to show message in popup when user register to site."Further instructions have been sent to your e-mail address". This message i want to show in pop-up.

Use this module to show popup on the specific page.Use the latest dev version https://drupal.org/project/popup_message


How to add class to a language field? In drupal 7 there is a field which displays the node`s language.

I have a multi-site installation and plenty of content types on each of sites. I don`t want to click for hours hiding this field. By default it is generated  with "form-item form-type-item" classes.

How could i add a class to this field to be able to hide it in css?

Thanks

The easiest way to do that in my situation was just adding to node.tpl:

hide($content['language']);


Manage Display formatting settings won't work I've got a problem with formatting decimal fields in Drupal using the Manage Display settings. I've already specified a thousands separator for this particular decimal field:

And clicked Update and Save: (see that it displays a sample value already formatted)

However, when I go to the actual field, it doesn't have any formatting:

Already tried formatting this field using a combination of a jQuery plugin and #attributes in this field's array, but Drupal won't save the value since it only accepts the dot and numbers as valid decimal value.

Is there anything I'm missing here? I should also say that I'm using a custom theme. I'm also willing to give info about my code as long as it doesn't touch sensitive business logic.

Manage Display is for the front end, not the back end (i.e. not the entity edit form).

When the field value renders on the front end, you'll see the formatting you've chosen.

There's probably not much point trying to force formatting for a number in the backend, it makes more sense to take the raw number and then only manipulate it upon output. But if you absolutely need the functionality, it'll likely be a custom JS job as Drupal doesn't have anything built in to handle it.


Simplest way to let writers edit Views headers/titles without Views UI access? What's the simplest* way to enable non-technical writers, editors etc to edit the text in Views headers, titles, footers etc, without needing to enable Views UI on a production site, train these non-technical staff to use some of it, and grant them Views UI permissions?

It's common for content staff - writers etc - to have nothing to do with site building tools like Views UI. It's not their remit or expertise. Also, they'll usually be editting content on the production site, while site builder UI tools like Views UI are often disabled on production sites to reduce unnecessary memory consumption (less PHP files to parse for hooks).

But, the text content of the title fields, view headers, etc is within their remit and expertise. What's the simplest way to bring these text snippets - but not the whole Views UI - within their reach?

*Here, 'simplest' means minimal extra modules, minimal complexity in workflow, minimal overheads) Options using Panels are fine in my case. Ideally, I'd prefer to avoid needing to use Display Suite.

The workaround I'm using at the moment, which just about works (but I'm sure there's a simpler way) is this:

I have a custom taxonomy vocabulary, 'Text Snippets'
Each Text Snippet has a name describing to editors where in the interface it is used
Each Text Snippet description contains the HTML to be used
The views' headers are set to 'Render entity' with the ID of the appropriate Text Snippet term written in
To stop the internal-use-only term name being displayed, I have a custom template in my theme templates folder, taxonomy-term--text_snippets.tpl.php, containing nothing but <?php print preg_replace("/<p[^>]*>[\s|&nbsp;]*<\/p>/", '', $description ); ?> (the preg_replace regex removes empty paragraphs)

I'm aware of a module, Snippets, which seems to have a similar idea, but it's not at all clear what the intended usage is, there's very little information - blank readme file, documentation is only placeholders - and the very low usage stats and queue history don't fill me with confidence.

You can use the  Views UI: Edit Basic Settings module:

  "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.


Printer: Is it possible to show print PDF and ePub url link for each node on Views? I have Printer module installed on Drupal 7. Let's say I have a view that lists all the articles in table format. I would like to have the PDF and ePub url link next to each article as a field. Is it possible?

Yes, add a global text field and under Rewrite Results select output this field as link and give the path eg. for PDF it should be printpdf/[nid].

similarly you can create one more  field for EPUB using printepub/[nid].

Note [nid] is a replacement pattern, you should add nid before these fields and exclude it from display.


Menu tree from taxonomy terms and nodes which belong to them i need to create a collapsible menu tree from taxonomy terms and nodes which belong to them (not nested terms, but content pages) i'm totally stuck about it  i've found solutions for nested taxonomy terms only, but not for combined with content pages from the term. meaning menu tree like this:

That's probably an opinion-based thing and actually also a too broad question. But here's what I'd do:

Programmatically create a new block.
Provide a hook_theme and your own template to later render the output the way you want.
Follow one answer from How to get all node entities tagged with a specific term? to get the data you need.
In the block's build() function pass the data to your custom template and build the markup you need.
Optional: Improve performance by either storing the data from step 3. in some Drupal variable that can be purged from some admin settings form button click. Or add some custom cache tags that get invalidated as soon as taxonomy or node CRUD operations take place.

You probably can achieve what you want with some Views voodoo, and maybe should try that first, depending on your programming skills.


Get all the nodes in the system I've found node_load_multiple() which allows me to get all the nodes, but I need to specify some parameters, e.g. the type of node that I'd like to fetch.

I'd like to get all the nodes in the system without the criteria. How can I do that?

The easiest way would be to use entity_load()

$nodes = entity_load('node');

If you don't provide the second argument ($ids) it will load up all entities of the given type:

  $ids: An array of entity IDs, or FALSE to load all entities.

Just for the sake of completeness node_load_multiple() doesn't require the $conditions parameter so you could also grab all of the node ids from the database

$nids = db_query('SELECT nid FROM {node}')->fetchCol();

And then use $nids to load the nodes:

$nodes = node_load_multiple($nids);


Alter the "From" address contact form I'm trying to alter the email and change the default "From" address to a different email address.

function mymodule_mail_alter(&$message){
   $message['from'] = 'myemail@gmail.com';
}

When I test send a test email through my site Contact Form.  The email "From" address is still using the default site email not the one I altered in my module.

Is there another way to make this work?
Thanks for your help.

I ran into this issue myself. I got it to work in the following way:

function mymodule_mail_alter(&$message){

  $message['from'] = "do-no-reply@example.com";
  $message['headers']['From'] = 'Name TO SHOW <do-no-reply@example.com>';
  $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['from'];
}

However, like you,  I thought adding $message['from'] = 'myemail@gmail.com'; is the way to go and I think it should -Perhaps other folks can chime in and let us know if this is a bug?

In any case, it seems drupal does more processing and checks to verify the from email address and if it does not pass all the checks it sets it to the sitemail, or the mail library just use the other headers. Note I think this behavior may differ based on which mail library you are using. In my case, and I presume in yours, its PhpMail.php.

The solution above worked but I am not sure if it's the most appropriate or if it would work for others who are using different mail managers..