Why am I missing 'notification' features on my entityforms? A coworker installed entityforms on a staging site and it delivers email notifications nicely.  I am trying to replicate the process on the production site, but I am missing all the features/UI related to email notifications.

Below you can see I'm missing access/submission/validation options.  I am also missing the 'Notifications' tab that should show up on the entityform 'edit' page.

Staging server

Production server

I have the rules module and other dependencies (auto-installed with drush)
I have Entityforms Notifications enabled
I have Rules UI enabled

What am I missing?

Because... I have different versions of Entityforms on staging and production.  In the more recent version (7.x-2.0-beta2), they just moved things around.

You can get to the notification rules now by going to Structure > Entityform Types > [form] and clicking the Rules tab.


Is there a way to import a view grid into a Carousel Hi i have created grid view of a content type coupon which has a logo,description and download button and i'm wondering is there a way to import that view into a Carousel so it can display a grid of 9 coupons and when i hit next it displays another set of 9.

Try using the jCarousel module which has great integration with views module.

This tutorial might help you as well - https://www.youtube.com/watch?v=jEMBVGBFskE


Cannot retrieve value on client side I use this PHP snippet on the server side after a submission of a webform:

function mymodule_webform_submission_insert($node, $submission) {
 // $node will give you the node id of your webform
 // $submission will give you the id of your data which you inserted in web form
 $sid = $submission->sid ? $submission->sid : FALSE;
 if($sid){
   dsm($sid); // yes, the sid is shown after a submission
   if(!isset($_SESSION['mymodule'])){
     $_SESSION['mymodule'] = array();
   }
   $_SESSION['mymodule']['webform_id'] = $sid;
   drupal_add_js(array('mymodule' => array('webform_id' => $_SESSION['mymodule']['webform_id'])), 'setting');
 }
}

... and then on the client side I have ths JS snippet:

(function ($) {

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

                var sid = Drupal.settings.mymodule.webform_id;
                console.log('the submission ID is: '+ sid);
        }
    };

}(jQuery, Drupal));

.. but the variable sid is "undefined" in the console (after a submission) no matter what I try to do. Can anyone see what I am doing wrong?

The problem here appears to be the location in which you are calling drupal_add_js(). The way Drupal works with form submissions, is that after processing is complete, it does a redirect to the page again. This way when you click back (or forward) in the browser, you don't get the message asking you if you want to post the data again. You are adding your JS in a processing function, which happens before the redirect, so it is getting lost after the redirect.

You'll need to find a different location to put your call to drupal_add_js(), that comes after the redirect. It should go in the same place where you are loading your script in the first place.


call js in html.tpl.php I want to add smoothstate script to my pages.
I have to call 2 files at the bottom just before closing body-tag. Smoothstate.js and Functions.js. How can I call those 2 js in my html.tpl.php

<script src="js/jquery.smoothState.js"></script>
<script src="js/functions.js"></script>

Smoothstate.js

Its too simple my friend. For these types of manipulations template_process_html(&$variables) comes handy. This is provided by theme.inc located in includes/ folder of your drupal directory.

You can put this function in your template.php file of your custom theme directory

/**
 *Implementing template_process_html()
 */

function custom_theme_process_html(&$variables) {
    $path = drupal_get_path('theme','custom_theme');
    $variables['scripts'] .= '<script src="' . $path . '/js/jquery.smoothState.js"></script>
<script src="' . $path . '/js/functions.js"></script>';
}

  This will append these new scripts to your scripts variables that is rendered to html.tpl.php as <script> tags while processing it. Provided that you put these scripts in the js folder located in your theme folder . So the file path should be like this - sites/all/custom/themes/custom_theme/js/functions.js.

Don't forget to clear the cache as its a new hook in your template.php file and drupal won't execute that hook until you do that.

Hope that helps.


Error "Public files directory Not fully protected" Appears in Nginx? I'm wondering why this errors appear on my drupal site when I am using Nginx:

Public files directory  Not fully protected
See http://drupal.org/SA-CORE-2013-003 for information about the recommended .htaccess file which should be added to the sites/default/files directory to help protect against arbitrary code execution.
Error
Temporary files directory   Not fully protected
See http://drupal.org/SA-CORE-2013-003 for information about the recommended .htaccess file which should be added to the tmp directory to help protect against arbitrary code execution.

Any solution to this?

In the security advisory referenced in the error, it describes the specific vulnerability as "Code execution prevention (Files directory .htaccess for Apache - Drupal 6 and 7)" and recommends updates to your htaccess files in your files directory. Part of the recommended htaccess update is the following text:

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

The SetHandler string is what Drupal is using to determine whether you've made this change or not.  Even though you're using Nginx as your webserver, its still going to display this error until you've made this update. From the advisory again:

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

I'm running a couple nginx servers as well and had to make these updates just to make these errors go away. I was curious how they were doing this check and found this in the
modules/system/system.install file at line 284:

// Check for the string which was added to the recommended .htaccess file
// in the latest security update.
if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file))
|| strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
...


Put structure fields in a div i'm beginning with Drupal 7, and i would like to do a "block" with a picture to the left, a title right to the picture, and a description below the title.

I made a new structure, there is already a field title, and a field body, so i just added a field image.

Then I made a new view containing this new structure, but the problem is that it shows the title, then the picture, then the description.

I think the solution would be to put the title field and the description field into a div block, and then with css, declare the div and the image as "inline-block". How could i do this please?

Your question is indeed very confused. You might first clarify some Drupal basic concepts.

What is a block ? "Blocks are the boxes of content (such as "User Login" or "Who's online") that can be displayed in regions (such as footer or sidebar) on your page." Read Working with blocks (content in regions) for full understanding.

What is a content type ? We don't speak about structures but content types : a Content Type is a pre-defined collection of data types (Fields), this is how site editors can input original content on a Drupal site. Read Working with content types and fields.

What is a view ? "Using the Views module, you can fetch content from the database and present it to the user as lists, posts, galleries, tables, maps, graphs, menu items, blocks, reports, forum posts etc." Read Working with Views.

How to change the way blocks, fields, and so on display  ? this is a very wide question.

Without editing any code, you can make some basic choices in admin/structure/types/, and for the content type you'd like to edit,  manage display of each of the fields
you can install an infinity of contributed themes
you can create your theme, and then customize your regions, edit your stylesheets... A good place to begin might be the Theming Guide

Drupal is a very powerful CMS / CMF , but you'll have to deal with these concepts to feel a bit more confortable


Execute Drupal Feeds Import Programatically - Where to put code I found this code for executing feeds importers programatically:

<?php

// Define the id (machine name) of the importer you want to use.
$importer_id = 'my_feeds_importer';

// Load the Feeds Source object.
$source = feeds_source($importer_id);

// Override configurations... (more on that in a moment)

// Execute the import.
$source->startImport();

?>

I'm just not sure where this code is supposed to go (I'm still pretty green when it comes to Drupal!).

I think you have found the code from this link. In this case you can mention this code in a custom function or hook_cron or in a separate page. Totally depends upon you.

Follow
Triggering the Feed Import module
and
Programmatically execute FEED import


How should I remove a region and zone in an Omega 3 sub theme? I have a sub theme of Omega 3.

What is the correct way to completely remove regions and zones from my sub theme? Is it OK to just simply disable them and then remove them from the .info file?

These regions and zones are never going to be used and I want to simplfy the site by removing anything that isn't needed.

Thank you

Just remove the region and zone definition from the theme info file.


How can I modify the $submitted variable for a custom node template? I have a content type called "Blog post" (machine name = blog_post).

I've set up a custom node template that works properly called "node--blog_post.tpl.php"

I'd like my $submitted output to be "by User Name | Month, Day of Month, Year" (example - "by John Smith | November 2, 2016"

I've been working on this for 2-3 hours without being able to have any effect on the output, and have gotten to the point in my searching where the only links I'm finding that seem relevant are things I've already clicked on. I'm stuck.

I know there are multiple ways to do this, but I'm looking for how to make this happen using a theme_preprocess_node function in the template.php file. Not only because I've seen multiple posts saying this is the "best practice", but also to gain more familiarity with the template.php file itself & how it is used.

Any thoughts?

You can do this.In your theme_preprocess_node function create a new variable which is used in your node--blog_post.tpl.php .

 function yourtheme_preprocess_node(&$variables) {
 $node = $variables['node'];
  if ($node->type == 'blog_post') {
    $created = $node->created;
    $date = date('F j,Y', $created);
    $name = $node->name;
    $variables['new_variable'] = "By ".$name." | ".$date;
  }
}

then print this new_variable in your tpl like this.

  <div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
  print $new_variable;
?>

Output show like this


How to get taxonomy term name from tid? A lot of our stuff has uris formatted like site/taxonomy/XX,  where XX is an integer.

I found a lot of questions like "how to get the TID from the name?", but I'd like to get the name from the TID. I'm trying to put together a breadcrumb script and everything is great except for these cases where I'm getting a trail like "home > term". Instead I want to have it like "home > <TERM NAME>".

How can I do so?

If you're using Drupal 7 you can use taxonomy_term_load()

$term = taxonomy_term_load($tid);
$name = $term->name;

If you've got a bunch of term IDs you can save having to run a single query for each load by using taxonomy_term_load_multiple():

$tids = array(1, 2, 3);
$terms = taxonomy_term_load_multiple($tids);

foreach ($terms as $term) {
  $name = $term->name;
}

If you're stuck using Drupal 6 you can use taxonomy_get_term():

$term = taxonomy_get_term($tid);
$name = $term->name;

There's no multiple-load option for Drupal 6 that I know of unfortunately.


Syntax to display only the node body using node embed module Would appreciate it if someone could let me know what the syntax is to display only the node body within another node.  I tried something like this:

[[nid:1234 body]]

Obviously, that is not working.  Any ideas???

That should be only [[nid:1234]] without body in it, as it embeds body by default. Also, make sure you've enabled the filter at admin/config/content/formats/TEXT_FORMAT.
Edit: Adding my comment in here to make it more clear.
If you wish to only show body of a node within node, you can do so by:

Turning on the "Node Embed" view mode at admin > structure > types > manage > CONTENT_TYPE > display

Changing the settings of the "Node embed" mode to only display body of the node. Node embed module uses this view mode by default (if enabled for a particular content type).

You will now be able to use the above syntax without any need to specify any options.

P.S. - You could use the Display Suite module to have a better control the display of the fields.


Change dropdown value depending on URL clicked Using Drupal 7. From links in an email newsletter, how would it be possible to change the value of a default option value on a webpage? Is there a /?q= that can be used?

email link1 -> my webpage with option 2 selected

email link2 -> my webpage with option 3 selected

by default, webpage dropdown has option 1 selected

Prepopulate module will take values from the URL and populate a field.
This page has an example for D7.


How to show "field-image" in search page? I want make a photo gallery with Drupal.
I have a problem with showing article images (that shows in homepage in a div classed "field-image"), I want show this image is search page.
After searching for something just title and text shows, how to show images there?
Thanks a lot :)
look at this shots:

If you're using default core search, you can modify "Search result" display there.


Trying to access node content with PHP I have the following code to load a different node into my homepage:

<?php $node = node_load(2); ?>

      <button class="close" data-dismiss="modal">×</button>

<?php echo $node->title; ?>

      <?php render( $node->content ); ?>

      Close

The title displays, but the content doesn't. I get the error Notice: Undefined property: stdClass::$content in include()

Based on what I read here I feel this should work. What do I need to do to make the node content display? (it's just a basic page w/ title and body)

The node's content isn't built when you load the node, you need to invoke it manually with node_build_content():

$node = node_load(2);
node_build_content($node, $view_mode);

// You now have access to $node->content


Is it better to create a taxonomy term using the 'create' method of the base Entity class or the entity storage manager? I've seen multiple ways to programmatically create entities.

In this case I'm creating a taxonomy term. One is using this method

$term = \Drupal\taxonomy\Entity\Term::create([
  'name' => $name,
  'vid' => $vocabulary,
])->save();

Where I'm using the base entity class's public static create function. Another way to perform the action is using an entity storage manager. Like so:

$term = [
  'name'     => $name,
  'vid'      => $vocabulary,
];

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term);

I looked up the 'create' function of the base Entity class and it seems to just be implementing what appears in the second example I provided. Is there a better practice between the two? Or does it not matter?

UPDATE: Also is there a difference between what the two return? Unless I'm doing things wrong I noticed that the top method returned an int which I'm assuming is the term id.

In procedural code it doesn't matter, because both do the same. The static create() is a shortcut for the second example. (The different result is because the first saves the term and the second does not, if you want the term as result then save in a separate step)

In OOP code a better way is dependency injection. The second example points in the right direction. Inject the entity type manager, store it in a class property and use it:

$term = $this->entityTypeManager->getStorage('taxonomy_term')->create($term);

How to inject a service depends on which class you want to use it in.

A lot of base classes include services already and if you are lucky such a common service like this is one of them. Sometimes, for example in a controller, there is a method to retrieve the service. Then add to the code above parentheses:

$term = $this->entityTypeManager()->getStorage('taxonomy_term')->create($term);

See ControllerBase::entityTypeManager().


.install file not working properly I am new to Drupal, and I am trying to write a module with an .install file which will create a database table. The table isn't being created (as seen from the error codes when I try to access it. It also doesn't show up in the Schema module listing) and I don't know what I did wrong. Can someone see if they can find the error?

This is the code:

function email_form_schema() {
  $schema['subscription_info'] = array(
    'description' => t('The base table for nodes.'),
    'fields' => array(
      'first' => array(
        'description' => t('The first name'),
        'type' => 'varchar',
        'not null' => TRUE,
        'default' => '',
      ),
      'last' => array(
        'description' => t('The last name'),
        'type' => 'varchar',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => '',
      ),
      'email' => array(
        'description' => t('The email address'),
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => ''
      ),
      'phone' => array(
        'description' => t('The phone number.'),
        'type' => 'varchar',
        'length' => 10,
        'not null' => TRUE,
        'default' => '',
      )
     ),
    'primary key' => array('email'),
  );

  return $schema;
}

function email_form_install() {
  // Create my tables.
  drupal_install_schema('email_form');
}

function email_form_uninstall() {
  // Drop my tables.
  drupal_uninstall_schema('email_form');
}

Here's the error when I try to access it:

  user warning: Table 'drupal620x120318224310.subscription_info' doesn't exist query: INSERT INTO subscription_info (first, last, email, phone) VALUES ('','','','') in C:\EasyPHP-5.3.8.1\modules\drupal620x120318224310\sites\all\modules\email_form\email_form.module on line 123.

I was missing the return $schema; line (which I modified above), but it still doesn't work. In the schema module it lists the "subscription_info" table as missing. What does this mean?

If I had a penny for every time I've done this...

You've forgotten to return $schema from your email_form_schema() function.

You'll need to reinstall the module (not just disable then re-enable) for the changes to take effect.

There's also a problem with the "last" column. It's a "varchar" and you're using the "unsigned" property which isn't compatible with that type.

You also need to provide the "length" property for all of the "varchar" type columns, including "first" and "last".


Turn Tags into Links in Search Results When a user searches for a certain tagged iamge I want them to be able to click on the tag and re-direct them on a page which contains all the images with that tag.
E.g. if I click Italy, all the pictures which have Italy as tags will be displayed.
Can I use Views module for it?

You can do this in two ways,

Using the module Similar By Terms
Using views, Read more here


Raw (unlinked) ouput of $name variable I'm using <?php print $name; ?> in node--front.tpl.php for an exceptional case, where I can't use Views and the output goodies Views has to offer. By default $name output is themed to link to author profile.

Is there anyway to output the author name in raw text, without going throught a preprocess function?

The entire node object is available as $node so you should be able to do something like:

$author=user_load($node->uid);
print check_plain($author->name); // reasonably safe given the 'Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.' validation upon registration but let's check_plain() it anyway

or

$author=user_load($node->uid);
print check_plain(format_username($author));

if you have modules installed that modify the display of the user name.


hook_views_query_alter() not working? Very new to web development and even newer to Drupal, and I have some questions that I would really appreciate if anyone could answer!
Here's my yml file, [Site name] is actually just the name of our site:
name: '[Site name] Query'
description: '[Site name] custom queries'
package: [Site name]
core: '8.x'

Here's my .module file:
<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

function ppc_query_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  $database = \Drupal::database();
  if ($view->id() == 'test_events') {
    $query = $database->query("SELECT node__field_date.field_date_value AS node__field_date_field_date_value,
      node_field_data.nid AS nid, DATE_FORMAT((node__field_date.field_date_value + INTERVAL -18000 SECOND), '%Y%m%d%H') AS node__field_date_field_date_value_hour
      FROM {node_field_data} node_field_data
      LEFT JOIN {node__field_date} node__field_date ON node_field_data.nid = node__field_date.entity_id AND node__field_date.deleted = '0'
      WHERE (node_field_data.status = '1') AND (node_field_data.type IN ('event')) AND (node__field_date.field_date_value >= DATE(NOW()))
      ORDER BY node__field_date_field_date_value_hour DESC, node__field_date_field_date_value ASC
      LIMIT 4 OFFSET 0
");
  }
}

I copied and pasted the query that was already being run on my view and added some changes that the views module couldn't support.
However when I run this module on my site, nothing changes. How do I get my query alter function to work?
Thank you!

Nothing changes because you are setting a hook argument, but the value to which you set that argument isn't kept.
hook_views_query_alter() is invoked from Sql::alter(), which is called from ViewsExecutable::build().
// ViewsExecutable::build()
// Let modules modify the query just prior to finalizing it.
$this->query->alter($this);

// Sql::alter()
\Drupal::moduleHandler()->invokeAll('views_query_alter', [$view, $this]);

The only way to alter the query is using the methods made available from QueryPluginBase (including its parent classes), not replacing an object passed to the hook with another object. See for example workspaces_views_query_alter(), an implementation of that hook done from a Drupal core module. The relevant code altering the query is the following one (ViewsQueryAlter::alterQuery() and ViewsQueryAlter::alterQueryForEntityType()). (I copied only the comments that could help in understanding the changes done to the query.)
public function alterQuery(ViewExecutable $view, QueryPluginBase $query) {
  if (!$this->workspaceManager->hasActiveWorkspace()) {
    return;
  }

  if (!$query instanceof Sql) {
    return;
  }

  $entity_type_ids = [];
  foreach ($query->relationships as $info) {
    $table_data = $this->viewsData->get($info['base']);
    if (empty($table_data['table']['entity type'])) {
      continue;
    }
    $entity_type_id = $table_data['table']['entity type'];

    $entity_type_ids[$entity_type_id] = $entity_type_id;
  }
  $entity_type_definitions = $this->entityTypeManager->getDefinitions();
  foreach ($entity_type_ids as $entity_type_id) {
    if ($this->workspaceManager->isEntityTypeSupported($entity_type_definitions[$entity_type_id])) {
      $this->alterQueryForEntityType($query, $entity_type_definitions[$entity_type_id]);
    }
  }
}

protected function alterQueryForEntityType(Sql $query, EntityTypeInterface $entity_type) {
  $table_mapping = $this->entityTypeManager->getStorage($entity_type->id())->getTableMapping();
  $field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($entity_type->id());
  $dedicated_field_storage_definitions = array_filter($field_storage_definitions, function ($definition) use ($table_mapping) {
    return $table_mapping->requiresDedicatedTableStorage($definition);
  });
  $dedicated_field_data_tables = array_map(function ($definition) use ($table_mapping) {
    return $table_mapping->getDedicatedDataTableName($definition);
  }, $dedicated_field_storage_definitions);
  $move_workspace_tables = [];
  $table_queue =& $query->getTableQueue();
  foreach ($table_queue as $alias => &$table_info) {
    if ($table_info['table'] == 'workspace_association') {
      break;
    }

    if ($field_name = array_search($table_info['table'], $dedicated_field_data_tables, TRUE)) {
      $relationship = $table_info['relationship'];

      if ($table_info['join']->field != 'entity_id') {
        continue;
      }

      $new_table_name = $table_mapping->getDedicatedRevisionTableName($field_storage_definitions[$field_name]);

      $workspace_association_table = $this->ensureWorkspaceAssociationTable($entity_type->id(), $query, $relationship);

      // Update the join to use our COALESCE.
      $revision_field = $entity_type->getKey('revision');
      $table_info['join']->leftFormula = "COALESCE({$workspace_association_table}.target_entity_revision_id, {$relationship}.{$revision_field})";

      // Update the join and the table info to our new table name, and to join
      // on the revision key.
      $table_info['table'] = $new_table_name;
      $table_info['join']->table = $new_table_name;
      $table_info['join']->field = 'revision_id';

      // Finally, if we added the workspace_association table we have to move
      // it in the table queue so that it comes before this field.
      if (empty($move_workspace_tables[$workspace_association_table])) {
        $move_workspace_tables[$workspace_association_table] = $alias;
      }
    }
  }

  // JOINs must be in order. i.e, any tables you mention in the ON clause of a
  // JOIN must appear prior to that JOIN. Since we're modifying a JOIN in
  // place, and adding a new table, we must ensure that the new table appears
  // prior to this one. So we recorded at what index we saw that table, and
  // then use array_splice() to move the workspace_association table join to
  // the correct position.
  foreach ($move_workspace_tables as $workspace_association_table => $alias) {
    $this->moveEntityTable($query, $workspace_association_table, $alias);
  }
  $base_entity_table = $entity_type->isTranslatable() ? $entity_type->getDataTable() : $entity_type->getBaseTable();
  $base_fields = array_diff($table_mapping->getFieldNames($entity_type->getBaseTable()), [
    $entity_type->getKey('langcode'),
  ]);
  $revisionable_fields = array_diff($table_mapping->getFieldNames($entity_type->getRevisionDataTable()), $base_fields);

  // Go through and look to see if we have to modify fields and filters.
  foreach ($query->fields as &$field_info) {
    // Some fields don't actually have tables, meaning they're formulae and
    // whatnot. At this time we are going to ignore those.
    if (empty($field_info['table'])) {
      continue;
    }

    // Dereference the alias into the actual table.
    $table = $table_queue[$field_info['table']]['table'];
    if ($table == $base_entity_table && in_array($field_info['field'], $revisionable_fields)) {
      $relationship = $table_queue[$field_info['table']]['alias'];
      $alias = $this->ensureRevisionTable($entity_type, $query, $relationship);
      if ($alias) {
        // Change the base table to use the revision table instead.
        $field_info['table'] = $alias;
      }
    }
  }
  $relationships = [];

  // Build a list of all relationships that might be for our table.
  foreach ($query->relationships as $relationship => $info) {
    if ($info['base'] == $base_entity_table) {
      $relationships[] = $relationship;
    }
  }

  // Now we have to go through our where clauses and modify any of our fields.
  foreach ($query->where as &$clauses) {
    foreach ($clauses['conditions'] as &$where_info) {
      // Build a matrix of our possible relationships against fields we need
      // to switch.
      foreach ($relationships as $relationship) {
        foreach ($revisionable_fields as $field) {
          if (is_string($where_info['field']) && $where_info['field'] == "{$relationship}.{$field}") {
            $alias = $this->ensureRevisionTable($entity_type, $query, $relationship);
            if ($alias) {
              // Change the base table to use the revision table instead.
              $where_info['field'] = "{$alias}.{$field}";
            }
          }
        }
      }
    }
  }
}

The code is also wrong because it replaces an instance of a class that extends QueryPluginBase with an instance of a class that implements StatementInterface. Those objects aren't interchangeable, as their methods and properties are different.


PHP XML parsing + daily authentication request I have a news provider who sends me non-RSS XML feeds through HTTP requests that then need to be parsed to be used on my site. However, my first request to the external server always has to be an authentication request which expires after 24 hrs. The authentication ID gets sent back to me as an XML tag attribute in the source code of an otherwise empty document. I then have to include this ID with every news request I send back to the news server.

Is there any way to automate this entire process through a series of Drupal 6 modules, or is it just best to write the code directly in the template files and schedule a daily task to request the authentication ID?

You could write a module where you implement hook_cron() to get the authentication ID and then store in the drupal DB (e.g. as variable via variable_set()). After that you can use it inside your templates without any worry. But you have to trigger your cron.php once a day via a sytem cron-job or the poormanscron module. For PHP xml-parsing take a look at SimpleXML.

EDIT: Module creation:

For this job it would be a simple module. Take a look at the module-dev-guide. First you create a YOURMODULE.info file. After that you put your code inside a YOURMODULE.module file. Than implement that hook_cron() like that:

function YOURMODULE_cron() {
     update_news_service_id();
}

function update_news_service_id() {
    // add your code here
}

One more comment: If you try to solve it this way you must consider calling update_news_service_id() from the template (or ..._preprocess()) if you run into an expired service id-error.


Overwrite file_directory_temp function without touching the core? I need to modify the file_directory_temp() function, but I can't touch the core.

My drupal-site runs in Microsoft Azure Cloud and I need to exclude all temp files from drupal-root into a absolute location.

I basically want to prefix the value from variable_get('file_temporary_path') with an absolute file-path: "C:\temp" + "\sites\default\tmp"

Because the absolute part of the path is a dynamic value, which depends on environment and is returned by function Microsoft_WindowsAzure_RoleEnvironment::getLocalResource('Temp') it can't be stored in database, due to changing enviroment.

In a nutshell:

I need file_directory_temp() function to return:

$temporary_directory = Microsoft_WindowsAzure_RoleEnvironment::getLocalResource('Temp') . variable_get('file_temporary_path', NULL);

instead of:

$temporary_directory = variable_get('file_temporary_path', NULL);

The prefix is dynamic and can't be stored in database, due to changing enviroment setup.

Code for variable_get() is:

function variable_get($name, $default = NULL) {
  global $conf;
  return isset($conf[$name]) ? $conf[$name] : $default;
}

So if value is constant during one page call you need to set:

global $conf;
$conf['file_temporary_path'] = Microsoft_WindowsAzure_RoleEnvironment::getLocalResource('Temp') . $conf['file_temporary_path'];

If value can change for each request, you need a more bold move. And  PHP 5.2.0 or later.

class TempClass {
  private $path;
  public function __construct($path) {
    $this->path = $path;
  }
  public function __toString() {
    return Microsoft_WindowsAzure_RoleEnvironment::getLocalResource('Temp') . $this->path;
  }
}
global $conf;
$conf['file_temporary_path'] = new TempClass($conf['file_temporary_path']);

That way you'll have an object, that will be converted to string on each use, and on that conversion will retrieve current value from Microsoft_WindowsAzure_RoleEnvironment class.

Where to put it?

Best place for it seems to be a hook_boot(). You need to make sure your hook_boot() is called first. To get your module to run first, use hook_module_implements_alter() or easier and less reliable way - Modules weight module.

If you don't care about the value provided via UI, you can (maybe should) put it in settings.php instead, and substitute reads from $conf['file_temporary_path'] with hard-coded value. You don't need to use global in settings.php.

Conflict with UI

When you open form to edit file_temporary_path, you will see value with Azure's prefix string already prepended. That's not what you want there, as multiple saves would prepend it multiple times. Use hook_form_alter() to change default value to one obtained directly from the database, or, if you hardcoded it in settings.php, to set it to hardcoded string and disable field.


Custom story-node-form.tpl.php not working I have created a custom node add form for story content type. Though this appears as expected but do not working. Problem is when i click on the Submit button then this form just redirect me again in node/add/story path instead creating the story page!Here is what i have did (Here i have used bartik theme):

  template.php

    function bartik_theme() {
    return array(
    'story_node_form' => array(
    'arguments' => array('form' => NULL),
    'template' => 'story-node-form',
    'render element' => 'form',
    ),
    );

  story-node-form.tpl.php

<?php print drupal_render($form['title']); ?>

<?php print drupal_render($form['body']); ?>

<?php print drupal_render($form['actions']); ?>

<?php print drupal_render($form['additional_settings']); ?>

<?php print drupal_render($form['actions']); ?>

Now if i click on the Submit button then this story creating form just redirect me again in node/add/story path instead creating the story page! What i am missing here? Thanks

I have solved this by doing <?php print kpr($form); ?> and put all the hidden input fields in the form like token, form_id etc that worked!


fetchAllAssoc() is returning only first row I have a query like this:

  $product_classes = db_select('node_type', 't')->fields('t', array('name', 'type'))->condition('module','uc_product')
  ->execute()->fetchAllAssoc('orig_type', PDO::FETCH_ASSOC);

It will return an array with only first valid table row, however there are more valid rows.

If I use this query, without specified fields:

  $product_classes = db_select('node_type', 't')->fields('t')-:condition('module','uc_product')
  ->execute()->fetchAllAssoc('orig_type', PDO::FETCH_ASSOC);

It will return array with all the valid rows. It is a drupal bug?

Maybe the reason?
"If the given key appears multiple times, later records will overwrite earlier ones."
https://api.drupal.org/api/drupal/includes!database!database.inc/function/DatabaseStatementInterface%3A%3AfetchAllAssoc/7


delete a product that added to an order I want to delete an order,but when I try to delete it notify me "This product is referenced by a line item on Order 40 and therefore cannot be deleted. Disable it instead" but I want delete it completely in my product list, It is not important delete an order item that is used in.

Commerce is protecting its own data integrity - if you were able to delete a product that's referenced by an order line, the next time you view the associated order something would break.

You'll need to remove the product from all associated orders before deleting it; I think the easiest way to do so would be to construct a View using Views Bulk Operations, select Line Items filtered by the relevant product ID, and bulk delete them. Obviously this will have an effect on existing orders, but since the product is attached to the line item by its ID, there isn't really an alternative (short of rewriting a bunch of stuff in Commerce).


"Page not found" on hook_menu() items I have create simple hook_menu but when i clear cache retrieve Page not Found

function sanabel_calculator_menu() {
  $items = array();
  $items['iban_generator'] = array(
    'title' =>  t('IBAN'),
    'page callback' => 'iban_generator',
    'access callback' => true,
  );

  return $items;
}
function iban_generator(){
  $branch = $_GET['branch'];
  $accountNumber = $_GET['accountNumber'];
  $number_format = "11192427" . $branch . "00" . $accountNumber . "192400";
  $checkdigit = 98 - ( $number_format % 97 );
  $iban = 'JO' . $checkdigit . 'BJOR' . $branch . '00' . $accountNumber;
  $output = '

 ' . t("Account Number") . '
    ' . t('IBAN') . '

  ' . $accountNumber . '	' . $iban . '

'. l(t('Back'), $back_form) .'
';
  return drupal_set_message($output);
}

How can fix this problem ??

Follow this checklist and it will work:

Make sure your module is called sanabel_calculator. If it isn't, change sanabel_calculator_menu() to MODULE_NAME_menu(). It's wise to use your module name to prefix all functions that it defines, as a rudimentary namespacing system. You might want to change iban_generator() to sanabel_calculator_generator() as part of that, to avoid confustion in the future.
Return something meaningful from your function. drupal_set_message() can return NULL, and other than that will only ever return a plain array. This is not acceptable as a page callback result, which needs to be a render array (or, less ideally, a string).
Make sure the module is enabled
Clear Drupal's caches

As an aside, consider defining a proper access callback or at least arguments for your page. It may not matter, but it's a good practice to get into.

If it still doesn't work after that, follow the steps again through again. If it still doesn't work, you've got something wrong with your installation. Try to install the module on a fresh copy of Drupal to confirm that.


Count items in nested field array for if/then in template I'm sure I'm missing something very straightforward here:  I want to prevent the thumbnail slider in my image gallery from being rendered if there's only one image for the node. My first thought was, optimistically:

  <?php if (count($content['field_media']) > 1): ?>

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

  <?php endif; ?>

I saw why that didn't work when I examined the node structure. In an example case for a node with one image, I have

 field_media (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 17 elements)

the last one being the actual file element with an fid, etc. The corresponding field for a node with two images is

 field_media (Array, 1 element)
    und (Array, 2 elements)
        0 (Array, 17 elements)
        1 (Array, 17 elements)

So the array I need to count is nested inside the 'und' array. I know I've used that in other templates, like $field_external_link['und'][0]['url'].  But when I print count($content['field_media']['und']), I get 0.  How do I evaluate the number of elements in that array?

You can use field_get_items api function to read values.

<?php

$images = field_get_items('node', $node, 'field_media');
if (count($images) > 1) {
  // Print Carousel
}
?>


Displaying SQL-table as a paginated list I'm trying the following and it works:

my.module:

   function my_menu() {
      $items['page_example'] = array(
        'title' => 'Page Example',
        'description' => 'Page Example',
        'page callback' => 'page_example',
        'access callback' => TRUE,
        'file' => 'my.page.inc',
        'file path' => drupal_get_path('module', 'my'),
        'type' => MENU_CALLBACK,
      );
     return $items;
   }

my.page.inc:

function page_example() {
  return array(
    'page_example' => array(
      '#type' => 'markup',
      '#markup' => generate_list(),
    ),
  );
}

function generate_list() {
  $query = db_select('users', 'name')
    ->extend('PagerDefault')
    ->fields('name', array('Name'))
    ->orderBy('created', 'DESC')
    ->limit(20);

  $result = $query->execute();
  $output = '';
  foreach ($result as $row) {
    $output .= $row->name.'
';
  }

  $output .= theme('pager');
  return $output;
}

But then I try prepending a uid-field to each row and it fails:

  $query = db_select('users', 'name', 'uid')
    ->extend('PagerDefault')
    ->fields('name', array('Name'), 'uid', array('Id'))
    //->addField('uid', 'User Id')
    //->addField('name', 'User Name')
    ->orderBy('created', 'DESC')
    ->limit(20);

  $result = $query->execute();
  $output = '';
  foreach ($result as $row) {
    $output .= $row->uid.': '.$row->name.'
';
  }

With the error:

Recoverable fatal error: Argument 3 passed to db_select()
must be an array, string given, called in my.page.inc
on line 13 and defined in function db_select()
(line 2387 in includes/database/database.inc).

UPDATE:

On Camsoft's comment (thank you) I've modified the code to:

  $query = db_select('users')
    ->extend('PagerDefault')
    ->fields('name', array('Name'), 'uid', array('Id'))
    //->addField('uid', 'User Id')
    //->addField('name', 'User Name')
    ->orderBy('created', 'DESC')
    ->limit(20);

And now it fails with

DOException: SQLSTATE[42P01]: Undefined table: 7 ERROR:
missing FROM-clause entry for table "name" at character 8:
SELECT name.Name AS Name, created AS created FROM {users}
users ORDER BY created DESC LIMIT 20 OFFSET 0; Array ( )
in function PagerDefault->execute() (line 80 includes/pager.inc).

I'm just trying to figure out how to add a 2nd SQL-table field to a paginated db_select... Please do not suggest a "View" to me, because I'm trying to understand DBTNG at the moment.

The call to db_select() and the following calls to methods are wrong.

The second parameter of db_select() is a table alias, which should then used when referring to the fields used by the query.
the parameters passed to the fields() is wrong; see the following snippet for an example of how the call to db_select() should be.

$result = db_select('file_usage', 'f')
   ->fields('f', array('module', 'type', 'id', 'count'))
   ->condition('fid', $file->fid)
   ->condition('count', 0, '>')
   ->execute();

Your call to db_select() should be re-written as:

$query = db_select('users', 'u')
  ->fields('u', array('name', 'uid'))
  ->orderBy('created', 'DESC')
  ->limit(20)
  ->extend('PagerDefault');


views exposed filter on non existent field I have a content type which has the following fields:

month: List (integer) [jan, feb, ..., dec] (non mandatory)
year: Date (only collects year - mandatory)

I can normally create two exposed views filters, one for the month and one for the year.

What I'd like to do though is have a single exposed filter which, internally, would operate on the two fields above at once.

For example if the operator is "Is Between" and the user selects Oct 2011 to Feb 2012 I'd like the filter to return only nodes which have:

2011, Oct
2011, Nov
2011, Dec
2012, NULL month
2012, Jan
2012, Feb

Note that I've used two fields (month and year) instead of one so I can have the possibility of a monthless node.

What approach should I take? I've thought of the following:

use a third field which, on hook_node_presave will store the calculated (filter specific) date on the node. I wouldn't like this field to be visible on the edit node screen though
somehow (using a hook) calculate and rewrite the view filtering query. My problem here is how to display an exposed filter for a field which does not exist

The most obvious solution to me would be to get the month data into the date field, since you are treating the date to be 1/1 when no month is given, this would fit just fine; there is no reason to create a new field for this.

You should be able to do this in a form submission handler for the node edit form.


Auto Fill Content Fields I want to have a content type named person with fields like first name, last name, phone number ....

In another content type named account, it will also contain the fields belong to person, but I want to have a drop down list for the field person in account to select from existing person content, and auto populate the rest of the fields in account.

Also, is it possible to auto populate a field based on the value in previous field? For example, two fields of the same content type, user id and user email, while user input the user id sunnyside, user email would automatically generate sunnyside@gmail.com.

Thanks

you have to write alter function for your form then you may attach fields from another entity by using field attach form function here is a example for loading profile2 fields form elements

 global $user;
         $profile = profile2_load_by_user($user,'profile');
        field_attach_form('profile2',$profile,$form,$form_state,'und');


Contextual link in Product Display type to allow me to edit the referenced Product? I have a Product Display node and it has the following contextual links: Edit, Delete and Manage Display.

The Edit link allows to edit the Product Display node.  I need to add another contextual link to allow me to edit the product referenced by the product display.

Please take a look a this image:

This is a year old question, but worth answering I think.

You can use this hook (hook_menu_contextual_links_alter). The sample does exactly what you want. (I mean altering node's contextual links)

Here's an actual code I did. And it works for multiple products too.

    // Add a link to all contextual links for nodes of type product_display.
    if ($root_path == 'node/%' && $router_item['page_arguments'][0]->type == 'product_display') {

      // Loop through all products
      foreach ($router_item['page_arguments'][0]->field_product[LANGUAGE_NONE] as $element) {
        $product = commerce_product_load($element['product_id']);

        // Add your contextual link
        $links['edit_prod_'.$element['product_id']] = array(
          'title' => t('Edit @sku', array('@sku' => $product->sku)),
          'href' => 'admin/commerce/products/'.$element['product_id'].'/edit',
          'localized_options' => array(
            'query' => array(
            'destination' => current_path(),
          ),
        ),
      );
    }
  }

This will add contextual links like 'Edit HMWPB' or 'Edit POHPB'


Unable to show form using controller (module) I want to make custom page in drupal with form, I checked few examples showing page in drupal via module and example of form via module, i tried to merge them but no success.
I made a custom page using drupal module with template (twig) file.

Below is my controller code

namespace Drupal\booktestdrive\Controller;
use Drupal\Core\Controller\ControllerBase;

class BiveController extends ControllerBase {
  public function show() {
    $form_class = '\Drupal\booktestdrive\Form\TestForm';
    return [
        '#theme' => 'bive_page_theme',
        '#form' => \Drupal::formBuilder()->getForm($form_class),
    ];
  }
}

Template file code

bive_page_theme.html.twig

<section> hii
{{ form }}

</section>

i also created form at src/form/BiveForm.php

namespace Drupal\bive\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class BiveForm extends FormBase {
  public function getFormId() {
    return 'booktestdrive_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['first_name'] = array(
      '#type' => 'textfield',
      '#attributes' =>array('placeholder' => t('First Name*')),
      '#required' => TRUE,
    );

    $form['last_name'] = array(
      '#type' => 'textfield',
      '#attributes' =>array('placeholder' => t('Last Name')),
      '#required' => FALSE,
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }

    public function validateForm(array &$form, FormStateInterface $form_state) {

      if (strlen($form_state->getValue('candidate_number')) < 10) {
        $form_state->setErrorByName('candidate_number', $this->t('Mobile number is too short.'));
      }

    }

  public function submitForm(array &$form, FormStateInterface $form_state) {

   // drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('candidate_name'))));

    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

   }
}

Routing.yml

bdrive.book:
  path: '/brive'
  defaults:
    _controller: 'Drupal\brive\Controller\BriveController::book'
    _title: 'Test'
  requirements:
    _permission: 'access content'

brive.form:
 path: '/brive-form'
 defaults:
   _title: 'Application form'
   _form: '\Drupal\booktestdrive\Form\BriveForm'
 requirements:
   _permission: 'access content'

You need define new function theme bive_page_theme before call it. You can see docs and example. In your case, you can write more code in file .module

/**
 * Implements hook_theme().
 */
function Your_Module_theme($existing, $type, $theme, $path) {
    return [
        'bive_page_theme' => [
            'variables' => [
              'form' => NULL,
            ],
            'path' => $path . '/templates',
        ]
    ];
}

and create file bive_page_theme.html.twig in folder templates of module. Clear cache and go to page.


Show search results in block When you click on a search result, you navigate to that node or user. I would like to show the search results in a block when a user navigates to one of the search results, so the other results are always quickly available. Any idea if this is possible?

I was thinking... Make search result variable ($search_results) global, and show this in a php block. But maybe there are better ways to solve this issue?

Override search-result.tpl.php with below code

<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url . '?search_keyword=' . arg(2); ?>"><?php print $title; ?>

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

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info): ?>

<?php print $info; ?>

    <?php endif; ?>

Then create a view that displays search results using views module and add a contextual filter saying search term, which is returned using PHP Code.

You can read the value in views contextual filter using $_GET['search_keyword'] and return the same.

Once view block is built, enable it in the pages you want !


Count of nodes by type I am looking for a snippet that lets me display the total count for a specific node type, e.g. "Pages = 167" or "Products = 10630."

What code should I use to achieve this?

You can use the Views module to do this.

Create a new view, remove sort options, fields and other default settings
Add a field for "Content: Type"
Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
Add yet another field for "Content: Type"
On the second "Content: Type" field, click "Aggregation settings"
Set the aggregation type to "count"
The second "Content: Type" should now look like "COUNT(Content: Type)"

That should be it! If needed, adjust some more settings like field labels and row style settings.

Here is an export of such a view, so you can easily import it and try it out:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Node counts';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
$handler->display->display_options['row_options']['hide_empty'] = 0;
$handler->display->display_options['row_options']['default_field_elements'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['external'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['html'] = 0;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type_1']['hide_empty'] = 0;
$handler->display->display_options['fields']['type_1']['empty_zero'] = 0;
$handler->display->display_options['fields']['type_1']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type_1']['link_to_node'] = 0;
$handler->display->display_options['fields']['type_1']['machine_name'] = 0;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type']['alter']['external'] = 0;
$handler->display->display_options['fields']['type']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type']['alter']['html'] = 0;
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type']['hide_empty'] = 0;
$handler->display->display_options['fields']['type']['empty_zero'] = 0;
$handler->display->display_options['fields']['type']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type']['separator'] = '';
$handler->display->display_options['fields']['type']['format_plural'] = 0;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


Drupal 8 Remove book child pages with in the content block I am looking to not show Book child-pages within the content and only show them in sidebar region. So I anticipate not to hide them using css but remove the child-pages that gets called automatically within the main content (near to the end of the content block)

In D7 (not sure of D8) if you install Display Suite and enable the "Full Content" view mode for Books. You can then apply any layout you want to book pages and control where the book navigation goes for example.

Attempting to override the book behavior from Core can be very difficult ...


How to drop tables shown as Missing in Schema Report During development/testing after using Backup and Migrate Restore in conjuction with Schema, Schema will show Extra tables no longer referenced in the database, used by modulesetc, and no longer required.

How can these tables be removed with a module or within drupal with api/php? Can a form be created to specify select tables to drop?

Check out the db_drop_table function.

You could use it on the mysite.com/devel/php page which runs arbitrary php for you, but be ultra careful with it and always have backups, because if you get it wrong you could completely kill your site.


How can I get the length of a list in Rules? If there is another way to check if a list is empty, that is fine too.

Make a custom module eg. customrules and create customrules.rules.inc in this module.
In customrules.rules.inc place following code:

/**
 * Implements hook_rules_action_info().
 */
function customrules_rules_action_info() {
  return array(
    'customrules_list_length' => array(
      'label' => t('Get length of list'),
      'group' => t('Data'),
      'parameter' => array(
        'list' => array(
          'type' => 'unknown',
          'label' => t('List'),
        ),
      ),
      'provides' => array(
        'list_length' => array(
          'type' => 'text',
          'label' => t('List length'),
        ),
      ),
    ),
  );
}

/**
 * The action for 'customrules_list_length'
 */
function customrules_list_length($list) {
  return array(
    'list_length' => is_array($list) ? count($list) : NULL,
  );
}

Now you should be able to use this action to get the list length


How to load a taxonomy term (or entity) by field value? To load a taxonomy term programatically you can use EntityFieldQuery.

<?php

// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $section_vocab->vid);
  $result = $query->execute();

  ...

}

However, that doesn't load the taxonomy term fields. Adding a field condition to the query$query->fieldCondition('field_id', 'value', '123'); to the query doesn't work as the result is always empty.

Bad solution

So the solution using EntityFieldQuery that I found here https://www.drupal.org/node/1517744 works, but it requires looping through all the terms in the vocabulary (in the worst case) which has a high cost.

<?php

// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

$sectionID = NULL;

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $section_vocab->vid)
  $result = $query->execute();

  if (!empty($result['taxonomy_term'])) {
    // To load all terms.
    $terms = taxonomy_term_load_multiple(array_keys($result['taxonomy_term']));

    // Look up for the first term with the field value that we want.
    foreach ($terms as $term) {
      // Stop looking if we find it
      $value = $term->field_id['und'][0]['value'];
      if ($value == $IDtoFind){
        $termID = $term->tid;
        break;
      }
    }

  }
}

If the taxonomy term has a field with machine field_id, how can you load the taxonomy terms with a specific value for it?

As specified in the EntityFieldQuery documentation. It is not possible to query across multiple entity types. It is no possible to query all the terms with a specific field value as this would require querying both vocabulary->vid and field_id->value.

To load a taxonomy term by field value is possible to get all the entities that have that value:

  $query->entityCondition('entity_type', 'taxonomy_term')
    ->fieldCondition('field_id', 'value', $IDtoFind, '=');

Using ->fieldCondition('field_id', 'value', $IDtoFind, '=') and ->propertyCondition('vid', $section_vocab->vid) in the same query would produce an empty result.

Solution

For the code in the question this would work, based on that field_id is used only one vocabulary and it value is unique.

<?php
// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

$sectionID = NULL;

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->fieldCondition('field_id', 'value', $IDtoFind, '=');
  $result = $query->execute();

  if (!empty($result['taxonomy_term'])) {
    // Set the internal pointer of an array to its first element
    reset($result['taxonomy_term']);
    // Get the key value for the first item
    $termID = key($result['taxonomy_term']);

  }
}


Use node_save with a custom nid On our system (D5) two nodes have been deleted (by mistake). I need them back but I can't simply load a backup as there's a lot of new content created.
I want to create these two new nodes again, manually, and they will obviously have a bigger nid.

Then, I would like to simply change the nid to the old (the deleted one) nid. This way, all node references will work again. (Node references from other content types).

I tried the following:

//load the newly created node
$node_new = node_load(1234580);

//put the
$node_new->nid = 81580; //this is the nid of the deleted node
$node_new->vid = 81580; //and its vid

node_save($node_new);

And if I print_r $node_new at the end, it says the nid is 81580, but on the database there's no node with that nide.

How can I create a node and specify the nid manually??

You'll need to change the nid manually in the database.
As far as I know, only the D7 node_save() allows you to specify the nid during initial save (because it allows you to set $node->is_new as well instead of overriding it).

And no version will ever allow you to change the nid in an update.


How to use Apache Solr as data source for a view Is it possible to use data indexed in Solr as the data source for a specific view?
I already tried installing the search api, search api page, entity api, ctools, search api solr and the views api.

I already created a server and an index which uses solr:

But the only fields that I get are node fields:

I'm expecting to get the fields from documents that I indexed in Solr. How do I do that in Drupal, is there a specific module that would allow me to make use of the fields that already exists in Solr as the fields for a view?

All you need is Apache Solr Views module.

  This module provides Views implementation for the Apache Solr Search
  Integration Project 7.x-1.x branch. Requires Views 3.

  This module will provide facet navigation combined with searching to
  make a powerful user experience.

After installing this module, you can able to create a Apache Solr view, which list all the fields which are available in the indexed documents in the solr.


List all terms from a vocabulary I have a taxonomy called services and want to list out all the terms. I can load the vocab with

 $vocabulary = taxonomy_vocabulary_machine_name_load('Services')

but cannot seen to get all the terms out.

There are a few ways but I prefer entity_load():
$vocabulary = taxonomy_vocabulary_machine_name_load('Services');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

You could also use:

taxonomy_term_load_multiple()
EntityFieldQuery


Colorbox trigger builds clunky html instead of array There is this view of which I configured the fields as follows:

Gallery images: exclude from display
  - Background: in cck, this is a separate image field with multiple values called 'Gallery images'

Title: default

Custom text:
  - Exclude from display
  - No results behavior: Hide if empty checked + Hide rewriting if empty checked

Colorbox trigger:
 -  trigger field: custom text
 -  popup: [field_project_gallery_images]
 -  No results behavior: Hide if empty checked + Hide rewriting if empty checked

This works nicely in itself, colorbox shows a nice slideshow after clicking on the custom text. The problem is that the colorbox trigger should only be output if there are actually images uploaded to the gallery images field. I other words, Hide rewriting if empty checked leaves me with no success.

Which isn't a surprise when dpm($fields). It shows the gallery images field as one chunk of HTML entirely instead of an array. dpm($fields) output comes down to the following if that makes sense:

    <?php

$fields['colorobox']['content']['Meer foto's

 Prev Next

']

?>

No wonder there is no 0 to interpret as an empty field. This way, I can't loop through it and hide if count 0. To count the characters of the HTML would be way too dirty. But then, what can I do?

This is unfortunately just the way the colorbox module works.

Because it is possible to put any content in a views colorbox it is set up to handle anything in a very generic way, which means it doesn't handle single images in the most effective way and the trigger field way of configuring things is more complex than is needed in some cases.

I opened a similar issue about resizing the colorbox based on images, which you also cannot currently do because of the same issue of the way it has been implemented.

It is something I believe the module maintainer could fix though.
I would recommend opening a feature request issue on drupal.org at https://drupal.org/project/issues/colorbox?categories=All


How can i change registration email send to admin I was wondering how to change the standard text in the email send to the administrator when a new user has registered.

Is there a way to change the text? Maybe the same way as you can change the emails send to the user when registered?

thanks

Unlike normal users there's is no UI to change the text of the message sent to administrator on account creation.

You could implement hook_mail_alter(), to achieve this via a custom module:

function MODULE_mail_alter(&$message) {
  if ($message['id'] == 'user_register_pending_approval_admin') {
    //$message['body'] is the array you want to change.
    $message['body'][] = 'Your custom message for admin goes here.....';
  }
}


MySQL master/slave database replication? Since it's so easy to set up pagodabox with multiple databases (for free), I thought I'd experiment with master/slave database setups.

I have good credentials for both MySQL databases. Everything should be fine and dandy.

The trouble is: At no point does Drupal create tables on the slave DB. I made a module to show me the credentials, and verify the connection, but the DB simply has no tables.

Should it? Is Drupal supposed to do this? Or do I need to do the initial replication myself?

No, Drupal doesn't.

Master/Slave replication is the job of the database management system, not Drupal's. All that Drupal does is use it, by using the slave server for specifically marked queries.

To be able to use replication, you either need a pre-configured hosting environment which already provides this or full access to the database server so that you can configure it. Replication happens on a server to server level, not database to database. In short, Pagodabox will most likely not allow you to set up replication.


I can't backup my website on a shared server because memory runs out. What can I do? I have a large Drupal7 website on a shared Hostgator server, and I cannot do automated backups because I always run out of resources.

I've tried 2 methods:

1) I first built my own CLI bash file and I set up a cron job to execute it every night. The cron job emails me the output, and it never finishes and it says it ran out of resources. It was to just save the backup to the same machine.

2) I installed the Backup and Migrate module for Drupal and set up an FTP account on a seperate server on a seperate network to send the backup to. When I try it, after a minute it goes to an Error 500 screen. There's an advanced option for choosing to use CLI tools (it says this is better for larger sites) but after several minutes it went to an Error 405: Not Allowed page.

Does anybody have any advice?

Thanks!

According to this tutorial hostgator shared hosts can get ssh access so 2 of the solutions below assume ssh access ha been setup properly (the setup of ssh is beyond the scope of these forums)

This is also a general solution as most shared hosts nowadays have ssh access

1. using command line

# go to root directory
cd httpdocs

# dump database
mysqldump -u USERNAME -p'PASSWORD' DATABASENAME > database.sql

# zip the whole drupal directory
zip -9 -qr html.zip .

2. Using drush

setup drush (done once)

# get drush
wget http://files.drush.org/drush.phar;
# if above does not work go to and get the link to latest version .phar from
# https://github.com/drush-ops/drush/releases
# wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar;

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

# go to that directory
cd ~

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

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

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

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

using drush

# after setting up drush
# go to root directory
cd httpdocs
# dump the database
drush sql-dump > database.sql
# zip the whole drupal directory
zip -9 -qr html.zip .

3. if no ssh present you will need to use cpanel, plesk or another control panel

database backup (one of the following)

go into cpanel and find phpmyadmin go into your database and start the export process
some panels will have under databases a way to backup a database without getting into phpmyadmin

files backup

go into file manager and find the root directory (public_html or httpdocs) and zip the folder

Notes

More on drupal backup

If memory runs out on any of the previous solutions perhaps you ought to upgrade your plan or move to a vps/dedicated/cloud hosting solution

if none of the above works and the support is not willing to help you set a way to backup your site get out of that host they are not worth the money that you spend


theme_hook_suggestions based on empty field I'm trying to implement theme_hook_suggestions in preprocess node template based on the fact that a field (field_logo) is empty or not.

The template change is not working.

Can anyone help?

This is the code that I have so far:

function community_alpha_preprocess_node(&$vars) {
  $node = $vars['node'];
  if(($node->type == 'advertorial') && !$teaser && $node_top){
    $advertorial_type = $node->field_logo['und'][0]['tid'];
    if(!empty($advertorial_type)){
      $vars['theme_hook_suggestions'] = 'node__advertorial';
    }else{
      $vars['theme_hook_suggestions'] = 'node__advertorial__alt';
    }
  }

}

Thanks.

You need to clear the cache after making changes in the template.php file.

For Drupal 7 version please run below command to clear the cache and check aftewards.

drush cc all

For Drupal 8 version please run below command to clear the cache and check afterwards.

drush cache-clear


How to add the relationship for tittle of content type of other in view How to add the relationship for tittle of content type of other in view of different content type.

You need to relate the two content types somehow. One of the most popular ways of doing it is using the module entity_reference.

After you install the module, create a field of type "entity_reference", and by then you should be able to add a relationship in your view using this field, allowing you to use all fields of the second content type on the primary content type's view.


Drupal as (powerful) relational database I’d like to make a Drupalsite, providing a platform for people around the world who are working on the same research topic to collaborate and communicate. (I’m sure Drupal is therefore an excellent choice).

However, this website should also include a relational database (which will be a very interesting research tool for the visitors of the website).  A test version of this database already exists in ooo base: it has 50 tables with a lot of many-to-many and one-to-many relations between them. Very basically it records the relations between persons, events and organisations.

I know it’s possible to create a relational database in drupal by creating custom contenttypes and by using the entity connect module. However, having a look at the way Drupal stores these data in its mysql database, I’m afraid this way of building a database isn’t very useful for me, as it seems very difficult to query the data (or to use [social network] analysis software on them). The possibility of querying the data easily, is crucial for my database.

I know it’s possible to add a second database to the drupal site (cf http://drupal.org/node/18429).  However, I’m not sure whether that’s the solution for my problem.

Very short I’d like to know:

(1) Whether it’s possible to change the way Drupal saves the data of some content-types in its mysql database, to a way which seems more “natural” for analyzing data (and being able to query them easily)

(2) Whether it’s possible to add a second mysqldatabase to the drupal site, which organizes the data of some content-types on a custom (more ‘natural’) way. If possible, the users of the drupal site have to be able to add content and to analyze these data, as if they were saved in the same database.

I’d be very thankful if someone could help me!

You have a good start on working with the databases.  From my own experience I am loath to rely/allow Drupal to maintain any sensible data.  And since you already have a robust database it sounds like it would not be a good option for you either.

With all that said, it seems like you want to simply hook into the node/content saving that occurs in drupal.  You will then be able to connect to an external database and process and insert the data anyway you choose.

Node API Hooks - D6 has similar functions, just named differently.  There are a lot of hook points in the process.  You can even alter forms and add your own submit functions.


Configuration of views with entity reference fields I've read several guides about this subject but still incapable of achieving what I want.

I have a main content type (aventuras) and then another content type for images. The images are referenced to the main content type via an Entity Reference field.

I want to create a view that shows a list of all the nodes of the main content type (their titles and other fields) along with their images (reference field).

I think I need to add the "Entity Reference: Referenced Entity" relationship and then the image field with that relationship selected, but that is not working (it only shows fields of the main content type, no image).

I've tried several alternatives (contextual filters, adding also the relationship to the filter, using Referencing Entity instead of Referenced...) without any luck.

Maybe this is an annoying noobie question that has been answered before, but I've searched and tried a lot and I can't find the solution for my case.

Any clue would be much appreciated. Thanks!

The images are referenced to the main content type via an Entity
  Reference field.

Who has the entity reference field? The Main content type (aventuras)?  OR the Images content type?

Based on your question, I will guess the Main content type.

If the Main content type has the entity reference field, then under Advanced you need to add a relationship of Referecing and NOT Referenced Entity (notice the bold endings).

Also, no need to add a relationship in the image field.


Drupal says "There was a problem creating field ZZZ: Table field_data_field_ZZZ already exists" I've run into this periodically:  I'm working on a new site and go to add a field that I've created at some point in the past only to find out that it's not available.
When I try to add a 'new' field (usually using the same title & machine name, because they pop up when I start typing), I get this message:

  There was a problem creating field ZZZ: Table field_data_field_ZZZ already exists

There are several posts out there on this issue, but none of the solutions really tell the whole story.

Why did this happen and how do I fix it?

Problem

It's possible that something else could cause this, but it doesn't seem too likely.

The problem comes from using backup_migrate to recover or overwrite your database when there is some degree of disparity in the fields in the different databases.  Here's one example of how things can get out of sync:

I start by building out a complex set of content types on my local machine.
I copy the database over to a staging site periodically so I have a stable copy and so other people can do other things.
I forget that I added some fields on my localhost.
I use backup_migrate to grab the latest copy of the database.  (This is where things start to go wrong - it could happen without a dev/staging scenario too, if, for example, you roll-back to an earlier backup of your own database.  There are probably many ways things can get out of wack like this.)
I then see that my field is missing - doh.
When I try to recreate the field I get that rotten message.  You tell me it exists, but you won't let me add the rotten field??!?

What's going on

The problem is two-fold:

Backup_migrate doesn't drop all the tables when you restore a database so the field_data_field_zzz and field_revision_field_zzz tables are not removed.
However the field_config table and the field_config_instance tables are completely replaced. This is where Drupal keeps track of the fields that have been created, so now it has no idea that field_zzz ever existed.

The immediate solution:

Take a look at the known fields (the contents of field_config).  Any fields that are not listed there need to be cleared out of the database, if you want to recreate them.  Just drop the field_data.. and field_revision.. tables from the database.  Now you can go about your business as usual.

..and the haunting:

The problem is that fixing this on your local machine does not fix the problem on other instances of your website.  For instance, if you clean things up and push them up to a staging server, that server is not going to delete unused tables either.  Then at some point in the future you'll grab a copy of that database and experience the pain all over again.  You will google the same query, end up at this post again and call me rotten names for giving you a solution that failed.

The definitive solution:

Frankly, understanding the problem is the biggest step.  The second biggest step is to make sure you fix all instances of your site.  So once you have a nice clean version of your site, you'll want to

drop all the tables on your other site(s)
go to install.php and create a blank drupal site
enable backup_migrate
now when you restore your clean db, you won't have all that baggage
repeat on each site (we usually have multiple localhost/dev installs, then a staging and live site)

In reality, there are a lot of reasons this may not be feasible, but now you should know enough to create your own work-around.


Drush @sites alias does not work in a multisite installation I have 3 Drupal sites installed and I've developed a simple "hello-world" command that just does the following:

drush_log(getmypid() . ' Hello world!', 'ok');

When I run drush @sites hello-world I get the following error message:

  Could not find a Drupal settings.php file at sites/default/settings.php

Please note that the command is working fine when run for a specific site.

drush -l test1 hello-world

I was under the assumption that Drush @sites alias should be available by default. Is it not?

I just tested this on HEAD of today's master branch of drush, and drush @sites status worked fine for me with no sites/default folder.  Try upgrading to drush 7.0-alpha9.


Get just the first item from a multiple valued field using field_view_field() I'm using field_view_field() to get the render array for a image field that has multiple values. I then use drupal_render() on that resulting array to print out the markup.

I only want the first image to be returned in the markup for that field. Is there a way to either manipulate the rendered array to remove the other fields or a setting when call field_view_field() to say only return first row?

Have you considered using field_view_value?  It is the recommended way to retrieve a single value from a multi-value field.


How to use my own video and be able to play from a specific time? I have Drupal 7 with the video module installed using ffmpeg. The video is playing fine. However, I noticed that users can only play from the beginning of the video. I would like to have users play from any specific time.

The embed video field module is only for embedding other videos so does not suit my needs.

May be you can try with javascript

document.getElementById('YOURVIDEOID').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

In jquery

var vid = $("#video")[0];
$("#button").click(function(){
    skipTime(100);
});

function skipTime(time) {
    vid.play();
    vid.pause();
    vid.currentTime = time;
    vid.play();
};


Remove jQuery and find out what is asking it to be included I'm using drupal 7 and I simply don't want jQuery included at all. It seems like most people are advocating modify the js in a theme hook. That's fine I suppose, but it seems like this is dangerous and a little silly.

If we're removing jQuery after something has requested it, won't that break whatever requested? How can I find out what is requiring jQuery?

Related to that is all the system CSS files that are included by default. I've also found that using a theme hook to get rid of them is the way to go. It seems like Drupal has a lot of "features" like this that require you to add more code to remove things. It seems like there should be a more efficient way to handle things like this. (forgive me if I'm mistaken, I'm coming from years of work with frameworks and not a full stack CMS).

In the end, what I want is a theme that has NOTHING in it except what I explicitly say should be there. Right now I'm considering just writing the html.tpl.php to not use the dynamic drupal variables.

I think that it is pretty safe to assume that any module using JS is going to assume that jQuery is present.  Yes they should feature detect this, but its availability in Drupal is pretty much assumed by everyone.  There is no real way to get a list of all of the jQuery dependencies.

CSS can be aggregated and minified if the worry is file count.

If you truly want to manage these yourself, your best bet is to remove the $scripts and $styles variables from html.tpl.php and manage your own, eg $myscripts and $mystyles.  You could also unset/reset them in your own template_process_html.

Drupal is built on hooks.  Don't think of it as having to add code to remove something.  You add code (implement hooks) as a way to modify or extend the default behavior.

Now that I have answered your question, you are really going out of your way to bypass a lot of the power of Drupal.  You should start by looking into what Drupal calls starter themes or base themes.  The Omega and Zen themes are two popular ones.


How to notify site admin when user registers with a specific field checked My case site has student and teacher accounts (teacher/student radio buttons). When user registers as a teacher, admin has to be notified so that admin performs further checks to accept the account.

How can I do this programmatically

You should be able to accomplish this easily using the Rules module:

Create a rule that triggers 'After saving a new account'
Add a condition that determines whether the value of the field is set to the teacher value (Using 'Data Comparison').
Add an action element to send a notification email (System > Send Mail).


On the theme "busy" how to remove the "0 comments" at the bottom? I have already deactivated the ability to comment on every page but now it just says "0 comments" this is very annoying.

Try disabling the comments module, or set the comments to be hidden in the content type settings.


'"entity_test" entity type does not exist' on attempted module uninstall I'm in the process of replacing D8's core Search module with Search API. When I try uninstalling Search, I get this error:

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The "entity_test" entity type does not exist. in /Applications/MAMP/htdocs/mysite/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

There is an entity_test table in the database, along with a number of related tables. I also have $settings['extension_discovery_scan_tests'] = FALSE; in the settings.local.php file.

How do I address this error?

Sounds like you installed the entity_test module accidentally and then disabled test modules afterwards.

Set that flag to TRUE, clear cache, uninstall search and the entity_test module (look for other enabled _test modules too) then set that flag to FALSE again.


How to alter languageswitcher to display as select element I am trying to get to grips with D8, and want to be able to use the language module's language switcher block. I am trying to alter the output to get it to display as a select element rather than a list.I tried creating block--languageswitcher.html.twig but couldn't see how to alter the list.

Looking into the module, I can see a function language_element_info_alter but cannot see how to use this to render a different output.

Do I need to use a block_alter or theme hook? In the LanguageBlock.php, the build() function returns an array with a #theme parameter set to links__language_block. Would this be what I need?

Yes, you could override the links__language_block template (links--language-block.html.twig) and print out a select there by hand. You would also need JS to make selecting something the same as clicking a link as an option element alone won't be able to trigger like a form.


Passing theme suggestions to radio and checkbox children I have a simple radio button defined by with following YAML:

country:
  '#type': radios
  '#title': Country
  '#options':
    1: 'England & Wales'
    2: 'Scotland'
  '#required': true
  '#theme_suggestion': minimal

The #theme_suggestion is my addition, in my .theme file I have the following code:

function HOOK_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#theme_suggestion'])) {
    $suggestions[] = $hook . '__' . $variables['element']['#theme_suggestion'];
  }
}

The combination of these options successfully allows me to override the twig templates for fieldset and radios e.g.:

<!-- FILE NAME SUGGESTIONS:
   x fieldset--minimal.html.twig
   * fieldset.html.twig

   x radios--minimal.html.twig
   * radios.html.twig
-->

However, these suggestions do not get passed down to the children (form_element, form_element_label and input__radio), I cannot find any documentation or examples on how to do this.

A possible way is to alter the form in which the radio is used if you know its id, or, for a broader solution, check for each form whether the radio is used.
Then you can call this function:

    function MY_CUSOMT_FUNCTION(&$form, $theme_suggestion) {
     foreach (Element::children($form) as $child) {
     if (!isset($form[$child]['#theme_suggestion'])) {
       $form[$child]['#theme_suggestion'] = $theme_suggestion;
     }
     MY_CUSOMT_FUNCTION(&$form, $theme_suggestion)
    }
   }

You can fine tune it to include only the children of your radio though


Adding a custom subject field to the Revision Information Drupal 7 I would like to be able to add a subject field to the Revision Information along with the log message. Is there any way I could do that?

No - because revisions are not Drupal entities themselves but metadata associated with entities. You can expose an entity to the revisioning system but not the other way around, its a core part of Drupal.

Best way I could think of to come close to this functionality is to have a special fieldset / field collection of fields that allow for what you want (ex. log message, subject) and then use field permissions to hide that from the end user. You would then have your team use these fields for recording their updates rather than the log field.


how do I call a rest server? I have a Drupal 8 site with a form that I have to submit to another server using the REST protocol.

I have the following information.

server address
server port
form data

I want to submit that information to the other server.

Is there any function I can use in Drupal 8?

Because of the new Proudly Found Elsewhere standard, Drupal doesn't have its own client.

It does however include Guzzle, a well respected library. You can use that to make your REST calls, or of course include and use another library if you wish.

You can get to the Guzzle client in a default Drupal 8 install through the http_client service:

$httpClient = \Drupal::httpClient();

And the docs for Guzzle are here.


How to simulate radio button functionality within a form I have a form which has 3 radio buttons, each providing a fieldset.

o Choice 1
  Fieldset of options v
o Choice 2
  Fieldset of options v
o Choice 3
  Fieldset of options v

In order to achieve this, the three radios are each individual radio buttons, and the fieldset for each is enabled when the radio is checked.

The problem, of course, is that once checked, checking one of the other radios doesn't uncheck the original, because they are different fields. I could use #states to simulate radio behavior, clearing one when another is selected, but I don't believe that will work. If I set Option2 to clear if Option1 is checked:
  Checking Option2, then checking Option1 will clear Option2, great
  Trying to check Option2 again will leave it unchecked, because the test of whether Option1 is checked will be true

I tried this setting for two of them:

  '#states' => array(
    'unchecked' => array(
      ':input[name="*theOtherOption*"]' => array('checked' => TRUE),
    ),

What happens is the behavior works for the first click of each radio button, clicking 1 turns off 2, clicking 2 turns off 1, and then it stops working and I end up with both clicked.

you should study the Ajax examples module you can follow the examples estructures to build you own code.
 After doing that your code should look somethink like this:

function test_code_radios_callback($form, $form_state) {
  return $form['radios_fieldset'];
}

function test_code_form($form, &$form_state) {

    $options = array(
        'Name'=>t('Name'),
        'Nickname'=>t('Nickname'),
        'Lastname'=>t('Lastname')
        );

    $form['alias'] = array(
    '#type' => 'radios',
    '#title' => 'Choose your alias',
    '#options' => $options,
    '#default_value' => isset($form_state['values']['alias']) ? $form_state['values']['alias'] : '',
    '#ajax' => array(
      'callback' => 'test_code_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
        ),
  );

    $form['textfields'] = array(
    '#title' => t("Your Alias"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('Write your alias here'),
  );

    if (!empty($form_state['values']['alias']) && $form_state['values']['alias']) {
    $value = array();
    $value = $form_state['values']['alias'];

    foreach($value as $item) {
    $name = $item;
    }

      $form['textfields']['$value'] = array(
      '#type' => 'textfield',
      '#title' => $value,
      );

  }

  return $form;
}
function test_code_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

I tested and it's working as i understood you need it. Tell us how it went. Have a good coding!.


Mocking Settings (settings.php) within Unit tests Drupal's Settings class is marked final and has no interface, meaning traditional PHPUnit mocking techniques will not work out of the box. Is it necessary to install third-party tools to be able to mock this or is there another way?

At first glance Settings appears to be read-only, however the constructor is quite forgiving in its parameters. We can construct a fake settings structure like so:
$site_settings = [
  'http_services_api' => [
    'auth_services' => [
      'title' => 'Auth Services',
      'config' => [
        'base_uri' => 'https://demo.api-platform.com/auth'
      ],
    ],
    'resource_services' => [
      'title' => 'Resource Services',
      'config' => [
        'base_uri' => 'https://demo.api-platform.com/books'
      ],
    ],
  ],
];

new Settings($site_settings);

This is alluded too here but never fully described.
Edit: I have added an example to the docs linked.


What are some examples of filter Correct faulty and chopped off HTML? In Drupal one of the text filters that is enabled by default is the filter Correct faulty and chopped off HTML. As I understand it must fix HTML bugs.

Can anybody please give some example(s) of situations, where it can help?

I am confused, because if I do not close some tag (for example DIV), and save the result, then I get the same result in both cases (= it doesn't matter if that filter is turned on or off).

In Drupal, there is rule that a text filter should never change anything that the user saves.  The "Correct faulty and chopped off HTML" follows this rule. That is why you don't see any changes in the body field when you edit.

However, the filter will fix your HTML when the text in the body field is rendered (i.e. displayed to the user).

For instance, if you use the Drupal 6 or 7 "Filtered HTML" text type (which makes use this filter) and put the following faulty and chopped off HTML in the body (this is all you put in the body of a node):

xyzzy

and examine the rendered HTML in your browser (for instance using Ctrl-U or Firebug in Firefox), you'll see that it is corrected to:

xyzzy

Screen shots

Text in editor:

Rendered text, as displayed by Firebug:


How to print a field content link in the views-view-field template in Drupal 7? I am trying to figure out if it is possible to print the content link of a field in the Views' template.

I would like to link an article title to its node, something like the following code:

print '' . $article['und']['0']['value'] . ''

This is a dumbed down version of my code in the view-view-field--field-article-title.tpl.php

$article = $row->_field_data['nid']['entity']->field_article_title;
$subtitle = $row->_field_data['nid']['entity']->field_article_subtitle;

if (isset($subtitle['und']['0']['value'])) {
  print $article['und']['0']['value'] . ': ' . $subtitle['und']['0']['value'] . '
';
}
else {
  print $article['und']['0']['value'];
}

Can anyone point me in the right direction? I've tried printing out the available fields, but for some reason I cannot print the fields in the view.

I'm not an expert and this may not be the absolute best way, but it works for me in D7 view-view-field templates.

Include something like this in your template file

<a href="<?php print base_path().drupal_get_path_alias("node/{$row->nid}") ?>">...


Body content appears to anonymous viewer but not to site admin In Drupal 7, on my front page, when logged in as admin, the node's content is not rendered.

However, when I log out, I can see content

This only occurs on one content type (called Front Page). No other content type mimics this behavior.

We're using Responsive Premium as our base theme, of which it is based on omega.

Is there a permission that I have forgotten about?

Check the field permissions in your content type. If you added custom permissions to a field and did not grant admin role access, the node will not be displayed.

By "admin" do you mean uid1 superuser or user in a role named "admin"