Trigger views exposed filter on custom select box I have this view which contains an exposed filter to filter out a simple content type listing page.
The problem is about theming and keeping the view functional.
I succeeded in theming the view with a select filter, as provided to me in a static html file.

The filter is select box but the theming have it's proper tags that works similar to a select box model.
For example:

<!-- Basic select box in Drupal -->
<select data-drupal-selector="edit-filterone" id="edit-filterone" name="filterone" class="form-select">
  <option value="All" selected="selected">- Any -</option>
  <option value="13">term 1</option>
  <option value="15">term 2</option>
  <option value="16">term 3</option>
</select>

<!-- Our themer select box model -->
<custom-select label="Filter label" name="filterone">
  <custom-option label="- Any -" name="filterone" value="All" selected></custom-option>
  <custom-option label="term 1" name="filterone" value="13"></custom-option>
  <custom-option label="term 2" name="filterone" value="15"></custom-option>
  <custom-option label="term 3" name="filterone" value="16"></custom-option>
</custom-select>

Then the value selected get stored in a JS object.

In this view I use BEF (Better exposed forms) module and autosubmit is activated with a hidden apply button.

Using twig suggestions I can populate the select list with the filter values but there is no action trigged when I change the item.

The view is not applied and it act just like a static html. I need a way to keep the filter functional as normal.

I can get the values with js when a select list change but I don't know (or have a clue) how to send these values by ajax and alter the view and get back the results as normal views do.

My first thought is to keep the select boxes provided by drupal and just hide them from display and when the user changes value in the 'fake' select box, have them copied to the hidden one; and then just trigger the click on the (hidden) apply button.

Any suggestions please?
(I don't know if my explication is that clear but I can be more specific if needed, thank you)

I managed to achieve that result I had thought of. Adding same filter in hidden display and just assign new values to it when the fake select box changed; then trigger the apply button.
I had little problems with 'all' value because I was parsing the selected values before reassign them.


Problems with Views Load More module loading via AJAX I tried to add the Views Load More module to my semantic view but it doesn't load all of the view fields (e.g. image, etc.) when I use it with ajax. Can someone give me a hint why?

Here you can see the view:

http://www.mustxhave.com/testing

The site runs Drupal 7.43 and Views Load More v1.5. The view output is standard, no .tpl theming for this view.

Your problem is the image path not the load more module.

I inspected the image in your view and found that it is being requested from this URL:
http://www.mustxhave.com/mustxhave/sites/all/themes/simpnews/images/xyz-300x500.jpg
which is wrong.

Removing musthave from the URL will fix the image path.
http://www.mustxhave.com/sites/all/themes/simpnews/images/xyz-300x500.jpg

This may be caused by one of these:

Check the view settings for the image field.
Check settings.php file for base_url variable value.
Check if have Rewrite Base in the .htaccess file.


How to setup hook_install to have a geometry field on a POSTGIS database? From a module, I would like to create a table containing a POSTGIS geometry field.
I guess I need to use hook_install but can't find any definition of a geometry field anywhere. How can I achieve that ?

I have no idea if this will work (don't have a postgis install handy to test), but try

$schema['table'] = array(
  'fields' => array(
    'some_geom_field' => array(
      'pgsql_type' => 'geom',
      ...
    ),
  ),
);

If that doesn't do it I think you're out of luck using hook_schema(), you'll probably need to execute a custom SQL script instead.


Creating a page.tpl.php template for a group of pages (Drupal 7) I have a special part of my site that needs a very different kind of layout from the rest of my site.  I have created a template file called page--special.tpl.php that implements the kinds of themeing I need.  This page works fine as the long as the page that is being viewed is at the endpoint ?q=special but I do not want to have to make a different template for each page in this special section (all of which would have the same theme code).  Is there anyway to have all pages that have endpoints starting with ?q=special use this template?

Is there some other better way to do this?

If the pages www.yoursite.com/special, www.yoursite.com/special/anotherpage, etc are the actual paths to the content and not aliases, then page--special.tpl.php should work for all of them.  If, however, they are aliases to node content, eg, www.yoursite.com/special/anotherpage is really something like www.yoursite.com/node/123, then you could do something like this in your theme's template.php file...

function YOURTHEME_preprocess_page(&$vars) {

  $alias=drupal_get_path_alias($_GET['q']);
  $args=explode('/', $alias);
  if ($args[0]=='special') {
    $vars['theme_hook_suggestions'][] = 'page__special';
  }

  // any other page preprocessing here

}

...which takes a dull ax to the url and chops it apart and if the first part is special then it tells drupal to use your page template for it.  If, however, you know that all of the nodes there are of a certain type, you could do it this way instead...

function YOURTHEME_preprocess_page(&$vars) {

  if (!empty($vars['node']->type) && $vars['node']->type == 'SPECIAL_TYPE') {
    $vars['theme_hook_suggestions'][] = 'page__special';
  }

  // any other page preprocessing here

}

...which would tell drupal to use your template file whenever it displays a SPECIAL_TYPE node on a full page.


Add Object in json file generate by services module drupal I need some help about this problem. I need to add object that encompasses the hash of my json file.

I use services module in drupal 6 for generate xml and json file from my nodes.
So, when i view my nodes in json i have this:

[
{
"nid": "7",
"vid": "7",
"type": "page",
"language": "",
"title": "Bievenido", ..... } ]

But i need that this json file look like this:

[
{
"<whatever>": {
    "nid": "7",
    "vid": "7",
    "type": "page",
    "language": "",
    "title": "Bievenido", .....  } ]

How to change this json file generated by services module?

The JSON is generated by the RESTServerViewBuiltIn class in the services/servers/rest_server/includes/rest_server.views.inc file, specifically the render_json member function.

Services does provide a way to override this.

Firstly in a custom module implement hook_rest_server_response_formatters_alter and change the View class that's used to render the output to a custom one:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['json']['view'] = 'RESTServerViewMYMODULE';
}

Then add your custom View class (I'd keep this in the module file to avoid having to load includes):

class RESTServerViewMYMODULE extends RESTServerView {
  public function render() {
    $new_data = new stdClass;
    $new_data->some_key = $this->model;

    $json = str_replace('\\/', '/', json_encode($new_data));

    return $json;
  }
}

Hope that helps


How to list taxonomy terms grouped by a field with Views I have a taxonomy vocabulary called 'clients'. There's a field on that called 'category' which is a simple text list.

I want a view that results in something like:

  Category Foo

  (rendered term in category Foo)

  (rendered term in category Foo)

  Bar Category

  (rendered term in Bar category)

It seems I can group by a field, but only if I select fields as the output. Is there a way to have it group by field (for the headings) but use the rendered terms (with a particular view mode) within the grouping?

A-ha!

Tick the "Force using fields" option under the page style. This turns on the fields bit which you can then use to group by.


Base URL issue in Subdomain I have my main site as example.com and also I am running the below subdomains with help of subdomain module

one.example.com
two.example.com

I have created the html block(admin/structure/block/add) for footer to list my site links. This block is visible for main domain(example.com) and all subdomains(one.example.com,two.example.com)

But I have URL issues in that footer block in subdomains.
For example I have Suggestions in footer block, when I am in main domain it goes to http://example.com/suggestions. It goes to http://one.example.com/suggestions & http://two.example.com/suggestions when I am in subdomains.

BUT IT SHOULD GOES TO ONLY http://example.com/suggestions FOR ALL SUBDOAMINS

Any way to achieve this?

I like adding the redirect to sites/default/settings.php instead of .htaccess (just because Pantheon ignores .htaccess redirects and a lot of my sites are hosted on Pantheon). I'm also just more comfortable with the syntax.

The first example will redirect just /suggestions to example.com/suggestions. The second example redirects any path beneath /suggestions (e.g., /suggestions/submit or /suggestions/submit/thankyou) to that same path on the main domain (example.com).

In terms of wild-carding this solution for scenarios similar to 'suggestions', I don't think that would work. I mean you don't want to redirect everything so you have to check for a specific REQUEST_URI.

But you could use this solution as a template for the other redirects you need. If you have a very large number of these (or anticipate a large number in the future), you might consider switching to the Domain Access module instead as it would handle this scenario without any redirects or custom coding.

You'll need to update 'example.com' to match your main domain and you may need to change 'http' to 'https' is you're using TLS.

// 301 Redirect from /suggestions to example.com/suggestions
if ($_SERVER['HTTP_HOST'] != 'example.com' &&
  $_SERVER['REQUEST_URI'] == 'suggestions' &&
  (php_sapi_name() != "cli")) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: http://example.com/suggestions');
    exit();
  }

// 301 Redirect from /suggestions/* to example.com/suggestions/*
if ($_SERVER['HTTP_HOST'] != 'example.com' &&
    $_SERVER['REQUEST_URI'] == 'suggestions' &&
    (php_sapi_name() != "cli")) {
      $url = $_SERVER['REQUEST_URI'];
      $url = substr($url, 13); // stripping '/suggestions/' which is 13 chars
      header('HTTP/1.0 301 Moved Permanently');
      header('Location: http://example.com/suggestions/'. $url);
      exit();
  }


Where can I find in database that page (panel) is disabled? I am using Panels module. If I go to structure -> pages menu link, I will see my pages list.

I can disable/enable those pages. But how does this work under the hood? Where is it marked in the database that some specific page is disabled?

Panel pages requires Page Manager module which comes with Ctools Module.... Below function in page_manager/page_manager.admin.inc is responsible for enable / disable action...

function page_manager_enable_page($disable, $js, $page) {
  if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], $page->task_name)) {
    return MENU_ACCESS_DENIED;
  }
  if ($page->locked) {
    if ($disable) {
      drupal_set_message(t('Unable to disable due to lock.'));
    }
    else {
      drupal_set_message(t('Unable to enable due to lock.'));
    }
  }
  else {
    if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
      dpm($function);
      $result = $function($page, $disable);
      menu_rebuild();

      // We want to re-cache this if it's changed so that status is properly
      // updated on the changed form.
      if (!empty($page->changed)) {
        page_manager_set_page_cache($page);
      }
    }
  }

  // For now $js is not actually in use on this.
  drupal_goto('admin/structure/pages');
}

When a panel page (Custom Created , Not default pages that comes with module) is enabled or disabled below function is called in ctools/page_manager/plugins/tasks/page.inc...

/**
 * Callback to enable/disable the page from the UI.
 */
function page_manager_page_enable(&$cache, $status) {
  $page = &$cache->subtask['subtask'];
  ctools_include('export');
  ctools_export_set_object_status($page, $status);

  $page->disabled = FALSE;
}

You can find panel pages details inside variable table under the variable

  default_page_manager_pages

When Disabled

a:1:{s:15:"test_panel_page";b:1;}

When Enabled

a:0:{}

Default pages that comes with module enable / disable status also stored in variables table...


How to resolve the error when posting a new node with Image Field and Entity Reference? I'm trying to create a new node using Drupal 7 + Services 3. The node type is 'activity_photo' has an image field, and a reference to a node. This is what I'm posting to the service
{
 "type":"activity_photo",
 "field_node_reference":{
 "und":[{
 "target_id":"x (1273)"
 }]
 },
 "field_photo":{
 "und":[{
 "fid":"20077"
 }]
 }
}

The response is status 200:
{"nid":null,"uri":...}

My error log shows the following:

Notice: Undefined index: display_field in file_field_widget_value()
Warning: end() [function.end]: Passed variable is not an array or object in file_managed_file_validate()
Notice: Undefined index: nid in _node_resource_create()

Any help on how to proceed?

In the end I changed the entity reference field to select list and posted like this:

{
 "title":"test",
 "type":"activity_photo",
 "language":"und",
 "field_node_reference":{
 "und":[1273]
 },
 "field_photo":{"und":[{"fid":"8880"}]}
}

also, I found my own modules was implementing hook_form_alter for this form, and this had further complications to be addressed to get it to work. So any hook_form_alter is something to remember when looking for similar problems.


Custom module with its own menu? I am in the process of writing my 3rd custom module and this one is my biggest challenge yet.
I know how to use hook_menu to generate menu items, and depending on the path you choose determines where they show up on the site (administration menu or main menu, etc).

My question is - how do I specify a NEW menu, so that the paths I create do not appear in "primary links" or "navigation" but in their own "custom module" menu?

You specify the menu_name parameter.

From the devel module:

$items['devel/cache/clear'] = array(
  'title' => 'Empty cache',
  'page callback' => 'devel_cache_clear',
  'description' => 'Clear the CSS cache and all database cache tables which store page, node, theme and variable caches.',
  'access arguments' => array('access devel information'),
  'menu_name' => 'devel',
);


drush status not showing correct setting from alias file I'm trying to get drush to work with my test environment, which is actually using a separate database.

so here's my alias in aliases.drushrc.php:

 $aliases['local'] = array(
   'root' => '/my/drupal/root',
   'uri'  => 'http://localhost',
 );

 $aliases['test'] = array(
   'parent' => '@local',
   'databases' => array (
     'default' =>
     array (
       'default' =>
       array (
         'database' => 'test_db',
         'username' => 'test_user',
         'password' => 'test_pwd',
         'host' => 'localhost',
         'port' => '',
         'driver' => 'mysql',
         'prefix' => '',
       ),
     ),
   ),
 );

When I look at the drush site-alias @local and drush site-alias @test the config is read correctly.

When I run drush @test status it gives me the default status.  Notice that the username and db are the default, not my test details.

 $ drush @test status
  Drupal version                  :  7.14
  Site URI                        :  http://localhost
  Database driver                 :  mysql
  Database hostname               :  localhost
  Database username               :  default_user
  Database name                   :  default_db
  Database                        :  Connected
  Drupal bootstrap                :  Successful
  Drupal user                     :  Anonymous
  Default theme                   :  sporttracks
  Administration theme            :  seven
  PHP configuration               :  /private/etc/php.ini
  Drush version                   :  5.8
  Drush configuration             :
  Drush alias files               :  /my/home/dir/.drush/aliases.drushrc.php
  Drupal root                     :  /my/drupal/root
  Site path                       :  sites/default
  File directory path             :  sites/default/files
  Temporary file directory path   :  /tmp

So the question is: why is the alias not being read?

This is not supported by Drush, as explained in this issue: https://drupal.org/node/1335626

In brief, the database information stored in an alias file is only used for Drush commands such as sql-sync, sql-cli and so on; a Drush alias will never affect the way that Drupal is bootstrapped.  Therefore, Drush core-status will always show you the database info from settings.php, which is where Drupal reads it from.

If you want to force a different database configuration for a given alias, it would be best to use Drupal's multisite feature, and make another settings.php in a sites/test folder.  Then, just specify 'test' as the uri for your alternate alias.  Should work like a charm.  I always prefer to give my local test installations a completely separate copy of the Drupal + contrib code base too, though, in case I want to fiddle with the code on test without interfering with my other local copy's behavior.  Using the multisite feature is fine if this is not a concern for you, though.


Does a template override require a subtheme? Feels like a silly question to ask, but I can't find a definitive answer anywhere.

Background

My project is a multi-site that features several themes that our users can choose from. These are all installed in /sites/all/themes. For one site in particular, I wanted to simply use a different page.tpl.php file. I tried copying the theme's page.tpl.php file into /sites/my_site/themes, but this didn't seem to work. This leads me to the question:

In order to override a template, must I use a sub-theme?

The correct answer is no since you can also override templates in a module (example). It doesn't sound like you want to do that, though.

At minimum you would have to create an *.info file that includes the dependency:

name = My Theme
description = Just a basic theme
core = 7.x
base theme = base_theme_name


How to convert an url in a link? I have some strings that can contain urls inside, and I need to convert this urls into links.

For example if a have this string:

Read for more information www.drupal.stackexchange.com/q/246298/28275

I need to obtain this string:

Read for more information www.drupal.stackexchange.com/q/246298/28275

How can I do this?

To achieve this in Drupal 8 we have in the Core the filter_url filter that convert URLs into links.

So we just need to apply the filter to our string.

use Drupal\filter\FilterPluginCollection;

// The text processing filters service.
$manager = \Drupal::service('plugin.manager.filter');
// Getting filter plugin collection.
$filter_collection = new FilterPluginCollection($manager, []);
// Getting the filter_url plugin.
$filter = $filter_collection->get('filter_url');
// Setting the filter_url plugin configuration.
$filter->setConfiguration([
  'settings' => [
     'filter_url_length' => 496,
   ]
]);
// The string.
$input = 'Read for more information www.drupal.stackexchange.com/q/246298/28275';
// Applying the filter.
$result = _filter_url($input, $filter);

// To use dpm() you need the devel module.
dpm($result);

For Drupal 7 is more simple

// Creating the filter.
$filter = new stdClass();
// Adding the filter settings.
$filter->settings = array(
  'filter_url_length' => 496,
);
// The string.
$input = 'Read for more information www.drupal.stackexchange.com/q/246298/28275';
// Applying the filter.
$result = _filter_url($input, $filter);

// To use dpm() you need the devel module.
dpm($result);

Output in both examples:

Read for more information www.drupal.stackexchange.com/q/246298/28275


Get an item in a list of taxonomy Hello Drupal Community,
I am creating a menu which has a link to an "editorial". I created a taxonomy named "edito" and created articles (content type) that are tagged with this taxonomy.
I need to recover the last article tagged with this taxonomy in the menu as a link (see image attached). Does anyone have an idea of how to achieve this ?
Thanks,

You should not try to hard-code the URL to the item in the menu item edit screen.

You should add a View to your Menu.

Views allows you create a view including a filter to show only recent content.

You can then add a filter for a specific Content Type, User or whatever. And you can limit the View to show only N items.

You can insert the View of new items into your menu with the help of 3rd party modules, an example is Menu Attach Block, see the project page for a list of similar helper modules.


Is it correct to use taxonomy_term_is_page() in this code? I am trying to get some content to show up when some conditions are verified: if I am on a certain page, the content will be shown; differently, the content is blank.
Everything looks correct; I just don't know if I am not using the correct function or something else is wrong.

<?php if (!taxonomy_term_is_page('18')): ?>

blah 1 News

<?php elseif (!taxonomy_term_is_page('28')): ?>

blah 2 News

<?php elseif (!taxonomy_term_is_page('29')): ?>

blah 3 News

<?php elseif (!taxonomy_term_is_page('30')): ?>

blah 4 News

<?php elseif (!taxonomy_term_is_page('81')): ?>

blah 5 News

<?php endif; ?>

This displays the results; however, when I am on one of the other terms the output doesn't change: it stays the same as the output for the taxonomy term with ID equal to 18.

My description for what I was trying to achieve has been changed; I am not trying to get anything shown based on any conditions. To put it in better words, I am trying to have the content shown; if I am on taxonomy/term/18, the content would show the else nothing would shown if I am on taxonomy/term/28 content shows and so on. It's simular to is_front_page function and you have content shown if you are on the front page, except these are taxonomy terms.

Basing on the documentation of taxonomy_term_is_page(),  the function just checks if the current page is the page of the passed-in term. Looking at the code, the function verifies the path of the current page is "taxonomy/term/%term-id", and "%term-id" is the term ID of the taxonomy term passed as argument.

function taxonomy_term_is_page($term) {
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

You are passing to the function the wrong parameters; you should pass it a taxonomy term object.
The code you reported is calling the function as taxonomy_term_is_page('28').

If you know the term ID for the taxonomy term, then you can use the following code:

<?php
  $page_term = menu_get_object('taxonomy_term', 2);
?>
<?php if (!empty($page_term)): ?>
  <?php if ($page_term->tid != 18): ?>

blah 1 News

  <?php elseif ($page_term->tid != 28): ?>

blah 2 News

  <?php elseif ($page_term->tid != 29)): ?>

blah 3 News

  <?php elseif ($page_term->tid != 30): ?>

blah 4 News

  <?php elseif ($page_term->tid != 81): ?>

blah 5 News

  <?php endif; ?>
<?php endif; ?>


Is it important to use base table in query? Is it important to use base table for entity in query? For example if I want to get all user's id of specific role, should I do:

  $query = db_select('users', 'u');
  $query->distinct();
  $query->fields('u', array('uid'));
  $query->innerJoin('users_roles', 'r', 'u.uid = r.uid');
  $query->condition('r.rid', 3);

or

  $query = db_select('users_roles', 'r');
  $query->fields('r', array('uid'));
  $query->condition('r.rid', 3);

No, it's not important, nor necessary.

There's no API method for getting this information, so going directly into the database is fair game. Once you're going directly into the database, you only need to include the tables and fields that your data requires - anything else is a waste of resources.

In this case, you don't need to select or filter anything from the users table, so there's no need to join it in (unless you're worried about referential integrity, and want to make sure the user record actually exists).


debug_backtrace and _drupal_error_handler_real with very high mem usage, can I disable? I was profiling some of my code with xhprof, and I noticed that debug_backtrace() and _drupal_error_handler_real() have a very high memory usage.

I set "Error message display" to "None" at admin/config/development/logging, and I also have database logging module disabled. Still, these functions seem to collect error information. Do you have any idea why it happens?

My code does generate some PHP warnings. If I fix them, would these error calls disappear?

_drupal_error_handler_real() is the function called from the error handler installed from Drupal (_drupal_error_handler()). A PHP error handler is called every time there is a not-handled runtime error (not an exception), including a warning.

The code execute from _drupal_error_handler_real() is the following one. debug_backtrace() is always called, if the error level is one set in PHP.

  if ($error_level & error_reporting()) {
    $types = drupal_error_levels();
    list($severity_msg, $severity_level) = $types[$error_level];
    $caller = _drupal_get_last_caller(debug_backtrace());

    if (!function_exists('filter_xss_admin')) {
      require_once DRUPAL_ROOT . '/includes/common.inc';
    }

    // We treat recoverable errors as fatal.
    _drupal_log_error(array(
      '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
      // The standard PHP error handler considers that the error messages
      // are HTML. We mimick this behavior here.
      '!message' => filter_xss_admin($message),
      '%function' => $caller['function'],
      '%file' => $caller['file'],
      '%line' => $caller['line'],
      'severity_level' => $severity_level,
    ), $error_level == E_RECOVERABLE_ERROR);
  }

Also _drupal_log_error() is called when debug_backtrace() is called, but without any module recording the error, the error is not effectively recorded. In fact, the error is recorded if there are modules implementing hook_watchdog(), such as the Database logging module, and the Syslog module. The task of watchdog(), the function called by _drupal_log_error() is pass the information about the error to the implementations of hook_watchdog() which are then free to record the error.

// Prepare the fields to be logged
$log_entry = array(
  'type' => $type,
  'message' => $message,
  'variables' => $variables,
  'severity' => $severity,
  'link' => $link,
  'user' => $user,
  'uid' => $user_uid,
  'request_uri' => $base_root . request_uri(),
  'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
  'ip' => ip_address(),
  // Request time isn't accurate for long processes, use time() instead.
  'timestamp' => time(),
);

// Call the logging hooks to log/process the message
foreach (module_implements('watchdog') as $module) {
  module_invoke($module, 'watchdog', $log_entry);
}


How to theme a blocktitle of a view? As i am still developing some basic php skills:

I want to theme the title of my views-block slightly (just color and fontweight)

I have created a views-view--my-view--block-1.tpl.php and pasted the code of the 'display output' under the theme information of my view.

However i am stuck here as i cant seem to find anything that looks like a block title variable.

I have looked in my block.tpl.php but dont know what code to use here.

Help appreciated,

Have a look on the original template on modules/block:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

As you might see in line 4 there is a

<?php if ($block->subject): ?>
<h2<?php print $title_attributes; ?>><?php print $block->subject ?>

<?php if ($block->subject): ?>

Use this... but do not forget to use

<?php print render($title_prefix); ?>

before the title and

<?php if ($block->subject): ?>

after the title - these variables enable contextual links.

Additionally assure that you follow the template naming conventions. I think it should be views--view--my-view--block-1.tpl.php (but I am not sure - did you alreay find out if your template file is used? To do this just add any text into the file to see changes in the browser).

When you just added a new template file remember to rebuild theme registry. Either by deleting all Drupal caches or by visiting admin/appearance. If you use Devel module in conjunction with Admin menu you find a possibility to rebuild the theme registry under the projects favicon on the left of the Admin menu.


Node ID is not appearing I am working on creating a view based on nid in Drupal 8.  I cannot find node id or nid listed - I see Entity id. I am trying to set up a contextual filter so only certain node fields (node type B) will show up when node type B's relationship field matches the node alias of node type A.
(I am looking at https://www.drupal.org/node/1841004, but the terminology is different for Drupal 8.)

Turns out nid in Drupal 8 is now listed as ID - and it is listed liked this:
Title - ID and Category - content.  It appears on the view as Content: ID. I put this in Fields and made it hidden.  I added a relationship to my other content type.  Then for contextual filter I used the Content:ID with the relationship. Under When filter is not available, I picked Provide default value: Content ID from URL. And then the view worked.


File Transfer failed, reason: Unable to change to directory I'm work on updates modules in my drupal site. When i access localhost/authorize.php after linked in config, i recieve this:

Update failed! See the log below for more information. Your site is still in maintenance mode.

the log is...

views

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/views

views_bulk_operations

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/views_bulk_operations

webform

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/webform

jquery_update

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/jquery_update

simplenews

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/simplenews

entityreference

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/entityreference

ctools

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/sites/all/modules/ctools

entity

    Error installing / updating
    File Transfer failed, reason: Unable to change to directory /drupal/sites/all/modules/entity

I have tried to fix permissions in folder using:
sudo chmod a+w and
sudo chown root sites/default and chmod 777 , every using folder sites/default and sites/all/modules, but i canot successfuly updates my modules using ftp and automatic.... how i fix this? thanks in advance

Try executing your chown command recursively, and also assign an explicit user and your web server's group, like so: sudo chown my_user:www-data sites/all/* -R where my_user is your id and www-data is your web server's group. This will recursively apply ownership to your entire directory tree.

It might also be worth pointing out that you mention assigning ownership and privileges to sites/default, but your error messages indicate that the problem is in sites/all. :-)

In my experience, failed uploads or updates are almost always due to incorrect ownership.


Delete block settings when removing a block from hook_block_info() My module creates blocks. These may come and go and I want to make sure I'm not leaving cruft behind, e.g. settings from the configure block screen for blocks that no longer exist (i.e. are no longer returned by my hook_block_info()).

I've noticed that removing a block and then adding a new one (with the same delta) magically brings up the old config.

What should I do in my module to clean out this config? (or is it somehow done for me in an occasional cron?)

I hope this should work if I get your question right.

db_delete('block')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();
db_delete('block_node_type')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();
db_delete('block_role')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();

cache_clear_all(MODULE_DELTA, 'cache_block');

Where MODULE resembles your module name and DELTA resembles your block's delta.


Which Drupal log file is available to proof when exactly some content was deleted and by whom? Somebody claimed that content has disappeared from their site. Of course like magically. No one has deleted it, they said.

How can I find out if content was deleted and by whom? Do I have to set up rules to notify me? Or is there a log that I'm overlooking? I already looked into admin/reports/dblog without success.

Check out their http://example.com/admin/reports/dblog. You should have messages like this one:

Type        content
Date        Wednesday, June 5, 2013 - 09:11
User        admin
Location    http://localhost/node/1/delete
Referrer    http://localhost/node/1/delete
Message     page: deleted test.

For future, you can use hook_watchdog()

  This hook allows modules to route log events to custom destinations, such as SMS, Email, pager, syslog, ...etc.


How do I import a module? I am working on Drupal 8 and I have migrated my Drupal 7 website to Drupal 8 using the Migrate Upgrade module, but none of the modules is imported from my previous Drupal 7 site.

How do I import modules from Drupal 7 to Drupal 8 without using Drush commands?  I'm not much familiar with Drush.

I have seen the article in which a process is given to import modules using  Drupal Module Upgrader, but it's based on Drush.

Is there any simple method to port Drupal 7 modules to Drupal 8?

Perhaps, your question in bold needs to be reworded to Is there any simple method to port D7 modules to D8? Which is what you're really after.

If you are referring to CUSTOM modules (not drupal.org contrib  modules) then the fastest / most simple way is to use Drupal Module Upgrader which you mentioned in your question. In module page they show you a video with all the steps.

There is no reason to be afraid of Drush. As a Drupal newbie, Drush can seem scary/daunting, I used to avoid it too, but once you learn Drush, which is not hard, you will discover that is super useful and a time saver. You will wish you learned it earlier.

It is important to note that while the Drupal Module Upgrader will port/rewrite some of the code, some of the code may not (depends on how complex your module is) and you will have to manually modify/rewrite certain parts by hand.

Other than using Drupal Module Upgrader, there is no other choice, but to manually re-write your entire module.

If you are referring to Drupal.org Contrib Modules then you will need to download the D8 version, if there is one.


Rate Widget Search API integration I have a view for search results.

I want to add the "rating" widget, but I cant find a way how to include it in the Search API fields. => The views cant make the relationship.
Is it possible ?

Clarification:
The view is not the "ordinary" type -> displaying contents, but it is displaying "Search index".
I am able to display fields that are defined by the Search API settings page, but I am unable to add relationships, for example Rate Widget (Vote Results module).

As a solution, I embedded another view as a field. That seems to work, but I am asking if there is another approach out there.

The answer is: you cannot do it in other way, because the view entity is search_api type.


How to show a menu for everybody but one role? I'd like to add, in a custom module, a hook menu that adds a menu only if

the user is logged in
the user has the role "immat"

I'm trying to use the hook_menu() hook but it's never called when the page displays the "Navigation" menu.
Where should I look / which hook should I use?

Thank you very much!

hook_menu is not called on every page load, because that make Drupal really slow. It is only called when the menu is being (re)built, and the resulting menu structure is cached.

In hook_menu, you can tell Drupal how to determine which users have access. Access is not granted by role, but by permission. That way, you can easily grant the same permission to other roles when needed.

You will need to:

Define a new permission using hook_permission
Add the new permission to the role you want to give access
Restrict your menu item to users with that permission by adding 'access arguments' => array('[name of your permission]'), to your menu item

For an example, see the menu_example module at api.drupal.org. More specifically, see how menu_example_permission defines a new permission and how menu_example_menu specifies that permission as access arguments for the $items['menu_example/permissioned/controlled'] item.


Views API custom table not showing fields I'm creating a custom view that corresponds to my module's table.

I already called the hook_views_api() hook.

function sample_views_api() {
    return [
        'api' => 3,
        'path' => drupal_get_path('module', 'sample')
    ];
}

To generate the view I called the hook_views_default_views() hook.

function sample_views_default_views() {
    $view = new view;
    $view->name = 'sample';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'sample_table';
    $view->human_name = 'Sample';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = false;

    $handler = $view->new_display('page', 'Page', 'page');
    $handler->display->display_options['path'] = 'sample';
    $handler->display->display_options['menu']['type'] = 'normal';
    $handler->display->display_options['menu']['title'] = 'Sample';
    $handler->display->display_options['menu']['weight'] = '0';

    $views['sample'] = $view;

    return $views;
}

But when I opened my generated views. The fields of the corresponding table does not show.

Any way to show the fields? Am I missing something to register the fields?

In order for Views to work with custom tables, you need to tell Views about your data structure with hook_views_data. The writeup and comments on that page will help you define the guts of the implementation. You basically have to tell views about the table, any relationships (and how), and describe each field in your table and what handler/filter etc it can have.

Aside from that, Data can help wire this automatically, but note that this will require re-defining your table/schema using the Data API.


How do I get when an entity was last updated? I found from the documentation that to get the created date I can use the    getCreatedTime() method.

How do I get when an entity was last updated?

If the entity uses the EntityChangedTrait (Drupal\Core\Entity\EntityChangedTrait), then you can use getChangedTime().


Duplicate nodes returned from a module's SQL query I'm in a spot of bother customizing the calendar block module for my needs. I've written a custom module that queries my database for published nodes that possess a specific taxonomy term. This works as desired; 3 node objects are returned as an array. However, this array is returned a total of 35 times. When I execute the query in my SQL manager the 3 rows are returned without repetition. Is there anything blatantly amiss in my code I haven't been able to spot?

/*
*
* Implementation of hook_calendar_block
*
*/

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {

   case 'alter':
                $sql = "SELECT DISTINCT node.nid AS nid
                                FROM {node}
                                INNER JOIN term_node term_node ON node.vid = term_node.vid
                                WHERE (node.status <> 0) AND (term_node.tid = 5)";

                $results = db_query($sql);

        while ($node = db_fetch_object($results))
        {
          $events[] = node_load(array('nid' => $node->nid));
        }

        foreach ($events as $var){
                $thisPath = $var->path;
                                $nodeTitle = $var->title;
                $thisDate = substr($var->field_event_date[0]['value'],0,10);
                                $realDay = substr($thisDate, 8,2);
                $realDate = substr($thisDate, 5, 2) . "-" . ( $realDay < 10 ? substr($realDay, 1,1) : $realDay ) ."-". substr($thisDate, 0, 4);

                                //$dayInfo[] = array ('date' => $realDate, 'title' => $nodeTitle,  'path' => $thisPath );

                                if ($date->date == $realDate) {

                                    $date->content = ''. l($date->day, $thisPath) .'';
                                    $date->content .= '
'. l($nodeTitle, $thisPath) .'
';

                                }
                            }
          break;

        case 'load':

        // Change the weekday's format and set the first day of the week to sunday.
        $calendar->weekdays =  array(
            'su' => 'S',
            'mo' => 'M',
            'tu' => 'T',
            'we' => 'W',
            'th' => 'T',
            'fr' => 'F',
            'sa' => 'S',
        );

        break;
  }

}

Edited to include all the code from my module - If anything I hope this can give others a similar starting point. if the code looks like a mess it's because it's my first module.

The code works: nodes with the desired taxonomy term are pulled from the database and each date on the calendar becomes a link to its corresponding node. However on closer inspection the 3 rows are returned 35 times, so doing anything beyond this (e.g. a choice of nodes if there are multiple ones on a single date) becomes a challenge / impossible.

I just took a quick look at the calendar_block module. From what I can tell, hook_calendar_block op alter is called for every single day in the calendar. I guess this makes sense at it allows you to alter the appearance of any day.

My guess is that the calendar on your site has 35 days in it which is why your query is run 35 times.

You could make use of a static variable to only do your stuff once or save the query etc.

Something like this could work:

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $events;
      if (empty($events)) {
        $sql = "SELECT DISTINCT node.nid AS nid
              FROM {node}
              INNER JOIN term_node term_node ON node.vid = term_node.vid
              WHERE (node.status <> 0) AND (term_node.tid = 5)";

        $results = db_query($sql);

        while ($node = db_fetch_object($results)) {
          $events[] = node_load(array('nid' => $node->nid));
        }
      }
      ....
  }
}

The above code doesn't catch the case where there is no result and is just meant as a proof of concept.

Update:
If you only want to run the entire code once, you could do something like this:

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $code_executed;
      if (!$code_executed) {
        ...
        $code_executed = TRUE;
      }
  }
}


Configuration successful but never gets imported I have some changes in core.entity_form_display.node.news.default.  When I run drush cim -y it says it is successful but it actually never imports it.

drush cim -y
Collection  Config                                      Operation
             core.entity_form_display.node.news.default  update
Import the listed configuration changes? (y/n): y
The configuration was imported successfully.            [success]

The changes are removing field groups from the form display.

If I try to import via UI it also says it is successful but it never gets imported.  I don't get any errors in my error log.

I tried to make some other configuration changes like changing the site name and it works. It seems to be an issue with Field Group or at least when deleting a field from from a form display.

Sounds like a known core bug: https://drupal.org/node/2666392


Create an order for a specific customer I'm new to commerce, but I can't find a way to generate an order for a already existing customer via Admin Panel. Do I have to code that by myself or am I missing something?

I've tried to use Commerce Admin Advanced Order Module but this only seems to work with drupal users, not commerce customers.

The simplest way to do this would be to create the order that you want until the step that you want with your admin/webmaster/whatever role that has enough permissions and then, edit the order and change the owner.

If you create an order so the customer can pay it, you just send them the checkout url, as you changed the owner, they will have access to finish the checkout.

If you process the payment as well, you need an extra step of configuration, in order to send the customer a proper notification that the order was made. Rules is a good way to do this.


How do I do a 'required if other field = x' using the entity validation api? I have a field in a content entity that is required if another field in it is checked, otherwise it can be blank.

My guess is that I'd need to make some kind of Validation Constraint Plugin for this - is there an easier way to do this, or a module where something like this already exists?

That sounds like a job for Drupal's Form API states.

Just add a hook_form_alter similar to this, in a custom module:

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'FORM_ID_TO_ALTER') {
    $form['OPTIONALLY_REQUIRED_FIELD']['#states'] = array(
      'visible' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
      'required' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
    );
  }
}


Given a field for Content Profile for a user, how can I extract that field via code? I have a location field for a user that is created via the Content Profile module.

How can I access that field in code for the logged in user? Is it something like $user->content_profile['location']

I can't seem to grab this info.

You'll have to load the content profile node into a variable first using content_profile_load.

This should work:

$user_profile = content_profile_load('profile', $user->uid);

That will return an object ($user_profile) that you can call the fields which you've set up.
Use

echo '<pre>'.print_r($user_profile,1).'</pre>';

to see which fields are available.


Drupal 7 Update Module Not Working I just upgraded to Drupal 7 from Drupal 6. It appears I've finally gotten everything working, except the module updater isn't working; it can't update from a URL or a file. I also cannot install new modules.

I check the box next to the module to update and it appears that it's working, or downloading; it works for a few seconds, then it just reloads the updater page and nothing has changed. It is the same when I install a new module, entering the URL for the module, or choosing the file from my computer. Again, it appears to be working, but it just reloads the module install page.

This sounds like a folder permissions problem.
Check to see that the user account that your web server is using to server web pages has write permissions in the 'sites/all/modules' folder.   Your webhost can help you with this.


Set default registration type for content type I created a registration type for a certain content type using the registrations module (https://drupal.org/project/registration).
But the user can select or disable a registration type.

Can you force this registration on a certain content type?

Since Registrations are fields make it a required field.

And then from the default values select the type of registration you want to force for a content type.


How do I get navigation menu on top with narrow viewport? I'm running Drupal 7.28 with Zen 7.x-5.5.  In the default setup, there is a region on the right side named "First sidebar" which contains a block named "Navigation".  I have put my navigation links there.  When shrinking the width of the browser to see how my site will be rendered on a mobile the navigation block gets positioned at the bottom of the page.

I want the navigation to be at the top in a mobile scenario, ideally with a bootstrap-esque collapsed menu.  How can I achieve this?

@media width queries in CSS
http://css-tricks.com/css-media-queries/
At a certain width, you could use a different positioning tactic, forcing it up top.
Via Javascript, checking against: window.innerWidth or body .clientWidth
Many things you could do here, from changing CSS rules, to actually moving it in the DOM.
Using a Drupal module for responsive menus like:
https://www.drupal.org/project/responsive_navigation
or https://www.drupal.org/project/responsive_menus


How to call view block on click? I have a page/node that contains 15 view blocks, each view block has many fields and all of this causes the page to load really slow.

How do I load the view block only when I need it? for example I would click a button/div (venue) then the view block venue will load instead of invoking all of the view blocks on the template and letting it load all at once.

UPDATE:
I tried using ajax but it's not working even though I turned the ajax on the view block.

This the code I used:

JS:

$(document).ready(function(){
$("#getvenue").click(function(){
    $.ajax(
    Drupal.settings.basePath + 'views/ajax',
    {

    view_name: 'custom_package_form',view_display_id: 'block_56'
    },

    function(response)
    {
        if (response[1] !== undefined)
        {
            var viewHtml = response[1].data;
            $("#output-venue").html(viewHtml);

            Drupal.attachBehaviors();
        }
        else {
            $("#output-venue").html("NONE");
        }

    });
    });
 });

Node Venue TPL:

<button id="getvenue"> GET VENUE </button>

Nothing happens, I tried alerting the var viewHtml to see if it has something, the alert only shows null.

What's wrong with the JS? Can someone point me to the right direction?

Thank you in advance!

Try this code

$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'POST',
    dataType: 'json',
    data: 'view_name=custom_package_form&view_display_id=block_56',
    success: function(response) {
      var output = response[1].data;
      $("#output-venue").html(output);
    },
    error: function(data) {
        alert('An error occured!');
    }
});


How can I configure the User Protect module to avoid editing/deleting users with "edit users" permissions? I am working in Drupal 6. I have created a role "admin users" with permissions for edit and delete users but I need that this role "admin users" cannot edit/delete the user admin. I have installed the User Protect module but I cannot to configure it correctly for the role "admin users" can not modify it.

I had to do it one day and I did like that. But in my case the permission is edit user 1. The code simply remove the user from the list. Feel free to change as you want.

<?php
function mymodule_menu_alter(&$items) {
  $items['admin/user/permissions']['access callback'] = 'mymodule_user_access';
}

function mymodule_user_access($string, $account = NULL, $reset = FALSE) {
  if ($string == 'administer permissions' && user_access('edit user 1')) {
    return TRUE;
  } else {
    return FALSE;
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_user_profile_form_validate';
}

function mymodule_user_profile_form_validate(&$form, &$form_state) {
  $account = $form_state['values']['_account'];
  if(!user_access('edit user 1') && $account->uid == 1) {
    form_set_error('category', t('You does not have right to edit this user.'));
  }
}

function mymodule_perm() {
  return array(
    'edit user 1',
  );
}

function mymodule_theme() {
  return array(
    'mymodule_user_admin_account' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

function mymodule_theme_registry_alter(&$theme_registry) {
  unset($theme_registry['user_admin_account']['file']);
  $theme_registry['user_admin_account']['function'] = 'theme_mymodule_user_admin_account';
  $theme_registry['user_admin_account']['include files'] = array();
  $theme_registry['user_admin_account']['theme path'] = drupal_get_path('module', 'mymodule');
  $theme_registry['user_admin_account']['theme paths'][] = drupal_get_path('module', 'mymodule');
}

function theme_mymodule_user_admin_account($form) {
  // Overview table:
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $output = drupal_render($form['options']);
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      if(!user_access('edit user 1') && $key == 1) {
        unset($form['accounts'][$key]);
        unset($form['name'][$key]);
        unset($form['status'][$key]);
        unset($form['roles'][$key]);
        unset($form['member_for'][$key]);
        unset($form['last_access'][$key]);
        unset($form['operations'][$key]);
      }

      $rows[] = array(
        drupal_render($form['accounts'][$key]),
        drupal_render($form['name'][$key]),
        drupal_render($form['status'][$key]),
        drupal_render($form['roles'][$key]),
        drupal_render($form['member_for'][$key]),
        drupal_render($form['last_access'][$key]),
        drupal_render($form['operations'][$key]),
      );
    }
  }
  else {
    $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}


How to import (stream) data in Drupal and save the visualization as nodes - similar to datamasher.org)? I am working on a data visualization Drupal website. I am looking for a functionality close to datamasher.org, a site that was built using Drupal.

But I cannot find a way that would allow me to create the same functionality.

My Question: How to import data/stream data in a Drupal site and save the visualization as nodes?

Nodes arent the best for storing data as such. I would suggest the data module for storing the datasets. (support for import via feeds is underway)
To display some results and charts there is several ways - have a look at forena for example. You could then create a node type that would save the parameter values for forena reports and upon node node display show the report. Similar functionality can be achevied vith views (not so much fomratting though).


Without access on a taxonomy term page I have created a taxonomy term "tags". If I use the url to access the content with that term I have the following error.

403 Forbidden
You don't have permission to access /drupal/tag/sport on this server.

"sport" is a taxonomy term and tag is the taxonomy.

Even if I am admin or anonymous user.

around the top of your .htaccess file you have

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(|~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

just remove 'Tag', new code should look like this

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(|~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

you can replace this lines with new one that I provided above...


Combining several attributes with string join My XML is structured like this:

<Export>
  <ProductType Type="Book">
    <Products>
      <Product Title="The Pragmatic Programmer">
        <Chapters>
          <Chapter Title="1 A Pragmatic Philosophy">
          <Chapter Title="2 A Pragmatic Approach">
          <Chapter Title="3 The Basic Tools">
          ...
        </Chapters>
      </Product>
    </Products>
  </ProductType>
</Export>

I am trying to map an XPath Expression to a multivalue field that contains a list of all the chapters.

I think the context expression is causing the xpath function for the mapped field to return an empty value.

I've tried the following and both do not work:

Context:
/Export/ProductType[@Type='Book']/Products/Product

Target Field:
fn:string-join(Chapters/Chapter/@Title, ', ')

This just outputs a comma.  Is there a way to combine all of the Chapter titles into one string like "1 A Pragmatic Philosophy, 2 A Pragmatic Approach, 3 The Basic Tools"?

UPDATE

I'm not sure that you can use expressions in string functions, but this stackoverflow post lead me to believe that it is possible.

The Feeds Tamper module has an implode plugin that makes this work.

  Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below. Additional plugins can be added in separate modules or through the issue queue.

  Replace every instance of 'dog' with 'cat'
  Filter items based on keywords or vocabularies
  Make every letter uppercase, lowercase, or capitalise every first letter
  Break a comma separated list of words into Taxonomy terms or a multivalued text field
  Combine separate 'first name' and 'last name' fields into one 'name' field
  Convert urls from relative to absolute


Bootstrap 3 sub theme - missing header for banner? I am new with Drupal Bootstrap 3 sub theming, and I checked the view source and noticed:

<div class="main-container container">

  <header role="banner" id="page-header">

      </header> <!-- /#page-header -->

I wanted to move header outside main-container - how or where can I edit that?

thanks

I think you are using the Bootstrap 3 subtheme and in that case you have to modify the corresponding templates. So to do that create a new directory "templates" in your subtheme directory and then there you have to place a page.tpl.php then edit as per your needs.

For further reference you can follow, Theming Guide & Bootstrap sub-theming "how to"


Change article layout on homepage I would like to change the layout of articles on my homepage.
But I cannot find the template hereof.
I've got my page.html.twig, which but that only includes a placeholder "{{ page.content }}" in which all the articles are loaded.
And then I've got node--article--full.html.twig, but the layout there only seems to affect the article pages.
So where can I find the template to adapt the articles and their layout as shown on the homepage?
Do I have to create something like page--node--article.html.twig to overwrite the design of something?

The list of nodes listed in the homepage by default is from the Frontpage(/admin/structure/views/view/frontpage) view. If you'll go to that view, you'll notice on the FORMAT section, under Show, the value is "Content | Teaser". This means that the each node displayed is using a specific View Mode called "Teaser".
Next is to enable twig debugging.  Once that's done and you check the homepage's markup, specifically on one of the article listings, you'll see this:

Notice that I'm highlighting one "article teaser" and on the markup you'll see a list of file names i.e. node.html.twig, node--teaser.html.twig and etc. and the one with the "x" is the default template that is being used.If none of the other files are found then Drupal always goes to the base template which in this case is node.html.twig. So if Drupal matches a theme suggestion in the list to a physical file on your theme, that's what it will use.
With those information, you can go to the current template file using the file path(core/themes/bartik/template/node.html.twig), copy it into your custom theme, rename it as node--teaser.html.twig, do some random edits for initial testing, clear the cache and then visit the homepage again.
You should see that the "x" under "FILE NAME SUGGESTIONS" will now be beside node--teaser.html.twig and your changes to the file as well.


How to fix a field with unlimited values where the "Add another item" is broken? I am working on Drupal 7.43.

I have created a few months ago standard fields (text) with unlimited values. Everything was fine.

Today, I can not add another item, the Javascript icon is turning and then nothing happens. Surprisingly, it works on a local version. The weirdest thing is when I use a fresh field, created for test, everything works fine and I can have multiple values added.

In recent log messages, I have an AJAX warning : Invalid form POST data. (EDIT : this warning message is not displayed each time I try to add another item.)

I have tried many different things (jQuery Update configuration, new theme, deactivation/reactivation of modules, cache flushing...).

Does anyone know if I could fix my "broken fields" so I can still use them instead of creating new ones and cloning all the values already entered?
Thanks in advance.

A similar issue here

EDIT (05/09/16) :

Looking at the Firebug Console, in JSON tab, I have just noticed that 2 lines are missing, compared to my localhost version, where the function works fine. The lines missing :

Object {command="add_css"...}
Object {command="insert", method="prepend", selector="head"...}.

Seems important? Any way to get these lines on the production website?

After many different tests, I have found the solution.

All the multi-value core fields using the module "Better Field Descriptions" were broken.

The help text added below by this module seemed to block the new option line to be created or at least displayed. Deactivate the module fixed the problem.

So, if you need a multiple values field and a permission to edit the help texts, be cautious with module interactions.

Thanks for those who tried to help me on this issue.


Drupal Translation Doesn't work I am trying to translate articles/nodes on my site. I installed all required modules.

I have a custom node type.

This custom node type has some fields that are translatable and not translatable.

I checked this checkbox

I created custom view for the front page that contains nodes of custom type.
But when I switch the language translation doesn't work.

Menu translation works. But the view nodes are not translated.

The interesting thing that if I visit my node by a full url path like this

http://test.net/node/1

Translation works fine.

I am outputting node properties in my template in the following way

          {{ node.title.value }}
   {{ node.field_description.value|raw }}
    {{ node.field_custom_body.value|raw }}

What can be wrong ?

EDIT

I have no option Content language selected for page

My view looks like this now

P.S I am using language switcher block to change language and it sets the session variable

You have to configure a filter for the language in the the view:

FILTER CRITERIA

"Content: Translation language (= Content language selected for page)"

Btw. you have a big security problem in the node template, it is not allowed to apply the raw filter on a field that contains user input. You should use

{{ content.field_custom_body }}

instead to print the field.


how to remember results of a views query in rules I have a site with an eva view that is embedded into a view page that is directly accessible, running the query for the first time. To that I have added rules_views, I want to e-mail out certain fields values of the view when the user requests it using a flag. (as the trigger) But I want to e-mail the field values out after the query is first run, with the original values. I want to preserve the state.

What is the best way to do this?

As a possible alternative to make this work (instead of using Views Rules), you may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

To actually trigger such Rules Action, you should be able to use a Rules Event like "... when the user requests it using a flag." (as in your question).


Config entity form field with multiple/unlimited cardinality I have a config entity form that has a taxonomy field, and it currently works with 1 term

$form['integration'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => 'Integration',
  '#required' => TRUE,
  '#target_type' => 'taxonomy_term',
  '#default_value' => $entity->getIntegration(),
  '#selection_settings' => array(
    'target_bundles' => array(
      'integration',
    ),
  ),
);

That works fine, but I need to be able to select multiple terms, I've tried setting '#cardinality' => -1, but it's only allowing 1 element. I added a taxonomy field with unlimited cardinality to a content type, then set a breakpoint on the form to see how it was being set up for the page rendering. It looks like it creates a container form element, then I assume iterates over an array containing all the terms?

I would have thought there would be a way to set the cardinality of an element by making use of field widgets on the config form page, but I'm not sure that's possible.

(Content) fields have cardinality. There is no such concept for form elements.

However, entity_autcomplete does have a #tags flag, which you can see in the getInfo() method of the class: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/function/EntityAutocomplete%3A%3AgetInfo/8.

If you set that to TRUE, then it allows you to select a comma-separated list of references.

If you're looking for the "Add another" functionality of entity_autocomplete or any other form element, then you have to build it yourself.


128 character limit in Drupal text fields I maintain a small module on Drupal.org and I'm having a few problems fixing this issue:

http://drupal.org/node/917340

Is this limit of 128 characters imposed by Drupal Core? Can I do anything in my module's code to work around this limit? Or is it best to suggest that users of my module use something like http://drupal.org/project/maxlength or http://drupal.org/project/skip_validation?

Maybe my brain isn't in gear, but in your code you have '#maxlength' => 128, everywhere...  Changing that to 4096 worked here and allowed a really long message. Changing textfield to textarea and removing #size and #maxlength worked as well.


Getting pages defined by taxonomy to display in a view I have a page view that displays video thumbnails in a grid layout (three columns.) Above each thumbnail is the title of the video and below it is the category. The category is defined by taxonomy and selected by the user when he uploads his video.

The overall view (all videos regardless of their category - ex: /videos/all) displays nicely in a page view (no taxonomy term involved here.)

The display problem arises when a user selects a category. Although the items belonging to that category are properly filtered, I cannot get a view (ex: videos/movies) to display them in the same manner as the overall view (three columns.) I get instead the node teaser layout (thumbnails in one column with a "read more" link below each. A page view with the same path as the corresponding taxonomy term (ex: videos/movies) does not take control of the display.

How can I solve this and have all category views display like the videos/all page? Display Suite does not "see" the videos/movies page created by taxonomy.

Any and all help will be greatly appreciated. Thank you. :)

Hope this will help you,

In Drupal 7,  you can use Context module.

Context : It allows you to easily organize your site into manageable sections .
Create a new context using the path - videos/%category and arrange the items like Overall View.

Note : Context


Show a popup after saving a new node How do I create a popup which can use the node variables after saving a new node?
For example, I want to show a popup with the social media share button. Should I use node_save()?

When a node is saved, the user is normally redirected to the page showing the node, which is not a form. In that case, hook_form_alter() doesn't help. I said the user is normally redirected to the page showing the node, as that is what Drupal does, but there could be a module that redirects the user to a different page, such as the one showing the node edit form to add a new node.

To show the popup when the node is viewed, you can use hook_node_view(), which can be used to add HTML tags to the node view page.

The example shown in the documentations shows how to add markup to the node view page.

function mymodule_node_view($node, $view_mode, $langcode) {
  $additional_markup = 'Markup to add to the page';

  $node->content['my_additional_markup'] = array(
    '#markup' => $additional_markup,
    '#weight' => 10,
  );
}

As for showing the popup right after the node has been saved, you could implement hook_form_alter() to add a form submission handler to the "Save" button; that submission handler would add a session variable that is the checked from your implementation of hook_node_view(). Its code should then be similar to the following one.

function mymodule_node_view($node, $view_mode, $langcode) {
  if (isset($_SESSION['nid']) && isset($_SESSION['timestamp']) && $_SESSION['nid'] == $node->nid && mymodule_check_timestamp($_SESSION['timestamp'])) {
    $additional_markup = 'Markup to add to the page';

    $node->content['my_additional_markup'] = array(
      '#markup' => $additional_markup,
      '#weight' => 10,
    );
  }
}

The values in $_SESSION are the ones set by the form submission handler. mymodule_check_timestamp() should return TRUE when $_SESSION['timestamp'] doesn't contain a value too past in time; this would help in the case there is a module that redirect the user to a different page, and then the user visit the node page to review the node s/he saved. For example, it could return TRUE when $_SESSION['timestamp'] is a timestamp 5 seconds earlier. It is up to you to decide how much delay should be acceptable between when the node is saved, and when the node is viewed from the same user who edited it.

You can change the weight used in hook_node_view(); that changes where in the node view page your markup is added.


Is there a function to clear the watchdog log inside a module? I don't want to clear the watchdog log from the UI each time while debugging. It becomes time consuming and tedious.

Is there a Drupal function to clear the watchdog log inside a module?

The best way to do this is via drush:

$ drush help watchdog-delete
Delete watchdog messages. Arguments or options must be provided to specify which messages to delete.

Examples:
 drush watchdog-delete all                 Delete all messages.
 drush watchdog-delete 64                  Delete messages with id 64.
 drush watchdog-delete "cron run           Delete messages containing the string "cron run succesful".
 succesful"
 drush watchdog-delete --severity=notice   Delete all messages with a severity of notice.
 drush watchdog-delete --type=cron         Delete all messages of type cron.

Arguments:
 severity                                  Delete messages of a given severity level.
 type                                      Delete messages of a given type.

Aliases: wd-del, wd-delete


custom private message block generates error I created a block to generate a private message link to send a message to all the users of a group. I use the php code as the text format on the block body.

<?php
$group = og_context();
$og_id = $group->gid;

$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $og_id, "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();

$result_tmp = $result->fetchAll();
$recipients = array();

foreach($result_tmp AS $tmem)
{
$recipients[] =  user_load($tmem->etid);
}

echo 'Send message to ehood members';
?>

When I use this, It created me a notice message saying -

Notice: Trying to get property of non-object in privatemsg_user_access() (line 335 of /sites/all/modules/privatemsg/privatemsg.module).
Notice: Trying to get property of non-object in privatemsg_user_access() (line 335 of /sites/all/modules/privatemsg/privatemsg.module).

Although it generated the link, It creates the error. I think its somehow related to how $account is mentioned ?

i tried to send global $user instead of $account, but still creates the same error.

In this case, the problem is that privatemsg_get_link() uses array() as default value for $account, but then uses the following code.

  if ($account == NULL) {
    global $user;
    $account = $user;
  }

The function should use NULL as default value for $account, in the same way user_access() does.

function user_access($string, $account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  // ...
}

The error message you see is because the function tries to access $account->uid when $account is an empty array. An array doesn't have properties, and that is what the message is saying.
As the function is passing that value to user_access(), the same error would be raised from user_access(), which check the value of $account->uid, and for which an empty array is not the correct value to pass to its $account parameter, which requires an user object, or NULL.

It's fine to use the default values a function has, but you should check what the function does when it gets the default values for its parameters.

It is wrong to call a function as privatemsg_get_link($recipients, $account = array(), $subject = NULL) when you want to use the default values for its parameters. Just call the function as privatemsg_get_link($recipients). With your code, you are setting $account to an empty array, and passing $account as parameter.
PHP doesn't have named parameters, but only positional parameters. If it had named parameters, it would be possible to call a function indifferently as functioname(34, param3 = 4, param2 = 12), or functioname(34, param2 = 12, param3 = 4).


Views Slideshow Output different in IE vs Firefox/Chrome/Safari A site I'm working on is using Views and the Views Slideshow plugin to generate a tabbed panel on the site. We modified the output of the plugin to display link names instead of IDs, which worked great. The view set the link back to the node.

We modified the view itself to instead use a link that the user specifies on the node instead of linking back directly to the node itself. Cleared the cache and FF works fine. When I test in IE, it doesn't link anywhere (the anchor's href is actually empty).

I've got all the caching on Drupal turned off, deleted the cache in IE, rebooted... the module itself seems to be outputting different HTML based upon the browser. Any ideas on where to start looking? I'm digging through the module itself right now but I'm not seeing anything that stands out.

Update

What ended up happening was a module (not the one I was working on) was detecting IE and including javascript that was for IE only. This extra javascript ran before mine and mangled some of the tags I needed to work with.

When browsers create different markup, the problem is most likely an error in the HTML, where IE is particulary bad at making broken HTML work.

Try comparing the actual source code for the page to see if it is the same.

If even the source is different it's most likely an issue with a reverse proxy or similar. Some are known to cause problems with IE with certain configurations.


How to get entity Translation's title in Twig i am trying to get row title -node title- in my custom module
with  template_preprocess_modulename_view($variables) and views-modulename-view.html.twig with using

row.content['#row']._entity.title.value

but it always return node title of translation source.

how can i get correct node translation title in twig?

--

update:

i am going to clarify my problem:

i have a view which returns nodes without any condition-
example of returned output is like:

- 'title of node 1 in english'
- 'title of node 1 in french'

i want to  manipulate title in twig but
row.content['#row']._entity.title.value returns always node 1 in translation source language. -in this case english-

is it possible to get exact title of row -considering translation and language of returned row- in twig?

update 2

in template_preprocess_modulename_view($variables) i tried:

  $rows = $variables['rows'];

  foreach($rows as $index=>$value){
    if (isset($value['#row'])){
      $row=$value['#row'];
      var_dump($row->_entity->get('langcode')->value);
    }
  }

but $row->_entity->get('langcode')->value returns language of translation source of row, not language of row itself.

Normally you filter rows having all the same language, but you don't have to. So rows can have different languages.

The code in the question seems to get the entity from the wrong place. See this topic for examples of different kind of rows: How to access raw data in twig template using views table format

A normal views row is a ResultRow object having the property _entity, which then should return the translated entity:

$entity = $row->_entity;

See ResultRow::$_entity

But it doesn't. Tested it with the pre-installed view Content and I had to get the entity translation of the row language stored in node_field_data_langcode before I could get the translated title:

foreach (views_get_view_result('content') as $row) {
  $entity = $row->_entity;
  $langcode = $row->node_field_data_langcode;
  $entity = $entity->getTranslation($langcode);
  $translated_title = $entity->label();
}


How can I dynamically change the display format? I have an entityreference field. I want to change the 'Format' under 'Manage Display' from 'Rendered Entity' to 'Label' based on custom logic. Basically, what I'm doing is, if there isn't an image in a node (field_image), it will load a default image from the taxonomy term. If there is an image in the node, it will just display the label. Sorry if this has been answered, but I can't find anything on it. I've tried hook_entity_view_alter, but I don't think that's the right one.

You can do that printing directly the entityreference field in the node.tpl.php. First you need to check if the image field exists and then display the entity reference, so you can do something like this:

if(!$content['field_image']){
   //Load default image
}else{
   print 'Your custom label.';
}

You have to remember to set the format to hidden in the display section.


field_view_value() with product reference field doesn't display attributes I'm trying to render a product reference field using field_view_value() - which works except for the attribute options don't render.  If it's rendered normally on a node, or in views then the attributes display as normal. Any ideas how to fix this?

$product_obj = node_load($nid);
$product_field = field_get_items('node', $product_obj, 'field_product');
$cart = field_view_value('node', $product_obj, 'field_product', $product_field[0]);

print render($cart);

Instead of using field_get_items/field_view_value try field_view_field.

$product_display = node_load($nid);
$add_to_cart = field_view_field('node', $product_display, 'field_product');
$add_to_cart['#label_display'] = 'hidden';
$cart = drupal_render($add_to_cart);


How do I add a dropdown field in the commerce form? Does someone know how to add a dropdown field to the commerce form?

I need to add a field where people need to select one of the 3 options. Ex.: "How did you know us?" (options: Google, a friend, I don't know)

Can anyone help me?

Thanks

I think this is what you are looking for:
/admin/commerce/config/line-items/product/fields

This is where you can add fields to the product line item type.  Make sure you have the Line Item UI module enabled or you might not have access to that UI.


How to dynamically make a field visible? I'm trying to render a field based on a select value. However I couldn't succeed for now, so here is what I tried:

I created a content type with a select field (field_type)

var_dump($form['field_type']['und']['#options']);

gives

array (size=5)
  '_none' => string '- Select a value -' (length=18)
  'externe' => string 'externe' (length=7)
  'interne' => string 'interne' (length=7)
  'carroussel' => string 'carroussel' (length=10)
  'vitrine' => string 'vitrine' (length=7)

I noticed 'und' by printing my field and reading the first comment on this page
Drupal process states 7.x

and my field that should be visible (or not)

$form['field_target_text'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#states' => array(
          'visible' => array(
            'input[name="field_type[und]"' => array('value'=>'interne')
          ),
        ),
      );

I tried to replace input with select, to remove [und] but nothing did the job until I replaced the field like this

$form['field_type'] = [
        '#type' => 'select',
        '#title' => ('TYPE TPE'),
        '#description' => ('TEST.'),
        '#options' => $form['field_type']['und']['#options']
      ];

Seems like he doesn't like my field not having an ['#options'] but ['und']['#options']. However by doing so, when I save my node, the field_type is empty.

Any help or advise would be appreciated.

You miss ] in the selector ':input[name="field_type[und]"' code test with the following it will work.

':input[name="field_type[und]"]' => ['value' => 'interne'],

Update:
The state work with any valid JQuery selector, so if you looking to target it with select selector instead of :input you can use this:

 'select[name="field_type[und]"]' => ['value' => 'interne'],


Passing variables to a theme from a custom module I have a custom module which initiates the theme hook - passing the $node object as an argument:

theme('my_widget', array($node));

function my_module_theme() {
  return array(
    'my_widget' => array(
      'template' => 'my_widget',
      'variables' => array('node' => array($node)),
    ),
  );
}

However, in the 'my-widget' template file, I need to pick up the $node variable. But doing a dpm() on $node returns Null.. - think I may be setting the variable incorrectly, but not sure what's going on. Cheers

The correct code is the following one.

Theme call

theme('my_widget', array('node' => $node));

Theme declaration

function my_module_theme() {
  return array(
    'my_widget' => array(
      'template' => 'my_widget',
      // This array contains the default values.
      // You should not use a PHP variable.
      'variables' => array('node' => NULL),
    ),
  );
}


Problem with custom token Below is the code I am trying to get implemented for a custom token module. The purpose of the token is to work in conjunction with the [field_display_name] token for the comment author's name for a recent comment block (created be Views). I am using tokens in the rewrite results option of (Author) User:link Field in the View. The plan was to add this new token to the comment tokens so that it would show up in the View field's rewrite results replacement patterns. The token replacement pattern would be [field_display_name][commenter-count], with the intended final output being one of the following options:

No additional commenters -> just the comment author's name i.e. "John Smith"
One additional commenter -> "John Smith & 1 other"
More than one additional commenter -> "John Smith & 2 others"

I have enabled the module, and I am not getting the new token showing up in the replacement pattern options. I'm not sure if this is a code issue or a Views settings issue. I am suspicious that the argument ($nid) for the commenter_count API function to perform the query is not being passed in from the current node. Any help would be appreciated.

Thank you in advance.

<?php
/**
* @file
* Extends the comment modules tokens to include a token (commenter-count).
* To be used in conjunction with the [comment:author] token.
*
* When Enabled this module creates a token that counts all commenters
* of a node and returns one of 4 possible strings:
*
*  Case 1 - No commenter   - returns False.
*  Case 2 - 1  commenter   - returns Null.
*  Case 3 - 2  commenters  - returns string: "and 1 other".
*  Case 4 - 2 commenters  - returns string: "and # others".
*/

/**
* Get number of commenters for a specific node.
*
* @param $nid
*  Node-id to count commenters for.
* @return $commenter_count result an integer, or FALSE on error.
*/
function commenter_count($nid) {
  if (isset($nid)) {
    // Retrieve the number of commenters for the current node-id.
    $results = db_query('SELECT COUNT(DISTINCT uid) FROM {comment} WHERE nid = :nid',  array(':nid'=> $nid))->fetchField();
    if ($results->uid < 1) {
      $commenter_count = '';
    }
    elseif ($results->uid == 1) {
      $commenter_count = t('& 1 other');
    }
    else {
      $commenter_count = t('& @num others', array('@num' => $results->uid));
    }
    return $commenter_count;
  }
  else {
    return FALSE;
  }
 }

/**
* Implements hook_token_info().
*/
function commentor_count_token_info() {
  $info['tokens']['comment']['commenter-count'] = array(
    'name' => t('Commenter count'),
    'description' => t('This token counts the number of commenters of a given node.')
  );
}

/**
* Implements hook_tokens().
*
*/
function commenter_count_tokens($type, $tokens, array $data = array(), array $options =      array()) {
  $url_options = array('absolute' => TRUE);
  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
    $language_code = $options['language']->language;
  }
  else {
    $language_code = NULL;
  }
  $sanitize = !empty($options['sanitize']);
  $replacements = array();
  if ($type == 'custom') {
    foreach ($tokens as $name => $original) {
      switch ($name){
        case 'commenter-count':
           $replacements[$original] = commenter_count($node->nid);
          break;
      }
    }
  }
  return $replacements;
}

A token like [field_display_name] in the rewrite results option for the display of a Views field is not the same as a token everywhere else in Drupal, so hook_token_info() and hook_tokens() won't help you.  On behalf of Drupal, Views, and the million or so other available words in the English language, i apologize.

Instead you need to extend a Views field handler class and override the document_self_tokens() and add_self_tokens() methods.  You can instruct a field to use your custom field handler via hook_views_data_alter() (thanks to Daniel Wehner for this info, and very likely the hook itself).

You can see example code from my need for adding a Views field replacement pattern / token.

If you need help adapting it for your need above let me know and i'll write that here, but the remember to list in your .info the file with your field handler extending class so that Drupal registers it, and it'll work fine.


I am not able to override the form #access setting I cerated a form alter with the file entity media upload browser. I studied this answer of how to alter this form. I then debugged and found that for what I wanted to do, I am in step 4 of the file upload browser as evidenced by the var: $var['#step'] (Integer) 4.

Thus my code so far is:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Form ID = file_entity_add_upload.
 */
function MYMODULE_form_file_entity_add_upload_alter(&$form, &$form_state, $form_id) {
  // Check that this is the fields step.
  if ($form['#step'] == 4) {
  echo 'This is step 4';
  // yep the above prints out.

  // Set access false for the specified field.
  $form['field_usage_restricted']['#access '] = FALSE;

  // Add a dsm after to see what's going on
  dsm($form);
  }
}

You'd think this would get rid of the form field, yet, it's still present. See the dsm below:

I would think that my custom alter FALSE setting would override the TRUE setting but no such luck, the field is still there.

I can use an unset($form['field_usage_restricted']); and that works fine to get rid of the field, but I've learned that ['#access '] = FALSE; is a better way to go, especially when there's ajax in use such as the case here. I do see in the debug that there's a form after build so I wonder if I need to do that?

I tried this on the off chance it would work but still no joy:

if ($form['field_usage_restricted'][LANGUAGE_NONE]['#after_build'][0]) {
  // Set access false for the specified field.
  $form['field_usage_restricted']['#access '] = FALSE;
}

(Note, my field, field_usage_restricted is not a required field.)

$form['field_usage_restricted']['#access '] the #access key has a space in it. Only reason I can think of you would get two items in the array like that. Remove that space, and dump the item out again. It should be overwritten and have FALSE for a value.


Drupal 7 Rules - Set value of multiple value reference field (user reference) I have a cck content type with a multi value reference field.
Using rules, I am trying to populate these reference fields when users create a different content type (for example an event and I want to keep adding user references for people that view the event -- this is an example.)

My issue right now is that I can fetch the entity to set the user reference (using a loop of users), but I can only set the first field.
How do I move to the next field of the fetched entity and set it to the next user in the loop list?

I imagined that as long as I was in the loop, for each item in the loop, a set data value on the reference field would move to the next field but it simply overwrites the first one.

I see that the particular reference field I'm trying to set values for is an array (fetched-entity:field-blah:0 etc). Since I cannot pick for example item [0], I thought  fetched-entity:field-blah without the delta would keep shifting to the next. It does not.

I'm thinking there is a way for me to loop through the deltas in the fetched entity as I loop through the list?

Any help appreciated.

Install next modules:

Conditional Rules
Rules Bonus Pack

Create a rule for "Content is viewed".
Set conditions , like "content is type"
Create a loop and set its name, in the data selector choose the field(not the deltas) like [node:field-alumnos-curso]
Create an action inside the loop(do not "set data value"), just select "add item to the list" and the value will be the list name or loop name.
Remember create a action "Save an entity".


How to get a form field to allow additional values? I need to have a way to allow for multiple values to be used for a field.

For example,

Someone has school name(s), and the form description says, "Add your schools here."

I add a school, press a button for an additional, another text field appears, etc.

I know I have seen this before, but I cannot seem to find it anywhere.  How do I do this?

I thought it might be this module(s):

https://www.drupal.org/project/field_collection

https://www.drupal.org/project/webform_addmore

How to add additional "items" on a webform in Drupal 7

But I'm not sure.  I thought it was built into Drupal webforms.

If you want to allow a field to get multiple values.you need to edit the field and allow the numbers of values to unlimited.
Suppose you want to allow multiple images to upload in Article content type.

1)Go to Administration » Structure » Content types » Article » Manage fields
2)Edit the field and under field settings,choose the values to unlimited or number of values you want a user can upload.
See the similar in screenshot url below.
https://www.evernote.com/shard/s496/sh/15655bf1-104c-40ed-ab26-bc6da6ebe7a5/bd1bce151edec9956746845474f3ba95


How to create a single page checkout for donations but standard cart/checkout for for other ecommerce? I am currently using Commerce for handling selling physical products but also donations.

I would like to have a one page donation that includes the amount and entering their credit card information but still allow the standard cart/checkout process if they are doing physical products.

Is there any way of doing both because it seems that I can only pull off one or the other?

Here is an example of a single page.

You can use Commerce Buy One Click module.
The Project page says

Commerce Buy One Click Module allows customers to checkout directly
from the product page with just one click, skipping the annoying
checkout steps.

For more info go through the module documentation.


Problems with text formats and Iframes I'm trying to display an iframe (google maps) on my node. I allowed "iframe" with the "plain text" format and unchecked "Display any HTML as plain text": http://www.diigo.com/item/image/fgah/3hc0?size=o

I select the text processing option  "Filtered text (user selects text format)" for the field:
http://www.diigo.com/item/image/fgah/dmeh?size=o
I enter the iframe code with the "plain text" selection
http://www.diigo.com/item/image/fgah/7svw?size=o
The iframe renders fine.

I changed the text processing option for this field to "plain text": http://www.diigo.com/item/image/fgah/04e2?size=o

Now the iframe won't render (just shows the iframe HTML code).
Why would it not work, isn't it the same "plain text" option?

Each text format that you create has some different processing options.

If you select

  Display any HTML as plain text

Then the result is what you explained, where HTML code is escaped and displayed instead of having any effect.

Instead

  Limit allowed HTML tags

Can be used to limit the kind of html tags which are allowed, but if disallowed tags are used, they will not take effect.

It sounds like you are confusing the two.

Update

The text processing and input filters are not related.

You have filter called plain text, but you could call it anything, like super input field, pony or whatever. When you select filtered input, you get to choose which filter to use.

The other text formatting option is plain text. Selecting this means that you wont use any text filter, not even the one you might call plain text. The result of using this kind of text processor is that the text will be rendered as plain text.


Restore with backup & migrate module does not work with Acquia Dev Desktop Having messed up my dev site (running on Win 7 using Acquia Dev Desktop), I restored a backup I took a few hours ago with the Backup & Migrate module. Now when I click the local site name in Acquia Dev Desktop I get a Choose Language message from Drupal instead of my site. I'm certain I had this problem a few months ago, but I apparently did not make good notes because I don't know where I found the instructions to fix this problem. My guess is that the $database parameters are wrong in settings.php or maybe there's some other problem.

Help is appreciated!

There could be many reasons for this not working for you but as long as you've got the database backup and a copy of your existing codebase, you should be fine. Fixing DevDesktop database issues is a little tricky but the easiest way is to just create a new instance with the correct settings. Quick steps to do this:

We're going to be deleting the whole site instance using DevDesktop so you should make a backup of the folder and your database backup or at least move it outside of the DevDesktop folder.
Now from the DevDesktop application, delete your site and then create another one with the same name, etc. This will create a new database and a new settings.php file that is connected to it.
Finally, you'll want to copy your codebase back into this directory
(making sure not to overwrite the settings.php or sites.php files
that DevDesktop created) and then try the restore again using backup
& migrate.