How to pass current selection to entity browser select view I am using an Entity Browser (2.x-dev in Drupal 8) as form widget for a custom entity's entity reference base field. The entity browser is configured

as a modal display,
with single widget,
and no selection display,
using a view with entity browser bulk select field as widget, and
to append chosen entities to the current selection of the reference field.

Selecting the entities is working fine. But the entity reference field shall not have any duplicates.

In order to ease selecting of entities without duplicates, I'd like to filter already chosen entities from the entity browser view results. So users will see unselected entities only.

For this purpose, I created a custom views argument_default plugin that exposes the entity browser selection storage as context default argument for the entity ID:

<?php

namespace Drupal\my_module\Plugin\views\argument_default;

use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface;
use Drupal\views\Plugin\views\argument_default\ArgumentDefaultPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * The entity browser selection argument default handler.
 *
 * @ViewsArgumentDefault(
 *   id = "entity_browser_selection",
 *   title = @Translation("Entity Browser Selection")
 * )
 */
class EntityBrowserSelection extends ArgumentDefaultPluginBase {

  /**
   * The selection storage.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   */
  protected $selectionStorage;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, KeyValueStoreExpirableInterface $selection_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->selectionStorage = $selection_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_browser.selection_storage')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function access() {
    return $this->view->getDisplay()->pluginId === 'entity_browser';
  }

  /**
   * {@inheritdoc}
   */
  public function getArgument() {
    $argument = NULL;
    $current_request = $this->view->getRequest();

    // Check if the widget context is available.
    if ($current_request->query->has('uuid')) {
      $uuid = $current_request->query->get('uuid');
      if ($storage = $this->selectionStorage->get($uuid)) {
        if (!empty($storage['selected_entities'])) {
          $argument = $storage['selected_entities'];
        }
      }
    }
    return $argument;
  }

}

The issue I face, is that the current selection within the selection storage is always empty, no matter how many entities have been selected at the entity reference field, and even after I complete the modal selection and open the entity browser again.

What do I have to do to have the current selection exposed in the entity browser's selection storage?

The Entity Browser doesn't current pass current default value items field in persistent data, but it's easy to add it.

1) Add persistent data using field_widget_form_alter()

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface &$form_state, $context) {
  if (!empty($element['entity_browser'])) {
    $default_value =  $element['entity_browser']['#default_value'];
    $ids = [];
    foreach ($default_value as $entity) {
      $ids[] = $entity->id();
    }
    $element['entity_browser']['#widget_context']['current_ids'] = implode('+', $ids);
  }
}

2) Update your selection so that if blank it shows all:

  /**
   * {@inheritdoc}
   */
  public function getArgument() {
    $argument = NULL;
    $current_request = $this->view->getRequest();

    // Check if the widget context is available.
    if ($current_request->query->has('uuid')) {
      $uuid = $current_request->query->get('uuid');
      if ($storage = $this->selectionStorage->get($uuid)) {
        if (!empty($storage['widget_context']['current_ids'])) {
          $argument = $storage['widget_context']['current_ids'];
        }
        else {
          $argument = 'all';
        }
      }
    }
    return $argument;
  }

3) Make sure you have "exclude" and "allow multiple" checked on your selection.

By the way, if you update to the latest dev release of entity_browser, you don't need your custom plugin.  There is a new entity_browser_widget_context default value views plugin that is configurable.

I also added an issue to the entity_browser queue to add this information when in the widget_context.


term field permission for authenticated user I have installed the tern_fields module.

I have added a term field to the taxonomy vocabulary. The specification of that field is.

type: File
widget: image

Now when I try to upload an image for a taxonomy term, it works fine for the admin but when I try to upload an image for a taxonomy term as a site manager then it gives me the following error.

The selected file test.jpeg could not be uploaded. Only files with the following extensions are allowed: png|gif|jpg|jpeg.

Where the site manager is a user role.
and in the permissions for the site manager against the term_fields module, both check boxes are checked. administer term_fields and upload term files.

what is the problem now?

I have found the answer of my own.

I edit the field there in the file extension I had entered like this "png, gif, jpg".

I changed it to "png gif jpg". insert the space instead of the comma and it solved my problem.


How to navigate the URL after booking page I have node content type for booking and created booking page in drupal 7 and same page is displaying error, confirmation and booking page. I am trying to split into three different pages(nodes) using same node--booking.tpl.php content type. I have custom booking.class.php that manages the booking process using two steps function prebooking and postbooking

After booking, I would like to redirect to xyz.com/booking-confirm if it's successfully booking and if it's error xyz.com/booking-error and currently, using xyz.com/booking for all actions.

What should I do? I am not sure, which option works. I have found this using some articles and stuck at this point.

Should I use header to redirect it?

header('Location: /booking-confirm');
header('Location: /booking-error');

Should I hook them in template.php?

function MYMODULE_user_register_form($form, &$form_state) {
    $form_state['redirect'] = 'path/to/somewhere';
}
Should I use drupal_goto to redirect it? it's in booking.class.php class?
Should I use hook_init? It's in template.php or booking.class.php ?

I am not sure, which is correct option to figure it out. I would like to split the URL using same content type. Any approach to solve the issue.

You should use form state to do redirects since users are interacting with forms. header is not really want you want and neither is drupal_goto.

The class(es) should return either a success/fail style response to the caller (in form submit) and based on that, you should handle the response and redirect with form_state redirect. The only job of your booking class should be to create a booking, it does not need to handle redirects or worry about any of that logic.

Also, no, absolutely don't do redirects from hook_init.

Vanilla example:

function myform_submit($form, &$form_state) {
  $book = new MyBookingClass();
  $form_data = $form_state['values'];

  // createBooking() returns either TRUE or FALSE

  if ($book->createBooking($form_state['values'])) {
    $form_state['redirect'] = '/booking-confirm';
  } else {
    // There was some sort of error.
    $form_state['redirect'] = '/booking-error';
  }
}


Drupal views get fields after filters without html markup I have a question about Drupal 7 and Views. Let's assume that I have views where I extract 2 articles ordered by post date. I want to extract only title and trimmed introduction (trim configured in field settings in view)

Now I would like to extract this data programmatically without HTML markup. So the result will be similar to this:

array(
    0 => array(
        'title' => 'Lorem ipsum',
        'introduction' => 'Lorem ipsum dolar solor...'
    ),
    1 => array(
        'title' => 'Lorem ipsum2',
        'introduction' => 'Lorem ipsum2 dolar solor...'
    )
)

Is it possible to extract such information from views?
I tried to do something like this:

$view = views_get_view('view_name');
$view->set_display('display_id');
$view->execute();
$data = $view->result;

But $data contain two elements with full nodes (all additional fields that I don't want to grab from database)

In addition for instance introduction is grabbed fully (must be trimmed somewhere in PHP).

Is it possible to do something like this:

$view->applyFilters(); //Like trim etc
$data = $view->getResults(); //return title + trimmed introduction but without HTML markup

Do You have any tips how to solve this problem? Is it possible for instance to pass template that will be rendered (where I could display only raw result without any HTML tags) or something?

Any help would be appreciated:)

After suggestion from AlfredArmstrong I checked plugin style docs.
To get filtered data without rendering html template simply do:

 $data = $view->style_plugin->render_fields($view->result);

Under $data will be array of filtered fields from view.


How to hide options in the second select before choosing option in first select i have taxonomy : Cities and taxonomy Towns.

cities have : Sousse and Tunis
Town have Elzahra (related to Tunis (taxonomy cities) and Sahlool (realted to Sousse (taxonomy cities)).

i have installed the module "reference_option_limit" and i created in the content a field named city and an other field named Town , in Town field i have coched :

and i created a view for this content :

but the problem in the page it shows me all the options: for the second select:

If I am not mistaken, you want to show in the second filter only the towns (villages) related to the selected city (ville) in the first filter. That means, the content of the second filter depends on the selection in the first filter. Am I right?

In that case, you might try something like the Views Dependent Filters module. See below its description:

  Suppose you had a view showing several kinds of products, such as
  cake, bicycles, and books, and an exposed filter on product type that
  lets the user refine the listing to one or more types.

  With this module you could add the following filters:

cake flavour, such as lemon, chocolate, coffee
bicycle size
book genre

  Each filter will only show when the type it relates to is selected in
  the filter for product type.


Running into deadlock when using XDebug with Drush For most of the Drush commands it is not too difficult to get XDebug and Drush working togethr and catch staff in your IDE, e.g. PhpStorm.

However, I ran into a deadlock when Drush is calling itself for a sub-process. This happens e.g. if you execute drush @site updatedb because this will invoke a second PHP task for the cache-clear all command. This second PHP task wants to connect to the Xdebug port as well which is still in use by the parent PHP task. This results in a deadlock: the child is waiting for the XDebug port to become available and the parent task is waiting for the child task - for ever or until Ctrl-C.

Is there a way around this?

In PhpStorm at least, under File >> Settings >> PHP >> Debug you can find Max. simultaneous connections and crank it up. I typically keep it at 8 but probably 3 is enough.


menu_tree_page_data() is not loading sub-menu items I have created a menu that has a handful of top level items and some sub-menu items.  it is similar in structure to my "main menu". It is my understanding that each top level menu item is an array, which also contains an array of menu items that are "below" that menu item.

When I print out the array of the menu it will not show the sub-menu items. Am I doing something wrong?

$mm = menu_tree_page_data('menu-second-menu');
print_r($mm);

My ultimate goal is creating X amount of individual menus, and display them in various places throughout the theme.

When I print the array values for the "Main Menu", which is assigned to a block and working, I do see the sub-menu items right where I'd expect them to be.

If you want the whole array of the menu use this function,

menu_tree_all_data('MENU_NAME');

If you find any difficulty, please let me know!


Show block on term page if term has no children Is there a way (probably with PHP block viability settings) to only show a view on term pages and only if the term has no child terms?

I've answered it over here, Check if taxonomy_get_children($tid) is empty, Then term has no children.


How do I display a search result message that includes filter criteria? I have a view to display nodes, with many filters and sorting conditions; that it gets confusing. I want to display the effective filters somewhere, for example refined by X or sorted by Y. is there any way to print the active filters?

for instance consider I have mobile shop, with a view to list phones.there are lots of fields that user can refine using exposed filters. I want at top of page print a message like:

showing phones with X Gb ram and Y screen size and Price Z.

I'm not sure I understand your question. You may have a look at :

Exposed Filter Data

  This module provides a themed function called get_exposed_filter_output() which print out the values of the exposed filter used in a view.

related topic in D.O : Use data from exposed filter in title or header. It will give you many ideas on how to print out the chosen exposed filters values programatically.


Modal form with CTools opened in several different pages I have a working module which opens a modal form with CTools. However, I must use the URL example.com/mymodule/page . There the module creates the link which opens the modal window with the form. How can I use the link in other pages? I have tried to just put the link and it does not work, it redirects to the page of the link (example.com/mymodule/nojs/) instead of opening the modal window.

I have finally solved the problem and now everything works: the modal window, the form and the submit, sending the email in final step. The problem was that the raw URL included the class ctools-use-modal-processed and apparently that simple css was making it not work. Now more or less understand the process, thank you for your help, it has been very valuable.


How do I use Path Matcher for front page? I have used the following code in a Drupal 8 theme file.

$current_path = \Drupal::request()->getRequestUri();
$path_alias = Unicode::strtolower(\Drupal::service('path.alias_manager')->getAliasByPath($current_path));
$visiblity = \Drupal::service('path.matcher')->matchPath($path_alias, $pages);

$pages contains values like '<front>' or '/blog'.

$visiblity is set to FALSE for /, but to TRUE for /node; Both are the front page.

What is the wrong with my code?

Your code is assuming that the request URI for / will retrieve /node on the getAliasByPath() method call. It won't. Setting the Drupal front page isn't the same as setting a path alias in the Path module.

Use the following code, which will return Drupal's internal /node path even on / requests.

$current_path = \Drupal::service('path.current')->getPath();


Drush Site-Aliases won't work I've been trying to set up some Drush aliases. However, when I try to run any command, it will echo the contents of all aliases files, and drush sa simply returns the contents of those files twice, and then the @none, @self and @default aliases (since I'm in the folder of a Drupal installation). When trying to run any command with an alias, e.g. drush @local status, I once again get a dump of those files, and finally a Could not find the alias @local error.

I've tried putting the aliases in ~/.drush/aliases.drushrc.php and in ~/.drush/local.aliases.drushrc.php. In the latter case, I tried two formats:

$aliases['local'] = array(
    'root' => '/home/user/subdomain/public_html',
    'uri' => 'subdomain.domain.com'
);

and

@code
    $options['uri'] = 'subdomain.domain.com';
    $options['root'] = '/home/user/subdomain/public_html';
@endcode

both without any different effect, apart from different contents being dumped. No other errors are thrown, it seems. I've also done a drush cache-clear all after each attempt.

Any thoughts as to what might cause this?

Your error was quite simple; you forgot to put <?php at the top of your alias file.


How to convert taxonomy term name to term id at time of importing and create custom node from csv in drupal? I am creating content type programmatically. I am importing content from csv file.. Everything working fine. But I am not able to select category at the time of import like other fields.. and how to convert term name to term id ,because csv giving me term name.

This function will return the term object if you pass it the term name:
https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_get_term_by_name/7

There is an example at the bottom of that link


Create node and photo gallery during installation of Drupal 6 I want multiples Node installation with Primary and secondary links, and also want to create Photo Gallery While Installing Drupal.

Is it possible to install and create nodes during installation?

The short answer: Yes!

You would need to use an installation profile for this.  With an install profile you can enable and configure modules, create new content types, add content, etc.

Here's one place to start:  http://drupal.org/node/1089736


How to open external links in new window? I'm using the "filtered HTML" text format in the node body with the "convert URLs into links" option enabled.
I would like to have all external links open in a new window. How can I do that?

The External Links module does exactly that:

  External Links is a small module used to differentiate between internal and external links. Using jQuery, it will find all external links on a page and add an external icon indicating it will take you offsite or a mail icon for mailto: links.

  Configuration options:

  Apply icons to either mailto: or external links or both.
  Configure external links to open in a new window.
  A confirmation message when leaving the site.
  Regular expression inclusion and exclusion of links considered external.
  CSS selector inclusion and exclusion of elements for processing


Validating extensions in file uploads I am trying to create a file validator for .csv uploads.  This is my code that works at allowing csv uploads (which are disallowed by default):

$validators['file_validate_extensions'] = array('csv');
$file = file_save_upload('csv', $validators);

However, when I try to upload another file (in this case fizzbuzz.py) I get this error:

For security reasons, your upload has been renamed to fizzbuzz.py.txt.

How can I change this to being and out right error when a non csv file is uploaded?

EDIT: Did some more testing.  This only occurs for my .py file.  Files with a .png extension get rejected and are not uploaded.

EDITx2: Okay, so it also rejects .bat, .gnumeric, and .txt file extensions.  It looks like Drupal does not validate two letter file extensions in the same way it validates three(+) letter file extensions.

If you take a look at the file_save_upload() call, you'll see what's happening with the py files.  It seems to be a It will occur with php|pl|py|cgi|asp|js files.

FROM: file_save_upload() http://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7

// Rename potentially executable files, to help prevent exploits (i.e. will
// rename filename.php.foo and filename.php to filename.php.foo.txt and
// filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
// evaluates to TRUE.
if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js) (\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
$file->filemime = 'text/plain';
$file->uri .= '.txt';
$file->filename .= '.txt';
// The .txt extension may not be in the allowed list of extensions. We have
// to add it here or else the file upload will fail.
if (!empty($extensions)) {
  $validators['file_validate_extensions'][0] .= ' txt';
  drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
}

}

If you wish to allow these uploads (without converting their extensions), you would set all_insecure_uploads to 1 (TRUE), but I doubt you do :)

KMT


Why do uploaded files gets saved with an all-caps file extension? On my product site any uploaded images get saved with the .JPG saved in all-caps. I don't see the same issue on my local development machine so I would think it has to be a server issue? The live site uses NGINX.

Definitely not a server (nginx) issue, as the server does not do anything with the files (well, it transfers them bit by bit). Like Charlie already asked, do you use any modules?

Edit: To answer your second question, of course you can “force” lowercase extensions. But personally I wouldn’t bug your users with that, they should simply upload whatever they have. Instead simply alter the files extension before saving the file to disk/database.

hook_file_presave() seems like the correct way to do this. You would have to create a little module and have a look at the file variable that’s passed to your hook, then simply strtolower() the file extension.


How to programmatically set custom display settings for an RSS feed? I am using Drupal 7 and Views 3.0-RC1.

I have defined an RSS feed for a view, but the full node content keeps showing up instead of the teaser. I believe it is because of these two issues:

http://drupal.org/node/1211008
http://drupal.org/node/1137116

The steps that appear to work are to:

Enable a custom display for RSS,
Configure the RSS custom display truncate the teaser and hide extra fields,
Enable the view to display full text for RSS.

I need to make this work programmatically as part of a features module.

The first step is easy. I do it with the following code in my .module file:

    function mymodule_entity_info_alter(&$entity_info) {
      $entity_info['customtype']['view modes']['rss'] = array (
        'label' => t('RSS Feed'),
        'custom settings' => TRUE,
      );

The last step is easy, as I can export the view.

The middle step has me stumped. I can't figure out how to set the display properties on the RSS display. I suspect it has something to do with field settings, but I can't seem to pull the pieces together. Any suggestions?

@JeremyFrench pointed out that the Features Module correctly exports the field settings for the view-mode, which fulfilled the middle step. No extra API calls is necessary.

My problem was with step 1. Though field settings are defined per-content-type and per-view-mode, the actual definition of view modes is independent of content-types. All content types share the same set of view modes, though each can implement their own field settings for that view mode.

This means that in my call to hook_entity_info_alter(), I should not have referenced customtype, I should just reference 'node'. That simple change enables everything to work.


How to implement some type of private messaging to arbitrary groups of users? I'd like to send private messages (with email notification) to groups of users. These groups can be either pre-defined or ad-hoc selected. Is there any way to implement this feature in a Drupal site?

I found Privatemsg which seemed quite promising since it has Views- and Rules-integration. But after all it has not meet the requirements: I couldn't find a way to populate the recipients field with multiple users (I thought using a view with exposed filters and VBO would be a handy tool for selecting users).

Is there any solution for this?

Using the Forena module, you could start from one of the Sample reports and solutions that come with it. I.e. the Active Users Email, which is a demo of the ability to send email to all active users of a Drupal site.

The idea is that those users who have access to it, actually get a FORM to have Drupal send an eMail to all users selected via the query. To do so, you just have to "submit the report".

The easiest way to see the out-of-the-box example at work, is to (temporary) install the module in some dev environment you have available (for obvious reasons this sample report is NOT available to anonymous users in a Forena demo site ...).

Here is what would be needed to transform (clone) this sample to fit your needs:

Adapt its data block (an SQL query) to list "all persons to be eMailed" (instead of all "active users of a Drupal site").
Adapt the actual content of the delivered eMail template to fit the actual eMail content (message).
Optionally you may want to make the "group" to be selected a report parameter.
Secure "access" so that only authorized users can send such eMails. Depending on how your security is setup, you may want to adapt the Forena permissions accordingly.

The above approach can be used for all sorts of eMails towards any set of users of a Drupal site. Whereas that "set of users" is just a matter of writing some (basic) SQL statement to select the users you want to target. E.g:

Users with a selected role or
Users who didn't login for X days anymore or
Groups of users that are either pre-defined or ad-hoc selected (as in your question), whereas you'd need 'something' to actually indicate that ad-hoc selection that you can retrieve via some SQL query, like:

a taxonomy term.
some flag (using the Flag module).
all members of a group, created using either Group or Organic Groups .
etc.

...

And the actual eMail content (message to be delivered) is actually anything you can format as an XHTML document.

Disclosure: I'm a co-maintainer of the Forena module.


How can I create a Install New Module-style "add button"? In the Modules page, there is a button that looks like this:

Is this easy to reproduce? If so, how is it done?

Figured it out. You create a sub-item in your hook_menu(), then set its type to MENU_LOCAL_ACTION.

  $items['menu/url'] = array(
    // --snip--
    'type' => MENU_LOCAL_ACTION,
    // --snip--
  );


Taxonomy + Drupal Commerce binding I'm trying to set up a testing site with DCommerce used to present product information, yet for the time being, there won't be any shopping cart functionality. I'm stuck at how to bind the products (instances of my custom product type defined in Store) with taxonomy, and also to have the URL aliases created dynamically based on that taxonomy.

Has anyone bumped inot a good case study or tutorial. I seemed to have googled the entire internet but to no avail.

Artur

Usually how you set up product display is via nodes, so 1 node have a relationship to 1 or more products (Fx a specific t-shirt in different sizes). Since products themselves doesn't have a public display, they are rendered through the nodes you create. This means that it is also going to be the nodes that have the url.

Trying to create a node path alias based on 1 or more products is going to be very tricky, because you don't know how many products you have, what if the products has different taxonomy etc. Instead it might make more sense to using the taxonomy on the nodes, or maybe use them on both. A node with a taxonomy term is a pretty normal case which is well supported. This should fix all the problems you have with url aliasing.


Drupal 7: Menu item being accessed even with false access callback? I have a menu item:

$items['login-now'] = array
(
    'title' => 'Log In',
    'page callback' => 'some_or_other_method',
    'access callback' => 'the_permissions_function',
    'menu_name' => 'menu-ecommerce-nav',
    'type' => MENU_NORMAL_ITEM,
    'weight' => '5',
);

And then I have:

function the_permissions_function {
    $isAnonymousUser = user_is_anonymous();
    if (!$isAnonymousUser) {
        return FALSE;
    }
    return TRUE;
}

This works if I am logged out. I can see the "log in" button. But when I log in, it STILL shows this login button. Why?

What's interesting is, I added this above the "return false"

print 'xxxx'; die();

And it hits this code!! But for some reason, it still shows the menu item? Why is it not hiding the menu item?

UPDATE

Even if I just do this:

'access callback' => 'user_is_anonymous',

It STILL shows the "log in" menu item when I am LOGGED in. Why on earth is it doing this? What am I missing?

user_is_anonymous() returns TRUE if the user is a menu administrator: see function user_is_anonymous

Try user_is_logged_in() instead, e.g.:

function the_permissions_function {
    $isLoggedIn = user_is_logged_in();
    if ($isLoggedIn) {
        return FALSE;
    }
    return TRUE;
}


Create Nodes for multiple languages in webform? I have a default Node for English, which will be translated when user logs in based on the user locale. Beside I need to create a separate node for ja(Japanese) like (mydomain.com/node/7).

I created a node(nid=7) by changing the 'Language neutral' to 'Japanese' language. when I hit the node it not gets translated to Japanese.

Is there any way to get it translated?

I think maybe your problem is because mistake configuration of translation

Enable translation support for a content type

Navigate to the Content types administration page (Administration >
Content > Types in Drupal 6, or Administration > Structure > Content
types in Drupal 7).
Select a content type you want translated, and select "edit", then "Workflow settings" for Drupal 6 or "Publishing options" for
Drupal 7.
At the "Multilingual support" section, select "Enabled, with translation".
   Be sure to save each content type after enabling multilingual support.


Customize a "Feature" I'm trying to create a feature that includes an Automatic Nodetitle.

I want to change two things related to Automatic Nodetitle: Hide Title in content creation and populate the field with tokens.

How would I go about this?

Use the strongarm module. When creating the feature select "Strongarm" from the component section then look for the variables that start with ant_{content type name}

Automatic Nodetitle can have up to 3 different variables for every content type.

ant_'{content type name}
ant_pattern_'{content type name}
ant_php_'{content type name}

Export those variables out with your content type and you should be ok.

This works in Drupal 6 & 7.


Submit values and redirect user from to external URL What is the equivalence of:

   <form action="https://paypaad.bankpasargad.com/PaymentController" method="POST">
            <input type="hidden" name="content" value='<?php echo $xml ?>' />
            <input type="hidden" name="sign" value="<?php echo $sign ?>" />
            <input type="submit" value="send" name="submit" />
   </form>

in Drupal 7 ?

I already use following code in my form submit handler, but it doesn't work:

function Chargingform_nameform_submit($form, &$form_state)
   {
    $options = array();
    $options = array(
        'method' => 'POST',
        'xml' => $form_state['values']['xml'],
        'sign' => $form_state['values']['sign'],
        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
    );

   $url = 'https://paypaad.bankpasargad.com/PaymentController';
   $response = drupal_http_request($url, $options);
}

How I can submit XML, sign to URL and redirect user to that URL at the same time?

This is my code:

function Chargingform_nameform() {
    $xml = 'PHP Handbook30000130000This is good book.MySQL Handbook25000250000This is a good book too.';
    // Get sing
    $sign ='ewtnXYRWPSalHhna9hgO+Kc0W9Z8JBUeG1FkcKPvZL5w2s588c0/B9r';

    $form['xml'] = array(
       '#title' => t('xml'),
       '#type' =>'hidden',
       '#value'=>$xml,
    );
    $form['sign'] = array(
       '#title' => t('sign'),
       '#type' =>'hidden',
       '#value'=>$sign,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
    );
    return $form;
}

function Chargingform_nameform_submit($form, &$form_state) {
  $options = array();
  $options = array(
    'method' => 'POST',
    'xml' => $form_state['values']['xml'],
    'sign' => $form_state['values']['sign'],
  );
  $url = 'https//:url';
  $response = drupal_http_request($url, $options);
}

I don't know really how to manage it in JavaScript.

Any suggestions?

You can generate form like that using '#type' => 'hidden' form API fields, and using '#action' on form itself.

If you want to submit values to Drupal and then redirect user to external site, you cannot do it directly. HTTP protocol does not allow you to send anything from your server to another "on behalf" of your user. The only way to do it is:

Get data from user
Save data, process it, do whatever you need
Generate form with action pointing to external service (usually payment gateway), and data required by it in hidden fields
Use JavaScript to make user's browser submit it.

If you are trying to do it using drupal_http_request, it's your server that starts payment procedure, not client's browser - certainly not what you want. And payment server will not allow switching procedure between different computers - it would be a security risk to allow that. If you could hand your session on payment server to your user, what would prevent attacker from doing the same (but with his bank account, not yours)? I know that's simplified explanation - for more details you may try to ask on Information Security.


Is Drupal internationalization development effort embracing the new "Entity Translation" method? Is it ready for use? I'm working on standing up a new Drupal 7 site that will have content in multiple versions, and as I'm reviewing the i18n module, I see that there are now two methods for translating content: "Content Translation" and "Entity Translation."

However, the articles I've found on this are all several years old. I would have expected that, by now, there would be consensus built around the "blessed" method of doing content translation, but I can't seem to find anything except "we're moving towards entity translation, hopefully it will be done soon," and this is all in posts that are years old--so maybe by now it is done? But I just can't find the posts saying it's ready?

So, is "Entity Translation" ready for prime-time, and it's the current method recommended by Drupal (the team)? I'm looking for an authoritative reference (e.g., post by someone on Drupal or i18n team, or a respected Drupal community member), that gives the current state of affairs for Drupal internationalization.

Thanks!

Let me start by stating that I am not on the i18n team, nor very involved in the development of Drupal. But I have been working with Drupal multilingual sites for over several years, where we switched to entity translation about 2 years ago. I have done the same search as you are doing now and these are my findings.

The article you've found already covers the main things, and entity translation in my opinion is more the Drupal way. The whole translation system already went into the D7 Fields API where a value is accessed like this:

$field[LANGUAGE_NONE][0]['value'];

Most examples will use 'und' (the value of the constant LANGUAGE_NONE) for the undefined index, but it can also contain a language code. Thus fields in D7 are already multilingual.

In my opinion the entity translation module uses this in a more effective way, where one piece of content, one node with one id is being linked to one field, which is used to serve content in several languages. Rather then having several nodes, each being in another language and linked to the others.

For us this solved problems when fetching certain nodes by id in an external system and finding out it had the wrong language etc.

I know entity translation is still in Beta, but over 2 years I never had an issue with it. Also note that at the bottom of the entity translation project page it states that it is in D8 Core now (although under the name of content translation). I've just tested this on a local machine and there is indeed one node for several languages, so it at least looks like entity translation is in place. Those things made me assume this is the Drupal way.

Hope this helps somewhat in making a decision.


How to pass a custom Form to a Twig template my problem is that my drupal 8 form is not getting rendered in twig template.

I created a form with build form method in drupal 8 when i tried it to pass in twig template it is not getting passed.for example my code is

modulenameconfig.php

class modulenameConfigForm extends ConfigFormBase {

  /**

   * {@inheritdoc}

   */

  public function getFormId() {

    return 'modulename';

  }
public function buildForm(array $form, FormStateInterface $form_state) {

    $form = parent::buildForm($form, $form_state);
    $config = $this->config('modulename.settings');

    $form['first_name'] = array(

      '#type' => 'textfield',

      '#title' => $this->t('First Name'),

      '#default_value' => $config->get('modulename.first_name'),

      '#required' => TRUE,

    );

    $form['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
      '#default_value' => $config->get('modulename.last_name'),
      '#required' => TRUE,
    );
    return $form;

  }
 protected function getEditableConfigNames() {

    return [

      'modulename.settings',

    ];

  }
}

modulename.module

<?php

namespace Drupal\modulename\Form;

use Drupal\Core\Form\ConfigFormBase;

use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_menu()
*/

function modulename_theme() {
  return array(
    'modulename_form' => array(
      'render element' => 'form',
      'template' => 'modulename-form',
      'base hook' => 'form'
    ),
  );
}

my twig file in templates folder

modluename-form.html.twig

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
  ]
%}

Personal Information

                                    <form method="post">

                                            First Name

                                              {{form.first_name}}

                                            Last Name

                                                <input type="text" class="form-control" name="lname" id="lastname" placeholder="Last Name" required>

any help will be greatly appriciated  help asap

This structure will not work with the autoloader right now - your namespaces and directory structure needs to follow these PSR-4 standards. (In particular, setting a namespace in your .module will cause Drupal to not find your hooks, which must be in the global namespace.)

I'm not sure I understand your use case fully, but it sounds like you want to:

Create a form.
Create a route that serves this form.
Render the form with a custom template.

For the first, your form class should be something like this (and must be saved in a file matching the class name under modulename/src/Form/{ClassName}.php):

namespace Drupal\modulename\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MyModuleConfigForm extends ConfigFormBase {

  public function getFormId() {
    return 'modulename_settings';
  }

  public function getEditableConfigNames() {
    return ['modulename.settings'];
  }

  public function buildForm(array $form, FormStateInterface $formState) {
    // build the form
    $form['...'] = [
      //...
    ];

    parent::buildForm();
    return $form;
  }

  public function submitForm(array $form, FormStateInterface $formState) {
    $this->config('modulename.settings')
      // set the values from the form
      ->set('...', $formState->getValue('...'))
      ->save();

    parent::submitForm($form, $formState);
  }

}

For the second part, you need a modulename.routing.yml file that looks something like this:

modulename.settings:
  path: '/admin/config/mymodule'
  defaults:
    _form: '\Drupal\modulename\Form\MyModuleConfigForm'
  requirements:
    _permission: 'administer site configuration'

(This is for admin configuration forms, since you mentioned ConfigFormBase. If you want a more general form and open it to anonymous users, extend FormBase instead and put _access: 'TRUE' in the route requirements.)

Finally, for the third part, you need to create your theme hook in modulename_theme(). (Your code already works, although the template key is superfluous as it matches the default.)

Then, modify the buildForm() as follows:

  public function buildForm(array $form, FormStateInterface $formState) {
    // build the form
    $form['...'] = [
      //...
    ];

    parent::buildForm();

    // *After* parent call.
    $form['#theme'] = 'modulename_form';

    return $form;
  }


Error uploading image Since I changed my drupal to my backup that it's giving me some errors, but overall it stills working, but today I was about to add a new content and when I try to upload new images it shows me this error

  "The file could not be uploaded."

And in log messages I've this message errors:

  Location: http://localhost/node/add/imovel?_wrapper_format=drupal_ajax&ajax_form=1&element_parents=field_image%2Fwidget

  Message: The upload directory public://2017-02 for the file field field_image
  could not be created or is not accessible. A newly uploaded file could
  not be saved in this directory as a consequence, and the upload was
  cancelled.

In the same location this 2 other errors:

  Recoverable fatal error: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given

  Notice: Undefined index: value in Drupal\Core\Field\Plugin\Field\FieldWidget\NumberWidget->errorElement()

Now I can't upload images and that don't allow me to add new content.
I already try to create a new field but that didn't work.

PS: I think the error has to do something about Image Crop because before this error happen a box to crop my image would appear after I upload and know I upload and no box to crop the image.. And when I press save and publish content the error pops

  The specified file temporary://filekrGdEp could not be moved/copied because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions.

This sounds very much like a permission issue. Please check the permissions of

  /home/user/public_html/sites/default/files/2017-02

The directory must be writeable for Drupal. Set its permissions at least to 710. You might want to set them for testing purposes to 755 or even 777 to see if your error messages disappear.


How to change Webform field value after a webform has been submitted I have a webform with a hidden field having a default value of No.  How do I change this value to Yes after a webform has been submitted using Rule? I'm using Drupal 7.x.  Thank you.

You should make a custom module, rather than using Rules.

Your module will implement the hook_webform_submission_presave, as shown also in webform.api.php inside webform directory.

Your function should look like this (well, this could be your entire .module file):

function mymodule_webform_submission_presave($node, &$submission) {
  $component_id = 3; //that's your hidden field
  $submission->data[$component_id]['value'][0] = 'Yes';
}

Making a custom module is very easy, take a look here.


How to generate feature containing date types and date format? I have created new date types and date formats using Drupal 7 UI. But I can't generate feature for both of them (format and type). Only format is available in Strongarm but type isn't. Please tell me how to generate feature for both of them.

There is another option: hardcode the date format in the preprocessor. And print it in the node you are using. In this way it is in your code base and you do not need to have it in your feature.


no www redirects to front page I recently taken over a Drupal site to maintain and work on the design bit. I'm having an issue where if I enter a page on my site without the www prefix, I get directed to the front page. You should of course end up on the correct page anyway, maybe with the www prefix added.

I'm checking the .htaccess file and there i noticed this part:

 # If your site can be accessed both with and without the 'www.' prefix, you
 # can use one of the following settings to redirect users to your preferred
 # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
 #
 # To redirect all users to access the site WITH the 'www.' prefix,
 # (http://example.com/... will be redirected to http://www.example.com/...)
 # uncomment the following:
 RewriteCond %{HTTP_HOST} !^www\. [NC]
 RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 #
 # To redirect all users to access the site WITHOUT the 'www.' prefix,
 # (http://www.example.com/... will be redirected to http://example.com/...)
 # uncomment the following:
 # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
 # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

As you can see I did comment out the first two rows so I thought this would correct this issue, but no, I get no change at all. Anyone got any idea about what could be wrong?

I also noticed this lines, which mentions a index.php redirect. But I can't really understand if this causes my problem.

 # Pass all requests not referring directly to files in the filesystem to
 # index.php. Clean URLs are handled in drupal_environment_initialize().
 # RewriteCond %{REQUEST_FILENAME} !-f
 # RewriteCond %{REQUEST_FILENAME} !-d
 # RewriteCond %{REQUEST_URI} !=/favicon.ico
 # RewriteRule ^ index.php [L]

There seems to be no 404 page but every wrong adress get redirected to the front page.

Try using this old method

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Replace example with your domain name.

Still if you have the problem check your Redirects in Hosting Control Panel or you can contact them to support this.


Autocomplete taxonomy with depth field I am looking to achieve the next functionality:

I have a content type about fruits, I've added an autocomplete taxonomy field to the content type with the possibility to register new taxonomy.

I would like to achieve some taxonomy depth.

I am using the autocomplete deluxe module

For example, I input in the field apple, fresh, and green.

When I go to the fruits taxonomy vocabulary, I would like to have the taxonomy depth like this.

Instead, I get the following.

Is there a way to achieve this with taxonomy autocomplete field?

I suggest implementing hook_entity_presave() getting values from taxonomy term reference field. If always the pre-term will be the parent of the current term then loop through the results of the term ids:

 if ($entity->getEntityTypeId() == 'node') {
    if ($entity->bundle() == 'Machine_Name_content_type') {
    // Get the values from taxonomy term:
    $terms = $entity->get('field_tags')->getValue();
    if (!empty($terms)) {
        foreach($terms as $key => $value) {
            // Exclude the first term because this will be the parent.
            if ($key != '0') {
                // Get the parent of the element.
                $parent = $terms[$key -1];
                // Load the current term.
                $term_loaded= \Drupal\taxonomy\Entity\Term::load($value['target_id']);
                // Set the parent: the term before.
                $term_loaded->parent = ['target_id' => $parent['target_id']];
                $term_loaded->save();
            }
        }

     }
  }
}

Hope to help you!


"managed_file" form field type returns null value in my form submission I am have been struggling with this for the past day or so. I am simply trying to create a custom entity and populate/or update the image field with the fid. Whats weird is that every other form field I am passing I can get the value for but this managed_file field for uploading an image always returns NULL when I call dpm().

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

Within my form_build function, I use the following code.

// Manage file.
$form['theimage'] = array(
  '#type' => 'managed_file',
  '#title' => 'Managed file',
  '#description' => $this->t('Manage file, #type = managed_file'),
  //'#default_value' => $form_state->getValue('theimage'),
  '#upload_location' => 'public://images/',
  '#required' => FALSE,
);

In the submission handler, I use the following code.

// Get the fid value, upload it and save it to the managed file table.
$fid = $form_state->getValue(['theimage', 0]);
dpm($fid);
if (!empty($fid)) {
  $file = File::load($fid);
  $file->setPermanent();
  $file->save();
}

Any thoughts, solutions, or recommendations would be greatly appreciated.

After alot of digging/debugging i discovered that i could not pull any data from the "manage_file" field while using the PrivateTempStore in my Multi-Step form. After disabling the form cache, i began to get the values and the expected behavior by using:

$form_state->disableCache();

My Submit Handler

public function buildForm(array $form, FormStateInterface $form_state) {
 /**
 *  Fixes image upload bug in form. Does not work unless we
 disable the cache while using PrivateTempStore
 **/

 $form_state->disableCache();

.......

}

See https://www.drupal.org/project/drupal/issues/2647812#comment-11683961


User registration form validate and submit hooks not called I try to add custom validation or submit function to the user registration form, but nothing works.

Here is the code in /sites/all/themes/mytheme/template.php:

function mytheme_user_register_form_validate (&$form, &$form_state) {}
function mytheme_form_user_register_form_validate (&$form, &$form_state) {}
function mytheme_user_register_validate (&$form, &$form_state) {}
function mytheme_user_register_form_submit (&$form, &$form_state) {}
function mytheme_profile_user_form_validate (&$form, &$form_state) {}

I also put similar code to /sites/all/modules/custom/mymodule/mymodule.module:

function mymodule_user_register_form_validate (&$form, &$form_state) {}
function mymodule_form_user_register_form_validate (&$form, &$form_state) {}
function mymodule_user_register_validate (&$form, &$form_state) {}
function mymodule_user_register_form_submit (&$form, &$form_state) {}
function mymodule_profile_user_form_validate (&$form, &$form_state) {}

None of the above functions are called and I have ran out of ideas.
As a proof that something works on this form, here is something that does work:

function mytheme_form_user_register_form_alter(&$form, &$form_state, $form_id) {}

This gets called!! But I need to validate...

By the way, the debugger shows (among other) this when debugging the hook_form_alter:

$form['#validate'][0] = 'user_account_form_validate'
$form['#validate'][1] = 'user_validate_picture'
$form['#validate'][2] = 'user_register_validate'
$form['#validate'][3] = 'profile_user_form_validate'

Add this in your hook_form_alter:

$form['#validate'][] = 'your_validation_function';

This way you can define an additional validation functions. Make sure you report all validation errors using the form_set_error() function.


Using custom JavaScript Is there a location where I can drop in a custom JavaScript file in Drupal 7.x?

It just includes simple event actions for menus, and I don't want to edit the theme/module files.

Or do I have to just add the "include" hook to the theme/module?

There's three places where you can put your Javascript resources:

Your theme folder. If you have a theme in your site named Mechaflash, you could put it inside Mechaflash/js or just in Mechaflash. In order to make the theme folder "more organized", generally people create a dedicated js folder. I would place Javascript in the theme when your Javascript delivers functionality specific to the theme / presentation layer, or that it affects all of the site (global).
In one of your custom modules. The same principle of creating a dedicated js folder can also apply here. I generally put JS on the modules when the Javascript is delivering a very specialized functionality relevant to a specific module. It also allows you to "package" your Javascript with your modules and to pass this modules to other sites (i.e. a modular approach).
In the site's library folder. I've never done this personally. Not because it's bad, but because I think it's reserved for more complex functionality that other modules (and themes) can use. A good example, the JQuery UI library.

You can do all of this using the drupal_add_js() function. Here are some examples of how to add a JS file from a module:

// Add a "javascript library" from your module. JS_LIBRARY is an integer constant with a value of -100, which means that `mecha_library.js` will be added before `mecha_ninja.js`.
$module_path = drupal_get_path('module', 'my_module');
drupal_add_js($module_path. 'js/mecha_library.js', array('group' => JS_LIBRARY));

// Add a javascript file from your module. The default 'group' here is JS_DEFAULT, so mecha_ninja.js will be added after mecha_library.js.
$path = drupal_get_path('module', 'my_module');
drupal_add_js($path. 'js/mecha_ninja.js', 'file');


How can I programatically log another user out in D7? On our site we have client accounts, each with a super administrator and sub users belonging to that account.

We want the super admin to be able to force sub users to log out. What's the best way to destroy a user's session in Drupal that works regardless of whether the session information is stored in Redis, Memcache or the database?

Before someone feels tempted to suggest user_logout(), that destroys the current user's session. I want the current user to be able to destroy a different user's session!

drupal_session_destroy_uid() sounds like a safe bet:

  Ends a specific user's session(s).

The core implementation clears the database, as you'd expect, but any module that overrides session.inc, and doesn't provide a working implementation of that function, would surely be considered broken (as user_delete_multiple() and other functions need it).

So in theory you should be able to use that function regardless of the storage.


How to troubleshoot Rules when a required variable for an event is not provided? I'm seeing a strange behavior on my site and I'm trying to figure out how to correct it.

I have a rule that triggers on the event After updating an existing user account.  This rule uses two variables, account and account-unchanged.  Both of these should be provided by default.

However, for some reason user accounts are being saved upon login-- and when they are saved at login, account-unchanged is unset.  This leaves a PHP warning in watchdog.

To remove this error, I attempted to add a condition, Not data value is empty (account-unchanged, but this just gives me another watchdog warning like so:

  Unable to evaluate condition data_is_empty.

Ideally I will be able to find the reason why user accounts are being saved on login, but in the meantime, is there a way to prevent the rule from being evaluated when a required variable is not set?

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected).

Note: maybe it's worth to do some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?"


Hide tab for user page for specific roles I am trying to hide tab for user page. This is good script but work only for node type. How can I make it work for user pages?
Thanks to all!

function bartik_preprocess_page(&$variables, $hook) {
    if (!empty($variables['node']) && $variables['node']->type == 'article' && in_array('editor', $variables['user']->  roles)) {
        $to_be_removed = array('node/%/edit', 'node/%/view');
        foreach ($variables['tabs'] as $group_key =>$tab_group) {
            if (is_array($tab_group)) {
                foreach ($tab_group as $key =>$tab) {
                    if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $to_be_removed)) {
                        unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

/--------
Update
--------/

Now I tryed this:

function my_theme_preprocess_page(&$variables, $hook) {
    /* Hide Tabs in users page */
    global $user;
    $arg = arg();
    if (($arg == 'user') && in_array('gestore', $variables['user']->roles)) {
        foreach ($variables['tabs'] as $group_key =>$tab_group) {
            if (is_array($tab_group)) {
                foreach ($tab_group as $key =>$tab) {
                    if (isset($tab['#link']['path'])) {
                        unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

But not work.

/----- Last Update -------/

This works. Thx @Yogesh.

global $user;
if ((arg(0) == 'user') && in_array('editor', $variables['user']->roles)) {
    foreach ($variables['tabs'] as $group_key =>$tab_group) {
        if (is_array($tab_group)) {
            foreach ($tab_group as $key =>$tab) {
                if (isset($tab['#link']['path'])) {
                    unset($variables['tabs'][$group_key][$key]);
                }
            }
        }
    }
}

You can use arg() function. The function returns a component of the current Drupal path. i.e. if you're on edit user page, the values returned by arg() function will be arg(0) as 'user', arg(1) as user ID, arg(2) as 'edit'.

function bartik_preprocess_page(&$variables, $hook) {
  $arg = arg();
  if (('user' == $arg) && (!empty($arg[1]) && is_numeric($arg[1])) && in_array('editor', $variables['user']->roles)) {
    // Your code goes here..
  }
}


How to pre-populate a text field when creating a new node? I am using Drupal 7. I have a Content Type called Request. I have two fields "Manager Name" (type Text) and "Manager Email Address" (type Email). When the user creates a new node of type Request, I want to pre-fill these fields with "Hello World" and "nobody@yahoo.com". Here is what I have tried so far (This is all in mymodule_form_node_form_alter):

$form['field_manager_name']['und']['#default_value'] = "Hello World";
$form['field_manager_name']['und']['#suffix'] = "Enter in the name of your immediate supervisor.";
$form['field_manager_email_address']['und']['#default_value'] = "nobody@yahoo.com";
$form['field_manager_email_address']['und']['#suffix'] = "Enter in the email address of your immediate supervisor.";

The two suffixes are working. When I create a new node of type Request, the suffix text appears under the field name, as expected. But the "default_value" fields are not working. What am I doing wrong?

instead of $form['field_FIELD_NAME']['und']['#default_value'] you should use
$form['field_FIELD_NAME'][LANGUAGE_NONE][0]['value']['#default_value']
try something like:

$form['field_manager_name'][LANGUAGE_NONE][0]['value']['#default_value'] = 'hello world';
$form['field_manager_email_address'][LANGUAGE_NONE][0]['email']['#default_value'] = "nobody@yahoo.com";


How do I display, in a ColorBox popup, a caption AND a title (caption from image 'alt' attribute and title from 'title' attribute I am trying to display in a ColorBox popup, a caption AND a title (caption from image 'alt' attribute and title from image 'title' attribute).
The colorbox is opened when an image is clicked.

Here is an example of what I want to do.

The img will be something like the following.

<img typeof="foaf:Image" src="http://localhost:4444/img.jpg" width="336"   height="254" alt="LEGEND / CAPTION balbalblalblalba balbalblalblalba balbalblalblalba" title="TITLE balbalblalblalba balbalblalblalba balbalblalblalba" class="">

Do you have any idea of how can I do that?

I am using:

Colorbox 7.x-2.10
Drupal 7.35

The colorbox module settings are the following.

Add "colorbox" class to your element. You could also select by document.getElementsByTagName("img"), but we don't really want to select every single img tag.

var cbox = document.getElementsByClassName("colorbox")

for (var i=0, i < cbox.length; i++) {
  cboxTitle = cbox[i].title;
  cboxAlt= cbox[i].alt;

  cboxTitle = "" + cboxTitle + " " + cboxAlt + ""
}

You then just got to make colorbox print out the title tag and style it the way you want.


How to make Drupal upload pasted links to .doc files from the internet Let's say I have a Drupal website and I want there a function that would work like this:
Paste an URL to a .doc file, so on submit Drupal downloads that file, uploads to its local server and generates a link to download from the website.

I was wondering if this needs custom coding or can this be achieve with a module?

Can be achieved with Filefield Sources module.

  FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser


How to fix the fatal error due to cached data while migrating? I was trying to migrate my site from one computer to another. I have imported .sql file from database from my first database (unfortunately forgot to clear cache) and created a new database in the second and exported the data. Then i have tried to point the settings.php's database array to the newly created database in the second computer but when i tried to access the page, i get a white screen with the following error

  Fatal error: require_once(): Failed opening required '/var/www/html/sites/pullup.local/modules/remote_stream_wrapper/remote_stream_wrapper.inc' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/html/includes/bootstrap.inc on line 3186

Where sites/pullup.local was my site folder in the first computer which is not present here. Then i tried to remove all the entries in the database starting with "cache". Even after clearing all the entries in the cache tables i am getting same error and I am not understanding that from where old folder path coming.

I also tried to remove the database entry from settings.php then it is working normal as the web installation page coming up. So I think something caches the old folder in the database (DRUPAL_ROOT variable value is cached).

How can I fix the problem?

Drupal uses code registry to load the files containing a class or an interface. While the code registry is cached in cache_bootstrap, it is contained in the registry and registry_file database tables.

To rebuild it, I would edit those database tables to change the path shown in the filename row to match the new site's path. Other methods that require bootstrapping Drupal would probably not work, since any class Drupal would use would not be found, causing a PHP exception, and stopping the bootstrap, with the effect that Drupal would not run the necessary code.


Drupal 8: Add custom class according to taxonomy in Views I have content type car, which has three fields: car model, year model and category (taxonomy term). In taxonomy term, I have three lists: volvo, toyota and BMW.

In the picture below, I have added a custom class called grid-item and besides that I would like to add a category name such as volvo, toyota or BMW. I would able to add category name if replacement patterns has been available :/

In the source code, you guys can see that I have class grid-item and I want to have a category name accoding to cars next to it.

You add taxonomy filed in view and Exclude from display this field.


How do I install the Spark distribution using only Drush? How do I fire up the Spark Distribution via a drush command?

From comments:

Clive: drush make build-spark.make ~/Sites/spark - Building Spark from Drush Make yourself


How to place Drupal_Security_Do_Not_Remove_See_SA_* into httpd.conf instead of .htaccess I run several Drupal 7 installations on a dedicated server with CentOS 6.4 and Apache 2 (the package httpd-2.2.15-29.el6.centos.x86_64).

I wonder, how to properly configure the Drupal_Security_Do_Not_Remove_* handlers in my /etc/httpd/conf/httpd.conf file since .htaccess files are disabled at my server by AllowOverride None directive.

Currently I have the following sections in httpd.conf for each of my sites:

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>
    </IfModule>
</VirtualHost>

And the recommended settings for the .htaccess are those here:

Options None
Options +FollowSymLinks

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Should the result in my case be the following?

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    Options None
    Options +FollowSymLinks
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files /var/www/html/mysite1.de/sites/default/files/*>
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>

        <Directory "/var/www/html/mysite1.de/sites/default/files">
            php_flag engine off
        </Directory>
    </IfModule>
</VirtualHost>

.htaccess files are just convienance mechanisms to change Apache configuration without needing to restart Apache (.htaccess are scanned/run any request) -- for performance reasons you may want to place any directives in .htaccess files directly into a vhost entry so the configuration is loaded and stored only one time; on Apache startup.

From the security notice SA-2013-003:

  Warning: Fixing the code execution prevention may require server
  configuration; please read:

  To fix the code execution prevention
  vulnerability on existing Apache installations also requires changes
  to your site's .htaccess files in the files directories. Until you do
  this, your site's status report page at admin/reports/status will
  display error messages about the problem. Please note that if you are
  using a different web server such as Nginx the .htaccess files have no
  effect and you need to configure PHP execution protection yourself in
  the respective server configuration files.

  To fix this issue, you must edit or replace the old .htaccess files
  manually. Copies of the .htaccess files are found in the public files
  directory and temporary files directory, and (for Drupal 7 only) the
  private files directory if your site is configured to use one.

So you take whatever is in the .htaccess file in your websites configured files directories (public, private, etc) and assure those same rules are in the vhost entry for the same set of directories. Typically you do this with a <Directory> directive:

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>
    </IfModule>

    # Enforce new security rules from SA-CORE-2013-003.
    # repeat this block as needed per known "files" directories.
    <Directory "/var/www/html/mysite1.de/sites/default/files">
      # Turn off all options we don't need.
      Options None
      Options +FollowSymLinks

      # Set the catch-all handler to prevent scripts from being executed.
      SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
      <Files *>
        # Override the handler again if we're run later in the evaluation list.
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
      </Files>

      # If we know how to do it safely, disable the PHP engine entirely.
      <IfModule mod_php5.c>
        php_flag engine off
      </IfModule>
    </Directory>
</VirtualHost>

It doesnt matter if the default web directory has AllowOverride None; typically another conf file included down the apache startup chain, or the virtual host loading setup (such as the following in Ubuntu) can be tweaked to allow any combination of Overrides:

# Ubuntu apache2.conf last line ...
# Include the virtual host configurations:
Include sites-enabled/

This is just saying include *.conf from sites-enabled these dont have to be vhost entries they can be any files with apache directives (but its cleanest to have them be vhost entries) and apache loads the configuration files following a filename pattern/sort.


How to theme the create content of custom content type? I have a custom content type property. The registered user can create the property when logged in. I want to theme the "create property page" the same as the site's default theme. Please let me know how we can theme the "create propery page". Is there any module or do we need to do something else?

Sometimes I want certain roles to see the admin theme on a given page, and sometimes I don't. whitefleaCH's ThemeKey suggestion might address that better (haven't tried that module) but another module suggestion that addresses this is Page Theme. Extremely simple module that does exactly what it's name implies:

Install the module
Go to /admin/structure/page-theme and click "Add theme"
Pick your installed theme and add "node/add/property" and "node/edit/property" and any number of other relative paths to the "Pages" field.

Anyone visiting any of those paths will see the content through the theme you designated.


Drupal commerce: Save into a customer profile field im trying to save into a customer profile field. Reading it out is no problem:

if(!empty($order_wrapper->commerce_customer_billing->field_shop_annotations)) {
$annotations = $order_wrapper->commerce_customer_billing->field_shop_annotations->value();
}

But saving into gives me an error message. Here's my code:

// Save annotations
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$annotations = $form_state['values']['annotations'];

$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

$profile = commerce_customer_profile_load($profile_id);

if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {
   // This gives me the error message:
   $profile_wrapper->commerce_customer_billing->field_shop_annotations->set('muh');
}

Everthing works fine except the set method inside the if clause. I also tried:

$profile_wrapper->commerce_customer_billing->field_shop_annotations->value = $annotations;

ok i got it:

$annotations = $form_state['values']['annotations'];
global $user;

// load oder
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

// get profile id
$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

// load customer profile
$profile = commerce_customer_profile_load($profile_id);
if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {

       // set the value of the field and save the profile
       $profile_wrapper->field_shop_annotations->set($annotations);
       $profile_wrapper->save();

}


How do I move more link to title of views block? I am using Drupal 7 and Views, I created a block and a "more link" for showing on the frontpage.

How can I move the "more link" next to the title of views block?

You should copy the views-view.tpl.php from views module into your theme folder. If you want to do this only for a specific views, you should also rename the file like views-view--your-view.tpl.php. Then you can simply move the 'more link' part wherever you like in this template file.

UPDATE:
Thanks to @Mołot's pointing about an issue that the title is rendered by the block, I've found out that there is already a discussion about that in the API page. As a workaround, you can set in the block configuration the title to <none> so that it isn't rendered by block. And in the views template replace the following part which is responsible for printing title:

<?php if ($title): ?>
  <?php print $title; ?>
<?php endif; ?>

with this:

<?php if (empty($title)): ?>
  <?php $title = check_plain($view->get_title()); ?>
<?php else: ?>
  <?php print $title; ?>
<?php endif; ?>


How do I store my client's passwords securely and make them retrievable? I am building a site that holds information about my client's computers. One piece of information I want to store is the password for an account on each computer. I want my authenticated users to be able to log on to my site and, if they have the right permissions, be able to see these passwords (maybe by clicking a 'show password' button).

The problem with this is that I can't store just the hashed versions of these passwords in the database because obviously then there is no reliable way of getting them back to plaintext, and I don't want to store the passwords as plaintext in the database either (unless access to this part of the database is strictly password protected by my authenticated user's passwords, which I don't know how to implement), so I was wondering if anyone has any suggestions of securely providing this functionality?

Making the passwords secure and retrievable in Drupal seems mutually exclusive to me so if anyone knows of any external services that might work then I would be very interested in hearing about them as well.

I am using Drupal 7.41.

Try either the Field Encrypt module:

  Adds options to encrypt field values.

  The goal of this module is to create a method for encrypting field
  values when stored in the database.

  This module depends on the Encrypt module
  (http://drupal.org/project/encrypt) for encrypting and decrypting
  strings.

Or which sounds better for your use-case of "settings" the Encrypted Settings Field module:

  This module adds the "encrypted settings" field through Field API,
  which has the following two features:

  The field can be encrypted before saving to the database
  The field can be validated to follow INI format

  This module is ideal to save
  credential settings information, such as a "Credit Card" field to add
  to users' profile.

A more developer friendly form which stores the final encrypted value into the drupal database and plays nicely with Drupal 7 core Form API elements is the Encrypt Form API module:

  After installing and enabling this module, you will be able to add an
  '#encrypt' property to any of the following supported Form API element
  types:

  textfield
  textarea
  checkboxes
  checkbox
  radios
  radio
  select
  password
  password_confirm

To use this module I would recommend assuring your site is served only in SSL, then the contents of the field is encrypted on save, after normal form validation occurs.


Where are config dependencies stored? I have this error when importing a single piece of config manually:

  Configuration foo.api depends on the MODULE extension that will not be installed after import.

There is no "MODULE" extension in the file system, core.extension config, the KeyValue table, config_snaphot, or anywhere else that I'm aware of that would be related.

If I delete the config

\Drupal::configFactory()->getEditable('foo.api')->delete();

Then try the import, it works. Great.

But as soon as I go back to my config form and save foo.api, the next time I try to import, I get the same error all over again.

This leads me to believe that a dependency tree must be stored somewhere, and that it isn't cleared when config is deleted.

Is this true, and if so where is it? If not, how can I resolve this?

I guess this could also be rephrased as How are module dependencies for basic configuration calculated, and how do you manually update them when they’re wrong?

The error you see is output from ConfigImportSubscriber::validateDependencies(), which uses the following code.

  // Validate the dependencies of all the configuration. We have to validate
  // the entire tree because existing configuration might depend on
  // configuration that is being deleted.
  foreach ($config_importer
    ->getStorageComparer()
    ->getSourceStorage()
    ->listAll() as $name) {

    // Ensure that the config owner is installed. This checks all
    // configuration including configuration entities.
    list($owner, ) = explode('.', $name, 2);
    if ($owner !== 'core') {
      $message = FALSE;
      if (!isset($core_extension['module'][$owner]) && isset($module_data[$owner])) {
        $message = $this
          ->t('Configuration %name depends on the %owner module that will not be installed after import.', [
          '%name' => $name,
          '%owner' => $module_data[$owner]->info['name'],
        ]);
      }

The code assumes that for a name like node.type.article the owner is the Node module. If the owner is not one of the installed modules, Drupal gives the error you see.

To answer your question, the module name is assumed to be stored in the configuration filename.


Setting upper limit on user profile picture I am not finding any option to set upper limit on user profile picture. Currently user can upload file of any size. I want to prevent this scenario and allow user to upload his picture of maximum 2Mb  or other.

How can set upper limit on profile picture?

You'll find it here: admin/config/people/accounts


Placing a block next to the comments section I have a problem that I have been working for hours now.  Basically, I would like to place a block next to the comments div.  So, in the footer of my page, I'd have all the user comments to the left and in the right side, I'd have my block.  I know I have to do some realignment in the page.tpl.php, but I just can't get the comments div and the block div to appear side by side.  Would appreciate any help on this.

Edit:

I added this in my template.php file:

/**
 * Custom function to render a block to manually position it in the node.tpl.php markup
 */
function mytheme_block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}

function mytheme_preprocess_node(&$vars) {
    //Add the related_by_term block to the variables array so that we can render it in our node.tpl.php file
    $vars['my_block'] = block_render('views', 'my_block-block_1');
}

And in my node.tpl.php, I added this after the comments section:

<?php print $my_block; ?>

But what I am getting is a memory limit exceeded error.  Basically, the block_render function is causing some problem. It's this line that is causing the problem:

_block_render_blocks(array($block));

Any input would be highly appreciated.  Spending hours on this issue.  Thank you...

The regions are usually printed in the page.tpl.php

And the comments are printed with in the node.tpl.php

You could follow the below steps to get a region with in node.tpl.php

Add a region in the .info file by adding regions[custom] = Custom
If you already have a preprocess_node in you theme template.php then add the below code or else create a function in the template.php with the name mythemename_preprocess_node(&$variables)

$variables['custom'] = block_get_blocks_by_region('custom');

This would give you a variable with in the node.tpl.php named custom. This is a renderable array of the blocks with in the region.

Now in your node.tpl.php you would be having something like <?php print render($content['comments']); ?> above or below that you can add

Or you could wrap them in a DIV to suit your requirement.

What ever you add to The region custom would now be displayed near the comments


Use "date_views_filter_handler" filter handler for custom table field How can I use "date_views_filter_handler" defined in date module as filter handler for a column of integer type on custom table while exposing it to views.

I will not say this answer the question I asked but must say this answer worked the way I want.

Instead of using "date_views_filter_handler" I used "date_views_filter_handler_simple" and it just worked like a charm.Here is what I did while exposing my custom table to views.

  $data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'date_views_filter_handler_simple',
    ),
  );


How to input internal CSS to content items with CKeditor Sometimes I don't have time to input css in the stylesheet, so I would like to simply add it directly to the article.

Since content items don't seem to have any  tags when viewing source, the tags get stripped.

How can I get this done, for example:

This is a heading

I have tried to add it inline, and it shows up when editing before saving, but not showing up on front end, only in back end.

If you are using Filter HTML go to:

/admin/config/content/formats/filtered_html

add the <style> tag to the limit allowed html tags

If the above does not do it, depending on which one you are using (filter or full html) You need to go to

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.


Webform: get field value from the Entity select option I have an entity select list based on View which collects a list of groups and their corresponding email address(may not be unique!).
It seems that there is bug in entity_reference.module so only titles of nodes are displayed.

I want to send emails based on the selected group. I have tried to set the Custom To email address using tokens but failed.

[webform_submission:values:groups:0:entity:field_email:*]
[webform_submission:values:groups:0:entity:field_email:value]
[webform_submission:values:groups:field_email:value]

Do I type the wrong tokens or is there any other alternative solution for this situation?

I was able to get all three of the below tokens to pull the single first email address for the group node's field_email.

[webform_submission:values:groups:entity:field_email]
[webform_submission:values:groups:0:entity:field_email]
[webform_submission:values:groups:0:entity:field_email:value]

Only [webform_submission:values:groups] returns 'Node Title (NID)'.


What does the entity_view function do? After reading the documentation and searching through code, I can't quite figure out what the entity_view function is for.

The documentation explains it executes the view callback if defined, with a fallback to the entity controller's view function. Since I use the EntityAPIController I want to use that view function, that adds a similar structure like below.

So I assumed entity_view is to replace a structure like this (part of a page callback).

// Prepare the entities
entity_prepare_view('entity_type', $entity_field_query_result);

// Apply theme to all entities
foreach($entity_field_query_result as $key => $item) {
  $entity->content = array();
  $entity->content += array(
    '#theme'     => 'my_entity_theme',
    '#element'   => $item,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  $render[$key] = $entity->content;
}
return $render;

Thus I've replaced that with

$render = entity_view('entity_type', $entity_field_query_result);

return $render;

This however shows an empty page, where the previous function showed me a list of entities. I have custom themes applied to these entities as follows, could that be an issue?

function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_entity_theme' => array(
      'variables' => array('element' => null),
      'template' => 'my_entity_theme',
      'path' => $path . '/template',
    ),
  );
}

So, is my assumption on entity_view correct, or am I missing steps to come to a renderable output?

A EntityFieldQuery doesn't return fully loaded entities as result.
Try running the query result through entity_load('type', $result['type']). Then you can render the resulting entites through entity_view('type', $entities).

Here an example:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'article');
$result = $query->execute();
if (!empty($result)) {
  $entities = entity_load('node', array_keys($result['node']));
  return entity_view('node', $entities, 'full');
} else {
  return array('#markup' => t('No article nodes found.'));
}


How Do I pass the Option description in Checkboxes to a webform result I have a 3-option checkbox built as follows in Drupal 8.

How do I pass the value of the option title selected by the user into the webform submission result?

For example in the below, if a user chooses 21, the result should show 21 in the submission result.

[] 21
[] 22
[] 36

Each check box is a node field fld1, fld2, fld3. I have got these displaying correctly but the result shows up as [fld1] for option 21

Additional details

Here is the raw source generated by the webform module. This is Drupal 8 btw.

choose_a_value:
  '#type': checkboxes
  '#title': 'Choose a value'
  '#options':
    '[webform_submission:node:field_fld1:value]': '[webform_submission:node:field_fld1:value]'
    '[webform_submission:node:field_fld2:value]': '[webform_submission:node:field_fld2:value]'
    '[webform_submission:node:field_fld3:value]': '[webform_submission:node:field_fld3:value]'
   '#required': true
  '#required_error': 'Please choose a value'

It roughly depends on how you build that form element. Form API or Field API? Seems you are with Field API here. In general all you have to do is to provide an associative array for the options where key equals value.

Form API

Here comes a simplified example for Form API. You might want to use $options = array_combine($my_array, $my_array); to build the options array dynamically.

$options = [
  '21' => '21',
  '22' => '22',
  '36' => '36',
];

$form['my_element'] = [
  '#type' => 'checkboxes',
  '#title' => 'Choose',
  '#options' => $options,
]

Field API

With Field API and the list field you have to build the associated array in the Allowed values list like in the following example. Simply divide key and value with a pipe character.

21|21
22|22
36|36


How to approach implementing a custom page header for each page I am building a site that gives the content managers the ability to craft a masthead image, teaser text, and headline text for each individual page. This will appear in an area outside of node.tpl and -- anyway -- can also appear on taxonomy index pages, etc.

My current approach involves creating a Header content type and adding an EntityReference field to each entity I use in the site, then modifying page.tpl.php to look for and render that field. But is there a smarter approach?

Edited

The site is a multilingual site, so I'm looking for something that supports i18n. That lets Field Collection out, unfortunately.

You might want to look at a solution using Minipanels.

Minipanels are basically Panels (shipped together) that can be used as a block.

You could create a minipanel with the required content and assign that block to the header region for a particular page.

Alternatively, you could set it up as a content type with an image, title and teaser and then a template or view mode to render it in the header.


Filter results using taxonomy terms I have an index for a content type that has a taxonomy field attached.

I have a fulltext search up and running using the index, but would like to be able to filter the results additionally using tags.

If I add the taxonomy field to the index, it is added as an integer value, and the ID of the tag assigned is being indexed in Solr.

If, however, I try to add the field as a filter in my View, I get an error that there is no handler available.

What is the correct way to implement filtering by taxonomy term?

IMHO the best way is to add the taxonomy's name to the index.  This may not be shown as an option in D7 if you have not asked for the fields to be extended to the referenced entities.

Note: expanding the field list in D7 can make the field list take Minutes to load and you may get a few script running long warnings.  Be patient and let the script keep running.  The list will come up eventually.

Once you have the text in the index, you can use this in either the search view filter or use it in a facet.

An alternative would be to add a relationship between your term id search field to the actual term data.  Then you should have the term name available for use.

Note that this method will add a lot more overhead to your search than just having the term names in the index.


How to read a Entity reference node's fields? I had a field using entity reference in my site. I'm trying to develop a module can read/use it.

$wrapper = entity_metadata_wrapper('node',$node);
dpm($wrapper->myRefField->getPropertyInfo());

This returns a error page, but dpm($wrapper->myRefField) shows that it's a standard EntityDrupalWrapper, though nothing in it.

How can I read $nid of the referenced node?

Errors below:

 Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation &quot;node&quot; does not exist LINE 3: node base ^: SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log, revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky, base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed, base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision_timestamp, revision.uid AS revision_uid FROM {node} base INNER JOIN {node_revision} revision ON revision.vid = base.vid WHERE (base.nid IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] =&gt; 1 ) in DrupalDefaultEntityController->load() (line 191 of /var/www/site2/includes/entity.inc).

Additional

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation &quot;filter_format&quot; does not exist LINE 3: filter_format ff ^: SELECT ff.* FROM {filter_format} ff WHERE (status = :db_condition_placeholder_0) ORDER BY weight ASC; Array ( [:db_condition_placeholder_0] =&gt; 1 ) in filter_formats() (line 427 of /var/www/site2/modules/filter/filter.module).

Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation &quot;semaphore&quot; does not exist LINE 1: DELETE FROM semaphore ^: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] =&gt; 18701629495353e89467a483.34692095 ) in lock_release_all() (line 269 of /var/www/site2/includes/lock.inc).

Uncaught exception thrown in session handler.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation &quot;sessions&quot; does not exist LINE 3: sessions sessions ^: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] =&gt; sLS3fA1YAd1u1G6_xC1yxg0Ba6Kgrus6oXDBm4Wpuww [:db_condition_placeholder_1] =&gt; ) in _drupal_session_write() (line 209 of /var/www/site2/includes/session.inc).

<?php

/**
 * We define a new function in our MODULE and will simply use it where needed.
 *
 */

/**
 * @param (object) $node
 * @param (string) $field_name
 * @return false|null|integer
 *    The target id. FALSE on error. NULL when no reference found.
 */
function _MODULE_get_node_reference($node, $field_name) {
    $target_id = null;
    if (!isset($node->type)) {
        return false;
    }
    // In case of any exception we simply return false.
    try {
        $entity_wrapper = entity_metadata_wrapper('node', $node);
        if (isset($entity_wrapper->{$field_name})) {
            $target_id = $entity_wrapper->{$field_name}->value();
        }
        // maybe we are in the middle of a DB transaction. In that case entity_metadata_wrapper() would not work
        if (empty($target_id)) {
            // So, we try using Fields API. This always works.
            $items = field_get_items('node', $node, $field_name);
            if (isset($items[0])) {
                $target_id = $items[0]['target_id'];
            }
        }
    } catch (Exception $e) {
        return false;
    }
    return $target_id;
}

?>


Views - Add a wrapper DIV around a Group In Drupal 7, I have created a View that lists several fields. The fields are grouped by another field (the term ID of the field). The mark up looks like this:

[Term 1]

 [Field Content]

 [Field Content]

 [Field Content]

[Term 2]

 [Field Content]

 [Field Content]

 [Field Content]

[Term 3]

 [Field Content]

 [Field Content]

 [Field Content]

However, I need the mark up to look like this:

[Term 1]

 [Field Content]

 [Field Content]

 [Field Content]

[Term 2]

 [Field Content]

 [Field Content]

 [Field Content]

[Term 3]

 [Field Content]

 [Field Content]

 [Field Content]

I know that you can use views-view-unformatted.tpl.php (Style Output) to over ride the view and then insert a DIV to wrap the group.

However, I need my wrapper DIV to be like this
. The number ID will correspond to the term that has been used to group the fields. By default, if you use views-view-unformatted.tpl.php, you cannot insert tokens for term IDs into it.

Any help would be appreciated.

I needed to do this same thing recently. You can create a template file:

Find the template under /modules/views/themes/views-view-unformatted.tpl.php.
Copy it into your /sites/all/themes/<your-theme> folder and rename to views-view-unformatted--<nodetype>.tpl.php.
Edit the file adding a div around the entire template. The
 tag is the group name.

Here is what the modified template file might look like.

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>


Views Dynamic Fields checkboxes to dropdown select I'd like to know if there is a way to modify the exposed check-boxes filter of Views Dynamic Fields module and convert it to a multi-select dropdown menu (like an ordinary exposed filter).

Unfortunately Better Exposed Filters module which makes that kind of modification possible, does not seem to apply on dynamic fields exposed filters.

Could anyone guide me how to make this kind of change on own?

U can do it through hook_form_alter, just check the form_id, and change the type of form element to that of select, it will create select list from checkboxes.

However for making it working u have to write some jQuery.

$("#<form_element_id>").on('click', function(){
$(this).closest('form').trigger('submit');
});


Error 500 (Internal Server Error) After Clearing Cache I truncated cache_block and cache_bootstrap tables in Drupal database (I don't know if its okay to truncate cache tables) and after that my site went down.

I am getting HTTP Error 500 that says

  The website encountered an error
  while retrieving www.drupalwebsite.com. It may be down for maintenance
  or configured incorrectly.

Before truncating those tables, my site was working fine. Is there any way to get it back to working??

  UPDATE -

I cleared all other cache tables too...

WEBSERVER LOGS -

  [Thu Dec 27 02:51:24 2012] [warn] [client *IP_Address*] mod_fcgid: stderr: PHP Fatal error: Call to undefined function ctools_include() in /var/www/vhosts/*my_site_name*/drupal/sites/all/modules/views/views.module on line 62

Somehow your site has entered a broken state since the Views module depends on ctools but it's not enabled.

What you need to do to fix it is to:

Enable the ctools module in the database, by running the following SQL UPDATE system SET status = 1 WHERE name = 'ctools';
Truncate all the cache tables in your database.
(Might not be needed) run $ drush rr, requires drush and the registry rebuild extension.
Run $ drush cc all requires drush.

Going through the above list should fix your site. Messing with your sites cache table can be a bit dangerous if you don't know what you are doing since drupal caches what modules it needs to load for performance.

You can read more about and download drush and registry rebuild on drupal.org.