Code for page access I would like to use PHP code in nodes of a specific content type. I can check the user's permission with the global $user if the user can access the node.

Is there any module to set view for created page content?
Is it secure to check page access with this code?

global $user;

// Check to see if $user has the administrator role.
if (in_array('administrator', array_values($user->roles))) {
  // Do something.
}

I think you are looking for a node access module. There are many of them, for example http://drupal.org/project/content_access (configure access with roles directly) or http://drupal.org/project/tac_lite (control access by adding special taxonomy terms) and many more.

For your second question, you should always define some permissions (with hook_perm in D6, hook_permission() in D7) and then check that. That allows to configure through the UI, which roles have that permission and the code is not tied to your specific configuration.


Conflict between package requirements when updating to Drupal 8.4 When running composer update, I get the following error:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: symfony/yaml[3.2.x-dev, 2.8.x-dev].
    - Can only install one of: symfony/yaml[v2.8.0, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.0-BETA1, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.1, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.10, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.11, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.12, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.13, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.14, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.15, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.16, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.17, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.18, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.19, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.2, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.20, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.21, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.22, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.23, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.24, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.25, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.26, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.27, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.28, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.3, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.4, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.5, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.6, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.7, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.8, 3.2.x-dev].
    - Can only install one of: symfony/yaml[v2.8.9, 3.2.x-dev].
    - Can only install one of: symfony/yaml[3.2.x-dev, v2.8.28].
    - drupal/core 8.4.0 requires symfony/yaml ~3.2.8 -> satisfiable by symfony/yaml[3.2.x-dev].
    - Installation request for drupal/core 8.4.0 -> satisfiable by drupal/core[8.4.0].
    - Installation request for symfony/yaml ~2.8 -> satisfiable by symfony/yaml[2.8.x-dev, v2.8.0, v2.8.0-BETA1, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19, v2.8.2, v2.8.20, v2.8.21, v2.8.22, v2.8.23, v2.8.24, v2.8.25, v2.8.26, v2.8.27, v2.8.28, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].

I've seen a few explanations for similar errors, but I can't figure out how to fix it. I assume it has something to do with incompatibilities between yaml versions. How do I go about solving this?

So, I've found a solution. I had to go into my composer.json file and specific these versions under require:

"drupal/core": "~8.4",
"drush/drush": "~9.0",

Once I updated those lines, I deleted the composer.lock file as well as the vendor directory. After that, I was able to install Drupal 8.4 using composer update --with-dependencies.


How to read-modify-write a multivalue entity-reference field I have some D8 entity code that does read-modify-write on a multivalue entity-reference field. The modification required is to change references to one entity to refer to another, without changing other references.

I get an exception thrown in $entity->set(...) saying that the Value is not an entity. I presume I'm calling the wrong thin somewhere but I don't see what the correct call pattern would be.

What I have at present is, and here $field_values is a EntityReferenceFieldItemList:

  $field = '...';
  $entity = $storage->load(...);

  $field_values = $entity->{$field};
  foreach ($field_values as $k => &$item) {
    $target_id = $item->get('target_id')->getValue();
    if ($target_id === $old_value->id()) {
      $changed = TRUE;
      $item->set('target_id', $new_value);
    }
  }
  if ($changed) {
    var_dump($field_values);
    $entity->set($field, $field_values);
    $entity->save();
  }

where $old_value and $new_value are both EntityInterface objects and $field_values is an EntityReferenceFieldItemList.

foreach (entity->get($field) as $k => $item) {
    $target_id = $item->target_id;
    if ($target_id == $old_value->id()) {
      $changed = TRUE;
      $item->target_id = $new_value;
    }
  }

  if ($changed) {
    $entity->save();
  }

That's it. You don't need to set any values, they are objects, your loop already updates them. You also don't need to loop over it by reference.

I just simplified it a bit because you can access target_id as a property through __set() and __get(), which has the advantage that you directly get the value and don't need to call getValue() on it.

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more information for example.


How to add google translate to comments I want to be able to have the ability to translate to comments only , is there any type of module I could use for this

Use the [Automatic] Comment Translation module

  Comment translation utilizes the Microsoft Translator to create translations of submitted comments on nodes that have existing translations available. Translated comments are placed in moderation for review.


Mixed public/private file upload In Drupal 6, the Private Upload module allows you to specify that a node file attachment should be stored in the private file system, so that it is not directly accessible by URL. There is a checkbox that toggles public/private.

In Drupal 7, some of this functionality has been moved into core. When you create a File field, you specify whether it uploads into the public or private file system. However, you cannot toggle public/private on each upload.

So what would be the best way in Drupal 7 to be able to specify that some file attachments be be in the public file system, and some be private? I could create two kinds of file fields, public and private, and have each node type have both kinds of file fields. Or I could have separate (though probably otherwise identical) public and private node types, with corresponding file fields. Both ways are awkward.

Any modules that would help with this that I have missed? (I put in a core feature request for a public/private toggle in the field, but that won't help in the short term.)

What you want is to build a custom widget for the file field type, that has a checkbox that says "this file should be private". Drupal 7 natively handles per-file public/private upload, so at this point it is nothing more then a UI issue.

It has been stated that Private Upload will not be ported to Drupal 7, but I think this is wrong. It should be ported and provide two features:

An upgrade path from the custom, hackish, storage of private files in Private Upload to proper private files (this is not going to happen by magic)
A custom widget that allows the user to choose between public and private during upload


Drupal 7: Display latest articles by an author with bio I have a content type called "Author" and have an author field on other content types which has a reference to the "Author" CT. (e.g. News Article having an author field)

The "Author" CT has these fields:

Title (Author Name)
Image
Bio

I'm using Panels on Drupal to create pages and I want to display Author pages like /author/author-name with Views, Panels, etc to display the Author name as Title of the page, author image and bio on top and the latest nodes by that author below all that bio.

I've created a view called Author with a contextual filter Content: Author but I'm unsure about how to use this on a Panel.

How do I go around this process to embrace panel pages and views to create author pages?

If you create a views panel pane (available as a views display mode) and place that with panels, then you can accept arguments from the panels context when editing the view. The display will have panels argument options controls that other display modes do not offer.


How do I programmatically render a menu's label? I'm trying to render out a menu with its label in Drupal 8. I am able to get the menu and its links inside of a preprocess function using a helper function, but I can't locate the menu's title.

Here is how I'm getting the menu. I'm able to add the return value as a twig variable $variable['menu']['menu-name'] and render out an <ul> anywhere I need to.

function get_menu($menu_name) {
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = $menu_tree->load($menu_name, $parameters);
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);
  $menu = $menu_tree->build($tree);

  return array('#markup' => drupal_render($menu));
}

Here is the snippet to change the menu name:

 function example_preprocess_menu(&$variables) {
      $element = &$variables['items'];
      foreach ($element as &$item) {
        if ($item['original_link']->getMenuName() == 'menu-machine-name') {
        //For the menu label
       $menu = entity_load('menu', 'menu-machine-name');
          $menu_label = $menu->label();
          if ($item['title'] == 'Example menu') {
            $item['title'] = 'New menu name';
          }
        }
      }
    }


Allow editing of only a single field of a node in Panels or a block I am working with drupal 7. I have organic groups and cck set up. I want users to be able to only edit the group audience field in an organic group but nothing else. Is there a way where I can only add a group audience edit field to a panel or a block ?

I looked at the form block module, but that provides access to the complete content edit page.

Thanks.

Try the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you allow your users access to the group edit form, they will only see the fields that you have selected to be editable using Field Permissions.

Use that in conjunction with the form block module as you've suggested and you should get the effect that you're looking for.


Multilingual views hide if no translation My Drupal website has 2 languages and I created blog view that lists articles (content type). Default language is English.

Problem is that some articles are only in German and then on my English view I get German articles.

I tried adding Content: Translation language Filter that I set to Interface text language selected for page but then on German page I only get articles that were created on German and the ones that were created in English but have German translation are missing.

Query :

SELECT node_field_data.created AS node_field_data_created,
node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_content_type} node__field_content_type ON
node_field_data.nid = node__field_content_type.entity_id AND
(node__field_content_type.deleted = '0' AND
node__field_content_type.langcode = node_field_data.langcode)
WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN
('article')) AND (node__field_content_type.field_content_type_value = '1')
))
ORDER BY node_field_data_created DESC
LIMIT 5 OFFSET 0

Query with Translation language filter:

SELECT node_field_data.created AS node_field_data_created,
node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_content_type} node__field_content_type ON
node_field_data.nid = node__field_content_type.entity_id AND
(node__field_content_type.deleted = '0' AND
node__field_content_type.langcode = node_field_data.langcode)
LEFT JOIN {node__field_tags} node__field_tags ON node_field_data.nid =
node__field_tags.entity_id AND node__field_tags.field_tags_target_id = '4'
WHERE (( (node__field_tags.field_tags_target_id IS NULL) )AND((
(node_field_data.status = '1') AND (node_field_data.type IN  ('article'))
AND (node__field_content_type.field_content_type_value = '1') AND
(node_field_data.langcode IN  ('en')) )))
ORDER BY node_field_data_created DESC
LIMIT 5 OFFSET 0

From queries, I see that LEFT JOIN is adding node__field_content_type.langcode = node_field_data.langcode and I think that is making problems when I add the language filter, any suggestion?

The problem was that I was doing condition in views with field that wasn't translatable and views are adding join on langcode, thanks to user 4k4 that linked to this issue that can be found here.

I fixed this by removing untranslated field from view and hooking into hook_views_query_alter and adding relationship myself :

<?php

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

function hook_views_query_alter(ViewExecutable $view,
QueryPluginBase $query)
{
    if ($view->id() == 'blog') {
        $definition = [
            'table' => 'node__field_content_type',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
        ];
        $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
        $query->addRelationship('node__field_content_type', $join, 'node__field_content_type');
        $query->addWhere('1', 'node__field_content_type.field_content_type_value', 1, '=');
    }
}

Also this hook has to be in MODULE.views_execution.inc file


Sending smtp email using mail() I have installed and configured https://www.drupal.org/project/smtp module
sending test email works fine, but when sending email with code nothing is sent and also no log in drupal (I have enabled debugging)

    $ownerEmail = 'email@someemail.com';
    $subject = 'update';
    $msg = 'You case has been updates';
    mail($ownerEmail,$subject,$msg);

mail() is a PHP function, that will never use SMTP.

You need to use the drupal mail manager and its mail function. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Mail%21MailManager.php/function/MailManager%3A%3Amail/8.4.x and the example code ther.


How do I add a class to a row based on the value of a field in that row? I have a view with a page display showing a list of events. I'd like to add a class to the rows of those events that are in the past.

The problem I have is that views-view-list.tpl.php doesn't have access to the values of fields within the rows.

And I can use views-view-fields.tpl.php to check the date field of one row, and wrap each field in that row with a div or span based on whether or not the date field is in the past.

I just can't figure out how to use the value of a field within a row to wrap the whole row in something with a class.

The following will add the class 'hello' to the li tag. I used a view with machine name 'dates' and a display name of 'page'. The time field is the node created time. You can just install Devel and uncomment the dpm($vars) statement to get what you need. I also left the conditional logic up to you.

Put this in your theme's template.php file:

function MYTHEME_preprocess_views_view_list(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    // dpm($vars); //uncomment to see variables
    foreach($vars['view']->result as $key => $value){
      $timestamp = $value->node_created;
      if ($timestamp) { // add whatever conditional logic you need here
        $vars['classes_array'][$key] .= ' hello'; // note the space in front of class
      }
    }
  }
}

An alternative method is as follows:

Put this in your theme's template.php file:

function MYTHEME_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'dates' && $vars['view']->current_display == "page") {
    $timestamp = $vars['row']->node_created;
    if ($timestamp < strtotime('now')) {
      $vars['classes_array'][] = 'bye';
    }
  }
}

and use this views-view-fields--VIEWNAME.tpl.php file:

<div class="<?php print $classes;?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
  <?php print $field->label_html; ?>
  <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</div>


Css redirect to other css file after logging out. Bug? I have styled the class .tab-content and it works fine whenever i logged in, but i logged out then the css file is changed to a different file as you can see on the screenshoots below. I have ran drush cc all and drush cron as well as I don't have boost module installed. Do you have any idea to fixed this?

when i login

when i logout

Drupal serves aggregated CSS. If one or more CSS files are not available (or required) for anonymous users they are not included in the aggregated file for the sake of a smaller file size. This file can obviously not be saved with the same name.

If you disable CSS aggregation (Configuration > Performance), you can see all individual files and this might explain the difference.


Which Rules Event should I use to trigger a Rules Action when accessing a particular Views page? I have a Views page, located at, say, www.example.com/entrepreneur.

When a user accesses that particular url, I want some rule to be executed.

I've looked at the Rules admininistration page to find out what exactly I should use as (the mandatory) "React on event", which looks like so:

But I am not able to find "page is viewed", but I need to execute the rule when user accesses the particular single page.

Any suggestions?

You need to download Rules module ,Rule_link module Token module

Enable Rule and Rule link and Token module
Go to /admin/config/workflow/rules_links
Add a new rule_link, Give the rule label and all other required field
Click on Configure rules tab and in access conditions you can add your conditions


My php is showing a numeric value for my list field...Why? In a form I'm trying to take a value a user selected from a radio button and compare it with what's in the database. The value for the radio button is stored in $form_state['storage']['level'].

The list field in my resource type for this set of items is set as follows:

Novice|Novice
Experienced|Experienced
Professional|Professional

And yet, when I echo out the value in $form_state['storage']['level'] it just gives me what appears to be the delta and not the value of the field. Would someone please enlighten me as to how the value is obtained in php code?

Try using $form_state['values'] instead of $form_state['storage'].

Check out the $form_state keys for a bit more information.


How to add Login menu to the first sidebar (secondary menu) I need to remove from the 'secondary menu' the login/logout menu from the header, and display in the first sidebar,

It doesnt seem to be as easy as just draging and dropping in blocks,

Try turning off the secondary menu (admin/structure/menu/settings).

Then, on the blocks admin screen (admin/structure/block), place the User menu in the first sidebar.


How to make same javascript code work on more than one same kind of field? I am using Field collection module and added some repeated fields. Each field has one button, on clicking the button, the text area is expands(toggling kind of). But the java code is working for only first field not for rest of the fields. I have added java script code through .info method. Thanks.

(function ($) {
     Drupal.behaviors.myfunction = {
         attach: function(context, settings) {
            $( "#button1" ).click(function() {
              $( "#p1" ).toggle("slow");
            });

 }}})(jQuery);

Hmmm, this is a kind of tricky one! Because you want the element corresponding to the button you clicked to be the only one that toggles, correct? Not all of the elements?

I think you want something like this for your code, where everything between [] is replaced with the relevant selector. So [BUTTON CLASS] would become the class that you apply to all the buttons, such as "button", not the ID that only gets applied to a single button ("button1", "button2", and so on). Likewise, [CHILD CLASS] would be replaced with a class that you apply to all elements that you have IDs such as "p1", "p2", etc on.

(function ($) {
  Drupal.behaviors.myfunction = {
    attach: function(context, settings) {
      $( ".[BUTTON CLASS]" ).each(function (index) {
        $(this).click(function() {
          $(this).parent().children(".[CHILD CLASS]").toggle("slow");
        });
      });
    }
  }
})(jQuery);

Hope that helps!

Edit
Updates made to the code to get the button parent and then the #p1 from there. It assumes that the #p1 and the #button1 are both children of the same element.

Edit 2
Given the structure

<button class="button1">Toggle</button>

<button class="button2">Link</button>

Text to be written here

<button class="button1">Toggle</button>

<button class="button2">Link</button>

Text to be written here

<button class="button1">Toggle</button>

<button class="button2">Link</button>

Text to be written here

The following JS does what you want, I believe:

$( ".button1" ).each(function (index) {
  $(this).click(function() {
    $(this).parents('.buttoncontainer').children(".p1").toggle("slow");
  });
});


How do I attach a link or image to a radio/select input element I want to attach an image-link to every input element.
Is it possible to do it on entity fields or on webform fields?
I prefer to it on server side.

ok, so then you need two parts both stored in a custom module:

an admin interface where the client can upload images for each relevant form element. Use drupal_get_form('FORM_ID') and loop through the form elements. Create a new admin form with image form elements corresponding to the webform elements. save the images and create a mapping table mapping the image urls to the form elements.
an invokation of hook_form_alter() adding prefixes to the webform elements as stored in your mapping table.


Module Uninstall Validators and Lazy Services I have recently been working on creating functionality for a module that requires certain content related to the module be deleted before the module itself can be uninstalled.
https://www.drupal.org/project/commerce_pos/issues/3006353

I used an example for core's book module where I saw that a service called module_install.uninstall_validator and a ProxyClass called BookUninstallValidator were used in order to implement functionality similar to what I was attempting to achieve.

My question is thus: why is the module_install.uninstall_validator set to lazy and what exactly is a proxy class?

I have searched in the documentation but have been unable to find any useful explanation; so any here or links to such pages would be much appreciated.

It's a property of services classes provided by Symphony's dependency injection framework. Per its docs on lazy services:

In some cases, you may want to inject a service that is a bit heavy to instantiate, but is not always used inside your object. For example, imagine you have a NewsletterManager and you inject a mailer service into it. Only a few methods on your NewsletterManager actually use the mailer, but even when you don’t need it, a mailer service is always instantiated in order to construct your NewsletterManager.

In other words, proxy classes are quick-loading dummy stand-ins until the actual class methods are needed to do the heavy lifting. In this specific case, the Book uninstall validator isn't useful until it's needed during the book module uninstall so there's no need to fully instantiate the validator service.


Is it possible to limit which products users can purchase by role? I have three products, A B and C. Anyone can buy products A or B, but only users with the VIP role should be able to buy product C.

How can I make sure users don't see product C if they don't have the VIP role?  (It would be best if they could not buy it at all, but I will settle for a solution that simply hides it.)  My products are displayed in a view using a Product display content type.

You should create an additional "VIP ONLY" product display - a node type that aggregates products and effectively shows them in the front-end.

With this new content type you could tap into its permission system using Content Access and limit the "View" permission to the "VIP user role".

When you want to create a VIP product simply create a new "VIP ONLY" node.

Steps:

Create a new node type in admin/structure/types . Call it "VIP ONLY".
Add a product reference field to the node. Use the existing field. It will now be listed in views that list product display types.
Setup the permissions as per above.
Profit.


How to display a colorbox only one time when a page loads I have created a colorbox effect to show the login form when the home page loads using the following jQuery code:

jQuery(document).ready(function() {
  jQuery.fn.colorbox(
    {href:"user/login/colorbox",open:true}
  );
});

Now I want to do the same to display a registration form, but this registration form should only be displayed one time.

Please can any one help me find a solution..

I would suggest writing a cookie after showing the login form and checking if the cookie exists before that. For cookies there's a nifty jquery plugin as well - no big programming involved on your side.
HTH


Custom field type with imagefield I'm creating a widget with an image field. But I keep writing 0 to the database. But i need the fid to be saved. I know I can manipulate the data with hook_field_presave(). But the items array only contains image => '0'.

mymodule.module

/**
* Implements hook_field_widget_form().
*/
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
...
  $element['image'] = array(
    '#type' => 'managed_file',
    '#name' => 'mymodule_custom_image',
    '#title' => t('Image'),
    '#size' => 40,
    '#description' => t(""),
    '#upload_location' => 'public://',
    '#theme' => 'mymodule_custom_thumb_upload',
  );
...
}

Edit:

/**
* Implements hook_field_widget_info().
*/
function mymodule_field_widget_info() {
  return array(
    'mymodule_polygone_widget' => array(
      'label' => t('Default'),
      'field types' => array('mymodule_polygone'),
    ),
  );
}

mymodule.install

/*
* Implements hook_field_schema().
*/
function mymodule_field_schema($field) {
  $columns = array(
    'image' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
    'zones' => array('type' => 'text'),
  );

  return array(
    'columns' => $columns,
    'indexes' => array(),
  );
}

Found it: Forgot the 'input ...' in my custom theme function :).

function theme_mymodule_thumb_upload($variables) {
  $element = $variables['element'];

  if (isset($element['#file']->uri)) {
      $output = '

';
      $output .= 'uri) . '" />';
      $output .= '<input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
      $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

      return $output;
  }
}


Drupal 7 prepopulate form values for embedded field collection I need to prepopulate my embedded field collection values in a specific form.
Here is what I've got so far:

<?php
// Hook form alter
function mp3_template_form_alter(&$form, &$form_state, $form_id)
{
  // Pre fill profile mp3 form with mp3 template data
  if (isSet($form_id) && $form_id == 'profile_mp3_node_form')
  {
    global $user;
    $user_full = profile2_load_by_user($user->uid, 'artists_profile');

    // Get field collection entity ids from the user
    $entity_ids = $user_full->field_copyrights_mp3[LANGUAGE_NONE];

    // Load field collection entities
    $entities = entity_load('field_collection_item', $entity_ids);

    // Here I want to prepopulate the $form['field_copyrights_mp3'] form field with my collection items that contain the data for field_copyrights_mp3
    $form['field_copyrights_mp3'][LANGUAGE_NONE][0] = $entities[0]; // 1 field collection
    $form['field_copyrights_mp3'][LANGUAGE_NONE][1] = $entities[1]; // 2 field collection
    // etc...
  }
}

I have searched a lot and tried multiple approaches to prefill my field collection with multiple rows of data. Hopefully someone can point me into the right direction of what I should do next.

Image of what I'm trying to prepopulate with multiple owners:

you can use the MODULENAME_form_alter hook to achieve this, by iterating through its nested array, maybe this can help

If this help, awesome, ping me if not, I can share some snippets that achieve that :)


The meaning of update.php pending updates I have replaced Drupal 7 core files from version 7.10 to 7.12. Now I am running update.php and it displays 3 pending updates, e.g.:

  menu module
  7003 - Add missing custom menus to active menus list

How do I get more information what this means exactly? I checked the site with release notes for Drupal 7.12, but there is no such string (7003) in that list.

It's part of menu_update_7003(). The comments in that function say it all really:

Make sure all custom menus are present in the active menus variable so that their items may appear in the active trail.

Usually just searching Google for the exact message in quotes (e.g. "Add missing custom menus to active menus list") will bring up the page that explains why it's been done (that's what I did to find this out). You can most likely do the same for the other two updates and find out exactly what they're doing.


Is it possible to use theme_table on each key of array? I know theme_table only accepts rows when $row=array(); I have an array like:
Array(
[0] => 'one',
1 => 'two',
)
Is it possible to have table rows as 'one', 'two', etc...
I mean, first row will be 'one',
second row will be 'two'.

How can I achieve this?

After few minutes, I realized it was so simple.

$rows[] = array('data' => array($row));

where $row wasn't array, it is array key.


Field collection 'add more' and 'remove' hooks? I am currently working on a project where i have a content type that has 2 field collections. (with cardinality 1)
Each field collection has one other field collection (with unlimited cardinality).

To summarize:

Content type X

Field collection 1

Some fields
Field collection A (unlimited cardinality)

Field collection 2

Some fields
Field collection B (unlimited cardinality)

Now,

I want field collection A and B to respond to each others "add item" and "remove" actions.
So that when you add an item to field collection A, automatically an item to field collection B is added as well and vice versa.

Are there any hooks available for this?

I have been doing some research but there is very little documentation about this that i can find.

Thanks so much in advance!

I managed to solve this with some jQuery.

Not sure if this is the "cleanest" way to do this, but it works. I hook into the mousedown() event of the "add another item" button,and trigger the other button's mousedown manually.

I also added a delay of 800ms, because of some conflicting events if the 2 mousedowns are too quickly after eachother.

Hope this helps anyone in the future.

$('#edit-field-pressure-calculation-und-0-field-pressure-calculation-line .clearfix .field-add-more-submit').mousedown(function() {
    setTimeout(function() {
      $('#edit-field-heat-calculation-und-0-field-heating-calculation-line .clearfix .field-add-more-submit').mousedown();
    }, 800)

  });


Varnish 3.0 and Drupal 7, get registered user to always have non-cached content I have issue with Varnish on Drupal 7 detailed here: http://drupal.org/node/1886218

Basically, what happens is:

User visits the certain page as anonymous, gets content served by Varnish Cache (OK)
Logs in
Clicks the link of the page that he visitied as anonymous previosly, but he gets cached page, instead of user-specific (that should not happen)
If he reloads page (f5), he gets backend served page, but if he clicks that link on the menu, he gets cached page.

It turns out that cached page was delivered by browser, not by Varnish; anyway, that should not happen, because user thinks he is logged out (I have user specific block in header).

How i can deliver such cache-control in header, so Registered users always get updated (not cached) content, even if they browsed site as anonymous before they have logged in ?

Thanks for help!

HTTP response:

The url we checked: www.mydomain.com
    HTTP/1.1 200 OK
Server: Apache (removed from security)
X-Powered-By:   PHP(removed from security)
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:  Tue, 15 Jan 2013 08:38:54 +0000
Cache-Control:  public, max-age=10800
ETag:   "1358239134-1"
Content-Language:   hr
X-Generator:    Drupal 7 (http://drupal.org)
Link:   <http://www.mydomain.com/>; rel="canonical",<http://www.mydomain.com/>; rel="shortlink"
Vary:   Accept-Encoding
Content-Encoding:   gzip
Content-Type:   text/html; charset=utf-8
Content-Length: 33254
Accept-Ranges:  bytes
Date:   Tue, 15 Jan 2013 08:49:22 GMT
X-Varnish:  1420616326 1420614128
Age:    622
Via:    1.1 varnish
Connection: keep-alive
X-Varnish-Cache:    HIT

You seem to be missing Vary: Cookie in addition to Vary: Accept-Encoding. You may add it in vcl_deliver using something like this:

if (resp.http.Vary !~ "Cookie") {
    set resp.http.Vary = resp.http.Vary + ", Cookie";
    set resp.http.Vary = regsub(resp.http.Vary, "^,\s*", "");
}


Accessing Drupal.settings outside of attach function I'm trying to make some of my Javascript in a Drupal 7 module a bit more modular, as I want to access a function inside Drupal.behaviors.attach() from another JS file. So first of all I need to move some variable declarations, and then the functions, outside of the attach function and hopefully access the variables from inside it with this.vars.myVariable - I'll try and explain a bit further with some slightly dummified code...

Initial, working code:

(function($) {
  Drupal.behaviors.myModule_someJS = {

    attach: function(context, settings) {

      var initial_page = Drupal.settings.myModule.initial_page;
      console.log(initial_page); // returns a value

    }
  }
})(jQuery);

However, this doesn't work:

(function($) {
  Drupal.behaviors.myModule_someJS = {

    vars: {
      initial_page : Drupal.settings.myModule.initial_page
      // Uncaught TypeError: Cannot read property 'initial_page' of undefined
    },

    attach: function(context, settings) {

      console.log(this.vars.initial_page);

    }
  }
})(jQuery);

It seems that outside of the scope of the attach function, Drupal.settings doesn't exist. Is there any way I can access these settings (defined in my .module file) from anywhere within behaviors.myModule_someJS ?

Thanks! Matt

Worked it out myself.

(function($) {
  Drupal.behaviors.myModule_someJS = {

    anotherFunction: function() {
      console.log(this.vars.initial_page);
    },

    attach: function(context, settings) {

      this.vars = {
        initial_page  : Drupal.settings.myModule.initial_page
      }

      this.anotherFunction();

    }
  }
})(jQuery);

Drupal.settings won't contain the custom stuff sent through from my module until the attach function is called, so therefore every settings variable can only be called inside attach()

(and from Alice's comments above, it may be a matter of drupal_add_js being called from within the page rather than in the init() hook)


How to embed node edit form on page? module_load_include('inc', 'node', 'node.pages');

$form_id = 'reviewer_rating_node_form';

global $user;
$rating_id = views_get_view_result('get_rating', 'default', $nid, $user->uid);

// Rating hasn't been created yet. Create one.
if (empty($rating_id)) {
    // add node properties
    $newRating = new StdClass;
    $newRating->type = 'reviewer_rating';
    $newRating->title = $user->name . "'s rating of " . $nid;
    $newRating->uid = $user->uid;
    $newRating->created = strtotime("now");
    $newRating->changed = strtotime("now");
    $newRating->status = 1;
    $newRating->comment = 0;
    $newRating->promote = 0;
    $newRating->moderate = 0;
    $newRating->sticky = 0;

    // add CCK field data
    $newRating->field_rating_application[0]['nid'] = $nid;
    $newRating->field_rating_reviewer[0]['uid'] = $user->uid;

    // save node
    node_save($newRating);
}

$rating_node = node_load($rating_id[0]->nid);

$output = drupal_get_form('reviewer_rating_node_form', $rating_node);
return $output;

This isn't working for me. If I dpm $rating_node it looks correct, but when I call drupal_get_form I get this error:

Fatal error: Cannot unset string offsets in includes\form.inc on line 498

If I log the $form variable at that line it's a string that starts with this:

Aform action="/devsite/node/423"  accept-charset="UTF-8" method="post" id="node-form" enctype="multipart/form-data">
<div>

That "A" instead of a "<" might be a clue. I have no idea.

Any suggestions on what I'm doing wrong here?

Why don't you use Editview module? You can create an editview with a block display and show it on your page to edit your nodes from there.


How to allow visitors add option in poll? I would like to have a poll for logged in and anonymous users to vote.
In the poll, users are allowed to add in their own poll option and vote. (Just like how Facebook poll is working previously)

Is there any drupal way which I can do this? Or I need to use some combination of ways to achieve this?

Advanced Poll

Advanced Poll is a replacement to Drupal's poll module and provides
multiple voting systems, decision-making tools, and management
options.

Then in permissions (/admin/people/permissions), allow anonymous and authenticated users to vote and add write in votes.


How to properly add multiple form elements in a loop? I have a form where I need to loop through an array and display multiple form elements in a specific area.

Example:

$form_layout = 'Some html';
$form_layout .= '
';

foreach($something as $key => $value) {
    $form_layout .= 'some html';
    $form_layout .= 'some html';

    // I need this to be displayed in between the above and below code
    // in the layout
    $form['awesome_element'] => array(
        '#type' => 'textfield',
        '#size' => 5,
        '#value' => 0
    );

    $form_layout .= 'some html';
    $form_layout .= 'some html';
}

$form_layout .= '
';
$form_layout .= 'Some html';

$form['some-other-awesomeness'] = array(
    // ...
    '#prefix' => $form_layout,
);

Doing it like the example puts the textfields after all the other page elements. I have tried using #prefix and #suffix but that breaks the layout even worse.

Any ideas on what I should do?

Edit: For clarity...

If I had layout elements such as a div tag I need my form elements, such as textfields, to be inserted in between those div tags.

So I need it to output something like this:

FORM ELEMENT
FORM ELEMENT
FORM ELEMENT

Instead it is outputting something like this:

FORM ELEMENT
FORM ELEMENT
FORM ELEMENT

Hopefully that is more clear, sorry if the above is confusing. Looking at code for the last 20 hours.

Edit2: added some visual stuff to make it easier to understand

Could you do something like the following:

$form['openingdiv'] = array(
  '#markup' => '<div>'
);

//Do all your foreach stuff here

$form['closingdiv'] = array(
  '#markup' => '</div>'
);

(Sorry it's a bit simple..I'm tired :-p)


How to update a field value for a node? I want to change the value of a field for a node.I used the following code:

$node = node_load($nid); // $nid is the function's parameter
$node->field['field_myfield'][$node->language][0]['value'] = 1;
node_save($node);

The problem is $node->language returns es while in print_r($node) it's und.
Why $node->language is different from what's in $node array and how can I get it?

$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_myfield->set(1);
$node_wrapper->save();

Entity metadata wrapper is a great way for set or read values of fields in the node!


Submit form after custom submit handler I'm trying to create my first module which essentially is a visitor sign-in system where each visitor is stored as a custom content type.

The user will be a visitor to our building who's able to input their name and who they are here to see (autocomplete field based on taxonomy terms). My custom module will then add a timestamp to the node, as well as email the person they are here to see.

Code is below:

function visitor_email_staff_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'visitor_sign_in_node_form'){
        $form['actions']['submit']['#submit'][0] = 'visitor_email_staff_my_custom_submit_handler';
    }
}

function visitor_email_staff_my_custom_submit_handler($form, &$form_state){

    $guestName = $form['field_visitors_name']['und'][0]['value']['#value'];
    $staffName = $form['field_tags']['und']['#value'];
    $visitorTitle = $guestName.' - '.time();

    $staffTaxonomy = taxonomy_get_term_by_name($staffName);

    foreach ($staffTaxonomy as $email) {
        $staffEmail =  $email->description; // email address
    }

    $form_state = array();
    $form_state['values']['title'] = $visitorTitle;
    $form_state['values']['field_visitors_name'] = $guestName;
    $form_state['values']['field_tags'] = $staffName;
    $form_state['values']['field_timestamp_in'] = time(); // timestamp
    $form_state['values']['field_timestamp_out'] = '';
    $form_state['values']['op'] = t('Save');

    drupal_form_submit('visitor_sign_in_node_form',$form_state);

}

The major issue I'm having at the moment is getting the data to save and submit... I keep getting the below errors:

Warning: Missing argument 3 for node_form() in node_form() (line 107 of C:\www\xxx\modules\node\node.pages.inc).
Warning: Creating default object from empty value in node_form() (line 115 of C:\www\xxx\modules\node\node.pages.inc).
Notice: Undefined property: stdClass::$type in node_object_prepare() (line 981 of C:\www\xxx\modules\node\node.module).
Notice: Undefined property: stdClass::$type in _node_extract_type() (line 379 of C:\www\xxx\modules\node\node.module).
Notice: Undefined property: stdClass::$type in comment_node_prepare() (line 1298 of C:\www\xxx\modules\comment\comment.module).
Notice: Undefined property: stdClass::$type in menu_node_prepare() (line 568 of C:\www\xxx\modules\menu\menu.module).
Notice: Undefined property: stdClass::$type in _node_extract_type() (line 379 of C:\www\xxx\modules\node\node.module).
Notice: Undefined property: stdClass::$type in node_form() (line 294 of C:\www\xxx\modules\node\node.pages.inc).
Notice: Undefined property: stdClass::$type in node_form() (line 300 of C:\www\xxx\modules\node\node.pages.inc).
Notice: Undefined property: stdClass::$type in node_form() (line 321 of C:\www\xxx\modules\node\node.pages.inc).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7922 of C:\www\xxx\includes\common.inc).

Am I going about this the wrong way? Should I be using something else instead of drupal_form_submit()?

Your close, however, I think there are two changes you'll need to make.

You'll need to add $form_state['bundle'] = "visitor_sign_in"  to your $form_state array()
You'll need to pass an (object) $node as the third parameter to drupal_form_submit.

The changes might look something like this:

function visitor_email_staff_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'visitor_sign_in_node_form'){
    $form['actions']['submit']['#submit'][0] = 'visitor_email_staff_my_custom_submit_handler';
  }
}

function visitor_email_staff_my_custom_submit_handler($form, &$form_state){

  $guestName = $form['field_visitors_name']['und'][0]['value']['#value'];
  $staffName = $form['field_tags']['und']['#value'];
  $visitorTitle = $guestName.' - '.time();

  $staffTaxonomy = taxonomy_get_term_by_name($staffName);

  foreach ($staffTaxonomy as $email) {
    $staffEmail =  $email->description; // email address
  }

  $form_state = array();
  $form_state['values']['bundle'] = "visitor_sign_in";
  $form_state['values']['title'] = $visitorTitle;
  $form_state['values']['field_visitors_name'] = $guestName;
  $form_state['values']['field_tags'] = $staffName;
  $form_state['values']['field_timestamp_in'] = time(); // timestamp
  $form_state['values']['field_timestamp_out'] = '';
  $form_state['values']['op'] = t('Save');

  drupal_form_submit('visitor_sign_in_node_form', $form_state, (object)$node);

}


Add birthday field on user account I want to enable my users to add their birth days in their profile. The users should select the date either from a calendar or insert them in three different fields of day,month, and year manually...The image should make it clear:

I'd just get the Date module and add a date field to the profile called something like field_user_birthday.

  This package contains both a flexible date/time field type Date field
  and a Date API that other modules can use.


Apply discount on checkout when a specific quantity of products are purchased with a specific taxonomy I have Commerce Discount installed that enables me to create a discount on a product with a certain taxonomy. However I only want this discount applied when a customer selects at least three of these products with the taxonomy.

It there a way I can update the rule created with the discount to achieve this?

This has already been logged as an enhancement Add option to specify amount of products that needs to be orderd

But I need to resolve this before my site can go live

Many thanks

I managed to resolve this by adding a condition to the rule that was created by the discount.

And
Total quantity of selected product comparison


Change Workbench state from Draft to Published programatically I would like to do a bulk operation and change nodes from a state of Draft to Published. I created a new revision from a previous change, but all revisions default to Draft. Now I would like to basically just publish the new revision. (I am using the Workbench module.)

I have tried doing things like the below, but none of them seem to work:

$node->workbench_moderation['current']->published = "1";

or

$node->workbench_moderation['current']->from_state = "draft";
$node->workbench_moderation['current']->state = "published";
$node->workbench_moderation['current']->published = "1";

$node->workbench_moderation['published']->from_state = "draft";
$node->workbench_moderation['published']->state = "published";
$node->workbench_moderation['published']->published = "1";

$node->workbench_moderation['my_revision']->from_state = "draft";
$node->workbench_moderation['my_revision']->state = "published";
$node->workbench_moderation['my_revision']->published = "1";
$node->workbench_moderation['my_revision']->current = TRUE;

or

workbench_moderation_moderate($node, 'published');

I've tried saving using the below rather than node_save as well, thinking maybe the node_save triggered a new draft.

workbench_moderation_node_update($node);

I just want to simply load the node, publish the draft, then save it again.

Any idea what I am doing wrong?

There are two solutions which I have found will work:

The First:

$nid = 1234;
$node = node_load($nid);
$node->body['und'][0]['value'] = 'new body';
$node->revision = 1;
$node->log = 'State Changed to published';
node_save($node);
workbench_moderation_moderate($node, 'published');

NOTE: I intentionally put workbench_moderation_moderate() after node_save() because in my case node_save() will trigger a new draft.  After the draft is created, I publish that draft.

The second:

$nid = 1234;
$node = node_load($nid);
$node->body['und'][0]['value'] = 'new body';
$node->workbench_moderation_state_new = workbench_moderation_state_published();
$node->revision = 1;
$node->log = 'State Changed to published';
node_save($node);

I am going with the first solution over the second solution because of the status messages. The first shows the two messages under the current revision:

From Draft --> Published on...
From Published --> Draft on...

whereas the second solution only shows one message which doesn't really make much sense:

From Published --> Published on...


Call Drupal behaviour when AJAX form is submitted? I have a form with an AJAX callback. I need to run some JavaScript when the form is submitted. Ive got this working by following the tutorial below:

http://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7

However I already have a JavaScript file in the module and I would prefer to put my code in there. This file is loaded on page load so I think I would need to listen for an event and run when this was detected. Can I use the AJAX callback to trigger an event thats within a Drupal behaviour?

function after_ajax_form($form, &$form_state)
{
    // First we create a form element with AJAX enabled
    $form['ajax_example'] = array
    (
        '#type' => 'select',
        '#title' => t('Change me'),
        // Note that I am setting the value and the display of the elements to be the same, for convenience sake in our callback function
        '#options' => array(t('Select something') => t('Select something'), t('Something selected') => t('Something selected')),
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array
        (
            'callback' => 'after_ajax_ajax_callback',
            'event' => 'change',
        ),
    );

    // Next we add our JavaScript file, named after_ajax.js. This file
    // lives in the /js folder inside our module:
    $form['#attached']['js'] = array
    (
        array
        (
            'type'  => 'file',
            'data' => drupal_get_path('module', 'after_ajax') . '/js/after_ajax.js',
        ),
    );
    return $form;
}

function after_ajax_ajax_callback($form, &$form_state)
{
    // First, we initialize our $commands array. This array will
    // contain each of the commands we want to fire for our
    // #AJAX callback:
    $commands = array();

    // Next, we create our insert function that will insert our updated content
    // back into the page. To do this, we use the system provided
    // ajax_command_html() function. We pass this function two values:
    // 1) Our AJAX wrapper (that we defined as the #prefix and #suffix of our form element)
    // 2) The rendered HTML that needs to be inserted into the wrapper in the page.
    $commands[] = ajax_command_html('#after_ajax_element_wrapper', render($form['ajax_example']));

    // Next, we will use the system provided ajax_command_alert() function as an example to show it's
    // working:
    $commands[] = ajax_command_alert(t('ajax_command_alert() is working'));

    // Next we will include a custom function that we will call ourselves in our JavaScript file:
    $commands[] = array
    (
        // The command will be used in our JavaScript file (see next section)
        'command' => 'afterAjaxCallbackExample',
        // We pass the value that the user selected in the select element to our
        // JavaScript function:
        'selectedValue' => $form_state['values']['ajax_example'],
    );

    // And finally, we will return all of our commands to the system to be executed:
    return array('#type' => 'ajax', '#commands' => $commands);
}

(function($, Drupal)
{
    // Our function name is prototyped as part of the Drupal.ajax namespace, adding to the commands:
    Drupal.ajax.prototype.commands.afterAjaxCallbackExample = function(ajax, response, status)
    {
        // The value we passed in our Ajax callback function will be available inside the
        // response object. Since we defined it as selectedValue in our callback, it will be
        // available in response.selectedValue. Usually we would not use an alert() function
        // as we could use ajax_command_alert() to do it without having to define a custom
        // ajax command, but for the purpose of demonstration, we will use an alert() function
        // here:
        alert(response.selectedValue);
    };
}(jQuery, Drupal));

AJAX callbacks only return an array of commands, and those commands are then executed by Drupal. It is the method I prefer when dealing with AJAX in Drupal.

Behaviors are attached to every page. If you really want to call the behavior, detached from a Drupal AJAX response, then your behavior needs to react when the form is submitted by attaching to that event without using AJAX event on the submit button of the form. See this answer: https://drupal.stackexchange.com/a/87600/57.

With an AJAX command, you can ensure that your command only executes if the form is validated without messing around with a lot of Javascript - though it depends on what you are doing. If you are showing a modal or some notification to the user about submitting the form, you may want to opt for the command so that you aren't running JS if the form did not really submit (i.e. not validated).

In your case, if you are using AJAX submission, then the submit event won't bubble up to the document. You can use ajax_command_invoke however to call a method. I recently had to do this on an AJAX'd form to push data to Google. Here is an example:

$commands[] = ajax_command_invoke(NULL, 'onFormSubmitSuccess');
return array('#type' => 'ajax', '#commands' => $commands);

Javascript file:

(function($) {
  $.fn.onFormSubmitSuccess = function(data) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      'event' : 'formSubmitted',
    });
  };
})(jQuery);

https://api.drupal.org/api/drupal/includes!ajax.inc/function/ajax_command_invoke/7


Map array of node IDs to bundle types without loading all the nodes For complicated reasons I need to map an array of node IDs to a list of node bundles. That is, for a given list of node IDs, I need to get all the different bundles (node types) of the nodes the IDs belong to. The simple approach would be to load all the nodes, map that to their bundles and using array_unique to get the final list. Unfortunately, this is not a good solution because there may be hundreds of IDs in the array and loading all those nodes will result in a bad performance hit and/or go over the memory limit.
What is the best way to map an array of node IDs to (unique) node bundle types? Is there something built-in or does this require a custom database query? If so, I would be grateful for a dynamic query I could use for this (we're using MySQL). Thanks!

Rather than trying to load all nodes, you can query the DB directly for the nid/type (Bundle) pairs you need. Query the node_field_data table and use the IN operator to retrieve all the relevant nids you need.
$nids = [1, 2, 3];
//@TODO: add select query on node_field_data
$query->condition('nid', $nids, 'IN');
//@TODO: execute query and array map results

See the drupal.org docs on using IN operator in dynamic queries.


hook_menu() with a query string parameter? I have a module that loads at path module/1/view and then when user clicks a button they are redirected to another site and then redirected back to the same URL they left from with a querystring that looks like module/1/view?code=123

How do I implement a hook_menu to catch this slight difference in url/querystring param? I essentially want the hook_menu for module/1/view and module/1/view?code=123 to be different.

hook_menu() doesn't handle query parameters, so the behaviour will have to be within a single page callback.

function MYMODULE_generic_page_callback() {
  $query = drupal_get_query_parameters();
  if (empty($query['code'])) {
    return MYMODULE_without_code_page_callback();
  }
  return MYMODULE_with_code_page_callback();
}

If you need dynamic behaviour for some of the other hook_menu() options, many provide a callback option.  For example "title callback" would also let you use a function to change the page title based on the presence of the query parameter in the same manner as the page callback.

For access control, it's probably better to return MENU_ACCESS_DENIED or MENU_NOT_FOUND from your page callback.  "access callback" will be called when rendering links to the path to determine if the user has access and the link should be shown, so the query parameter will not be available on the page that contains the link.


In drupal 7 how to add a link to a node which creates another node related to the previous being visible only if a user has not yet done so? I have a node #1 of content type A. If the user equals a certain role AND has not yet done the following, show a link within node#1 saying "create node of type B".

If the user clicks this link, he may create a new node of type B. Then, when looking at node#1 again, the link disappears (or changes), since the user has already created another node from within node#1.

If you would delete that last created node and visit node#1 again, you would again have the possibility to create a node of type B which would automatically be related to the respective node, in this case node#1.

How can you do that?

I can see couple of ways to do it.

1) add the module http://drupal.org/project/node_limit

2) Create a menu with node/add/contentA

3) add this block to the node of the type content A

4) to do the third step you would need to add alias to the content A nodes by following method

Setup a URL alias pattern for content A
Click on Configuration in the admin menu, and look for "URL Aliases".
One of the tabs is called "Patterns" - this is where you can adjust the automatic URL alias settings for your content. In the "Content Paths" section you'll see the default is set to "content[node:title]" -- just below that you'll want to set "Pattern for all Blog entry paths" to "contenta/[node:title]" and save your new configuration. This means all of your future Content A content will have URLs like: http://yoursite.com/contenta/your-contenta-title.

(Thanks to Jonathan Webb http://www.drupalgardens.com/content/block-not-showing)

That should do it.

This assumes that the user can only add one node.

EDIT : An update with the requirement mentioned in the comment

Instead of step 1 and 2 do the following

1) Enable php filter

2) Create a view of the type block with just one field may be nid of the node. Remove the label. Rewrite the out put to some thing like  so that nothing is displayed.

3) Add contextual filter of the type content:author and select provide default value and from the drop down select User ID from logged in user

4) In the header section add a field of the type gloal:textarea click on "Display even if view has no result" so that it would be displayed even if there is no result.

5) Select PHP code as the filter and paste the following code with the changes that suite your requirement such as changing the url to the one that adds your content type.

<?php
  $view = views_get_current_view();

   if (!count($view->result))
   {
       print "Add Node";
   }
?>

Follow step 3 and 4 to add the block to the node.


Benefit of processing multiple entities at once? I am about to port renderkit to Drupal 8.
The D7 version contains an interface EntityDisplayInterface, which builds render arrays from entities.
In the D7 version, this contains one method buildEntities($entity_type, $entities); which allows to process multiple entities at once. The idea here was that this could speed up performance.
For D8, I wonder if this is still relevant. E.g. it seems that D8 views really renders each entity separately. And even though there is EntityViewBuilder::viewMultiple(), this really does most of its processing within the foreach(), so separate per entity.
So.. should I drop the buildEntities() method in D8, and only leave buildEntity()?

buildMultiple() exists, but it was done before we introduced render caching to entities and with that, lazy entity rendering/building. Now we don't really need multiple processing.

See https://www.drupal.org/node/2843565 for a discussion about that and the conclusion that we don't really need buildMultiple() anymore.

The idea is that if we render a page with 20 articles, then rendering them all separately is slightly slower on the first request. However, if you save one of those articles, or create a new one, then when accessing that page again, only one needs to be rendered (again), the others can be returned from the cache.

Whether or not a multiple API makes sense for you depends on how it will be called, if you expect it to be called on multiple entities, then can make sense, if not, then probably not.


Load an AJAX submission enabled webform using another AJAX call I am using Javascript/AJAX to call a path defined in a custom module which loads existing node content for display.  i.e. you are at:

/custom/path

and it makes an AJAX request to /custom/content with arguments to load the content for the page (placed in #main-content). Content may be a page, video or other custom Content Types.

Custom navigation elements on the page cause further AJAX requests to /custom/content with different arguments to replace the content.

This has worked well until the need to incorporate webform's into the mix.  Due to the non-refreshing nature of the page the webform needs to be loaded, displayed and submitted using AJAX.

I have setup hook_form_alter to add the necessary $form['actions']['submit']['#ajax'] to webforms and they work properly when called directly.  The form submits via AJAX.  However, when they are loaded via AJAX this does not work.  They submit as per normal and navigate away from my desired wrapper page.

I have ensured Drupal.attachBehaviours is being called post AJAX load.  I suspect my problem is in the loading/rendering of the webform in the module, but have not been able to successfully piece it together.  The module serving /custom/content basically does the following:

$node = node_load($node_id);
$output = drupal_render(node_view($task, 'full', NULL));
echo $output;

It displays the webform perfectly (like other content) - it just doesn't implement the #ajax submission part.  I've tried all manner of more specific form buulding for when $node-type = webform but no success.

Try to create ajax links with this module Ajaxify Drupal with JQuery Ajax.

It will load all ajax behaviour of loaded content(if loaded content contains ajax enabled form then that also)

  Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.


What does features_exclude mean in a features info file? I found this line in the *.info file of one of my feature modules.

features_exclude[field_base][field_block] = field_block

I did find a number of drupal.org issues dealing with this, but no documentation about the intended purpose.

The context of my example does not really matter; I am asking about the general meaning and implications of the features_exclude key.

features_exclude is generated by the Features UI when creating a Feature. It is not created by drush fu FEATURE_NAME. See https://www.drupal.org/node/1064472#comment-7196064.

  The features_exclude lines are purely for the new UI to determine if an auto-detected dependency should be checked or if you have specifically unchecked it.


How to create custom date display format that displays event duration I am new to Drupal. I want to display event date like,

"28/07/2016 | 02 PM to 04 PM"

Default date formats display date like,

"28/07/2016 - 02 PM to 28/07/2016 - 04 PM"

How can I create such custom display format?

Do the following:

Administration » Configuration » Regional and language » Date and Time
There you will see a tab for format.
Create a new format string "Y-M-d".
Make this as your default for all date fields and you won't see the seconds any more.
You don't need the date module for basic formatting.

UPDATE: From following comment,

If you want optional End time, use Timefield module

  Timefield is a Field API field for storing simple non-timezone time
  values, with an optional end time, utilizing a simple JQuery
  timepicker widget for input.


How to increase the performance of my website in Drupal 7 I have tested my website on http://www.webpagetest.org/, and I found my website performance is very bad. I have used minifying of CSS and JavaScript, and reducing the pic size; performance is still very bad.
How do I solve this problem?

You can guess all you want and experiment, but the only way to actually achieve meaningful results is to profile the system to figure out where the bottlenecks are.   There are many ways to accomlish this.

You can use the Performance module to identify slow pages.

You can use xhprof and the Devel module to identify memory problems, and show slow functions and queries.

Are you running APC?  If not, you should.  Stick the apc.php file somewhere safe and check the statistics to make sure you don't have cache churn.

Install DB Tuner and see what the mysqltuner results and recommendations are, particularly with regards to buffer sizes and query cache size.

You can also read up on profiling and optimizing Apache

You could also experiment with Zend Server CE as it includes a PHP optimizer in addition to opcode caching.


Allow customer to change Quantity in cart On my site it's not possible for customers to edit the quantity field in the cart view.

How do I allow that? I can't find a permission setting for this anywhere.

Go to the display settings of the product(#overlay=admin/structure/types/manage/product_display/display)
Click on the gear icon and select the checkbox "Display a textfield quantity widget on the add to cart form."


Tabulation order in Display Suite Display suite (http://drupal.org/project/ds) allows you to modify the form display appliyng template layouts.
But if i chose (say) a 3 column layout, with say 6 field, the tab order is per column and not per field weight.

example:

left-----middle---right

field1 - field2 -field3

field4 - field5 -field6

if i press tab, the focus shift from field 1 to field 4, and not on field 2 as expected.
 it's possibile to set a tab order per row and/or per field weight?

You could probably do this if you use something like javascript or jQuery and using the tabindex attribute.  Take a look at the below link at Stackoverflow as an example:

https://stackoverflow.com/questions/2894539/how-to-set-tab-order-in-jquery


How do I assign a role to a user after the user's email is confirmed? I want to assign a role to a user after the user confirms his/her email.

How do I do this?

You'll want to take a look at Rules and LoginToboggan (as per this answer on Drupal Answers).

Rules will allow you to add a "trigger", such as adding a role to a user, and LoginToboggan will provide the "trigger" for when the account is validated.


Running PHPUnit test from CLI and debug in PhpStorm: Remote file path '/directory/path/-' is not mapped to any file in project I'm trying to execute a PHPUnit test via the CLI to debug in via PhpStorm, being on a Ubuntu 16.04 operating system. It's a KernelTestBase unit test for Drupal 8. The normal execution of the test - without PhpStorm and Xdebug - works. The problem appears, when I have XDebug switched on. I'm executing it that way from the terminal:

  peter@computer ~/Websites/pbt-d8 $ vendor/bin/phpunit -c
  modules/permissions_by_term
  modules/permissions_by_term/tests/src/Kernel/SelectTermTest.php

If XDebug is switched on, PhpStorm shows me a weird "Remote file path error":

  Remote file path '/home/peter/Websites/pbt-d8/-' is not mapped to any
  file path in project

I have also attached a screenshot of the debug window:

What confuses me here, is the "-" character at the end of the path. I have not specified this character anywhere.

I have no idea what I should define here as a path mapping within PhpStorm:

My phpunit.xml file (which is located at modules/permissions_by_term/phpunit.xml) looks like follows:

<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">
  <php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="mysql://root:password@localhost/pbt-d8"/>
    <env name="SIMPLETEST_BASE_URL" value="http://pbt-d8"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/home/peter/d8-tests"/>
    <env name="PHP_IDE_CONFIG" value="serverName=pbt-d8"/>
    <env name="XDEBUG_CONFIG" value="remote_enable=1 remote_mode=req remote_port=9000 remote_host=127.0.0.1 remote_connect_back=0"/>
  </php>
</phpunit>

Do you know what's wrong here? Do I need any specific XDebug configuration to fix this issue here?

You can disable "Force break at first line when no path mapping specified" in "Debug" settings and this error goes away. While execution is paused, you can see that the break is happening in a secondary callback that is called with - as an argument (See $_SERVER['argv'][0]).

This doesn't happen with purely unit tests because there isn't a secondary callback but BrowserTestBase. KernelTestBase must be working simillarly to BrowserTestBase.


Accessing Content: Path field within views_view_unformatted TWIG template I have a view that has the fields: Content: ID, Content: Title and Content: Path.

In my views-view-module.html.twig file I can access the fields via the following:

{{ item['#row']._entity.id }}

{{ item['#row']._entity.title[0].value }}

But I cannot seem to retrieve the path field using:

{{ item['#row']._entity.path[0].value }}

Do I do this the same way or am I missing a trick?
I've tried to use dump/kint but I keep getting the WSOD.

Can anyone offer me a solution?

Thanks in advance

You access the fields from the entity. That are not the fields from the view. And in the entity there is no field path.

Look for the path in the row content. This is a good advice not only for the path, but for all fields, because in the entity the field values are the raw data from the database and not formatted for output. That doesn't make a difference for the id and the title though, because they are plain alphanumeric, but you really should do it for more complex fields. And for computed fields like path you have no other choice, if you don't want to compute the field again yourself.


How to write webform settings and conditions programmatically I'm trying to create a webform on my node programmatically so that I can set it up to be used as for a specific scenario. What I wanted to do is have all of the components my client want to appear automatically, but also default to specific settings for user entry, email specific users and validation rules etc, because they are going to have the same setup for each one, and they aren't going to want to write their setup out every single time.

I was using the Webform Default Fields module, but I know that this only works with the components, and not the setup. So I got rid of it and started writing my own version, with big help from this answer to get me as far as I am right now. But I'm struggling to find the correct format of how to write in a conditional statement, or how you would set the settings for the webform.

My current code is as follows:

function mymodule_node_insert($node) {
  if ($node->type == 'event') {
    _abstract_webform_components($node);
  }
}

function _abstract_webform_components($node) {
  $components = array(
      0 => array(
        'name' => 'First name',
        'form_key' => 'first_name',
        'type' => 'textfield',
        'mandatory' => 1,
        'weight' => 1,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
      1 => array(
        'name' => 'Last name',
        'form_key' => 'name',
        'type' => 'textfield',
        'mandatory' => 1,
        'weight' => 2,
        'pid' => 0,
        'extra' => array(
          'private' => 0,
        ),
      ),
    );
      // etc etc

  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $component['extra']['locked'] = 1;
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }

  // Retrieves information about the author
  $author = user_load($node->uid);
  // Adds the author of the node as the default email recipient
  $email = array(
    'nid' => $node->nid,
    'email' => $author->mail,
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);

  $validation = array(
   'validator' => 'max_words',
   'action' => 'add',
   'nid' => $node->nid,
   'rulename' => 'Maximum Abstract Length',
   'rule_components' => array(
     1 => '1',
   ),
   'data' => 300,
  );
  webform_validation_rule_save($validation);

  }

Basically I'm missing the correct notation for how you add a condition to the webform but I have the right command to insert it. Also, I have the notation for how I want to setup my webform settings, but I don't know how to apply it

Many Thanks

EDIT

I've got one half of it, I've managed to add the conditional statement into the code, I was actually using the wrong code, but I managed to find a proper example of how the array needs to be written, edited the code above

I had a similar requirement :

The site will have some landing page contents and the site owner can add those contents at different times, and once a content of type landing_pages will be created some blocks (already created) will get enabled on that node details page and a new webform node with some predefined fields will get created and get enabled as a block on that page in particular places.

I did it in D6.

My approach for the dynamic webform block :

I created a webform node with all the default & predefined fields, say with nid = 100
Enabled 'Available as block' option by visiting 'Form settings' tab in the path 'node/100/webform/configure'
Created a custom module 'landing_pages'
I cloned the nid = 100, each time a new landing_pages content is created
In hook_init() used this code :

/**
 *Implementation of hook_init().
 */
function landing_pages_init() {
// Update the 'blocks' DB table with the blocks currently exported by modules.
_block_rehash( $theme = NULL );
}

In hook_node_api() used this code :

/**
 *Implementation of hook_node_api().
 */
function landing_pages_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
 switch ($op) {
   case 'insert' :
     if ($node->type == 'landing_pages') {
       $node_id = 100;
       // function to create & save the clone node
       $new_nid = clone_node_save_custom( $node_id, $node->title );
     }
   break;
   case 'load' :
     if ($node->type == 'landing_pages') {
       /*updating webform block*/
       $result2 = db_fetch_object( db_query( "SELECT n.nid , n.title FROM {node} n WHERE n.type = 'webform' ORDER BY n.nid DESC LIMIT 1" ) );
       $var_result2 = 'client-block-' . $result2->nid;
       $result3 = db_result( db_query( "SELECT b.bid FROM {blocks} b WHERE b.module = 'webform' ORDER BY b.bid DESC LIMIT 1" ) );
       $nid = $node->nid; // Can avoide this step & directly use $node->nid
       $var_result1 = 'node/' . $nid;
       $check1 = db_query( "SELECT bl.bid FROM {blocks} bl WHERE bl.pages LIKE '$nid' AND bl.module = 'webform'" );
       /*if blocks table doesn't have any entry for 'pages' like this 'nid'*/
       if (db_affected_rows() == 0) {
         $check2 = db_fetch_object( db_query( "SELECT b.bid, b.region, b.status, b.visibility, b.pages FROM {blocks} b WHERE b.delta LIKE '$var_result2'" ) );
         /*if blocks table doesn'thave any entry for 'delta' like '$var_result2'*/
         if (db_affected_rows() != 0) {
           /*if blocks table doesn't have any entry for 'region' & pages,0 as entry for 'status' & visibility*/
           if ($check2->region == '' && $check2->status == 0 && $check2->visibility == 0 && $check2->pages == '') {
             $exp = explode( '-#-', $result2->title );
             if ($exp[0] != '')
               $title = $exp[1];
               db_query( "UPDATE {blocks} b SET b.module = 'webform', b.delta = '%s', b.theme = 'YOUR_THEME_NAME', b.status = 1, b.region = 'sidebar_second', b.visibility = 1, b.pages = '%s', b.title = '%s' WHERE b.bid = %d", $var_result2, $var_result1, $title, $result3 );
             }
           }
         }
       }
    break;
    case 'delete' :
      if ($node->type == 'landing_pages') {
        $res = db_query( "SELECT b.bid, b.delta FROM {blocks} b WHERE b.module IN ('webform' , 'block') AND b.theme = 'YOUR_THEME_NAME' AND b.pages LIKE 'node/$node->nid'" );
        while ( $row = db_fetch_object( $res ) ) {
          if (! is_numeric( $row->delta )) {
            $exp = explode( 'client-block-', $row->delta );
            if ($exp[0] == '' && is_numeric( $exp[1] )) {
            //This validation can be skipped
              $type = db_result( db_query( "SELECT n.type FROM {node} n WHERE n.nid = %d", $exp[1] ) );
              if ($type == 'webform') {
                node_delete( $exp[1] );
            }
          }
        }
        else {
          db_query( "DELETE FROM {blocks} WHERE bid = %d", $row->bid );
          db_query( "DELETE FROM {boxes} WHERE bid = %d", $row->delta );
        }
      }
    }
    break;
 }
}

Supporting functions :

/**
 *Definition of clone_node_save_custom().
 */
function clone_node_save_custom($nid, $nodetitle) {
 if (is_numeric( $nid )) {
   global $user;
   $node = node_load( $nid );
   if (isset( $node->nid ) && clone_is_permitted( $node->type )) {
     $original_node = drupal_clone( $node );
     $node->nid = NULL;
     $node->vid = NULL;
     $node->tnid = NULL;
     $node->name = $user->name;
     $node->uid = $user->uid;
     $node->created = NULL;
     $node->menu = clone_node_clone_menu_link( $original_node );
     $node->book['mlid'] = NULL;
     $node->path = NULL;
     $node->files = array();
     $node->title = t( '!tit -#- !title', array('!tit' => $nodetitle, '!title' => $node->title ) );
     $node->clone_from_original_nid = $original_node->nid;

 if (variable_get( 'clone_reset_' . $node->type, FALSE )) {
   $node_options = variable_get( 'node_options_' . $node->type, array('status', 'promote' ) );
   foreach ( array('status', 'moderate', 'promote', 'sticky', 'revision' ) as $key ) {
     $node->$key = in_array( $key, $node_options );
   }
 }
 drupal_alter( "clone_node", $node, $original_node, "save-edit" );
 node_save( $node );
 return $node->nid;

  }
}
}

/**
*Defines clone_node_clone_menu_link()
*@param $node
*/
function clone_node_clone_menu_link($node) {
if (variable_get( 'clone_menu_links', FALSE )) {
  // This will fetch the existing menu link if the node had one.
  node_invoke_nodeapi( $node, 'prepare' );
  if (! empty( $node->menu['mlid'] )) {
    $old_link = $node->menu;
    $link['link_title'] = t( 'Clone of !title', array('!title' => $old_link['link_title'] ) );
    $link['plid'] = $old_link['plid'];
    $link['menu_name'] = $old_link['menu_name'];
    $link['weight'] = $old_link['weight'];
    return $link;
  }
}
return NULL;
}

Theme used is ZEN
Region I needed the webform be enabled is 'sidebar_second'
We shall have control over the settings of each webform for each Landing Page

Hope it helps.


Automatically creating an organic group for each new user I would like to automatically create an organic group for each newly registered user. I checked all its settings, no such option with organic groups module, then I checked the rules module but no luck there too.

The Rules module will allow you create new OG node after saving a new user account. Just do the following:

Create your rule and add an "After saving new user account" event to it
In the action section, select create a new entity
In the value section, select node
In the Content type, select the "your group"
Fill the title as you need; you can do this using the token
Fill the author

Hope this will help.


Is updating the composer.json file & consequently composer.lock in Drupal 8 considered a good practice or hacking the core? I have been working with another developers on a scaffolding tool for Drupal8 based on Symfony Console component.

The current setup process includes updating composer.json using composer CLI:

COMPOSER_BIN_DIR=bin php composer.phar require hechoendrupal/drupal-app-console:dev-master

Maybe writing to core/vendors is not the best practice any suggestions

Modifying anything in core is generally not recommended.
Unlike other projects that use composer, Drupal already has its composer packages included in core/vendor and you are not supposed to change them, nor the composer.json. Updates to Drupal 8 core would wipe your changes.

There is a module Composer manager that will open a second vendor directory in sites/sitename/vendor (I think). There is some discussion going on in the issue queue, e.g. Is it okay to have duplicates of symfony, guzzle, etc... in sites/all/vendors?. I imagine a future where sites/sitename/vendor could replace core/vendor. But we are not there yet.

I think you should participate in the composer vendor issue queue, this is all work in progress.

EDIT:
It should be mentioned that the way Drupal 8 is using Composer is not the way it is recommended. The recommended way is that the user should download Drupal and vendor packages via Composer. Instead, it is all pre-packaged. One reason for this is to support shared hosting where you don't have a commandline available, and just want a complete package to upload.


How do I apply a defined Image Style as a View Mode for a File field? I'm currently working my way through O'Reilly's "Using Drupal", but I appear to have reached an impasse.

I'm trying to specify a view mode for a File field-type which utilises the Media File Selector widget. The problem is, I'm not getting any of my set Image Styles in the View Mode drop-down. I'm just getting:

default
teaser
Full Content etc.

(see screenshot of view mode options: http://i.imgur.com/CdogRKu.png)
(this screenshot shows my image styles: http://i.imgur.com/ZRE8nqO.png)

The book was published April 2012 so I'm not sure if anything might have changed significantly since then? I'm using the most up-to-date version of Drupal and all modules.

Can anyone tell me if this is wrong way to perform this task, and if so what the right way is?

Cheers!

It appears that things have changed.

Applying image styles is now done exclusively through the structure->file types->images menu.

More extensive instruction can be found in this answer: How to set Media Styles in Media 7.1.2 / Media 7.2.X?


Re-submit form after confirmed AJAX form I have a form with submit AJAX button. When clicking this button, it calls function callbackAjax(). In this function callback, I checked a condition A to show a warning dialog if A is FALSE. The warning dialog has a message and two buttons, Confirm and Cancel. Cancel action will close dialog and do nothing. Confirm action will continue doing the callback function with condition A is true.

function renderForm($form, $form_state) {
  $form['submit'] = array(
    '#type'  => 'submit',
    '#ajax'  => array(
      'callback' => 'callbackAjax',
    ),
  );
}

function callbackAjax($form, &$form_state) {
  if (!$condition) {
    // Show dialog with confirm button
    // If confirmed, doing code in else clause
  }
  else {
    // Save data
  }
}

Please tell me how to re-submit form to save data after I clicked button Confirm which be rendered from AJAX callback?

I tried to set button Confirm as same as Submit button from main from, to call AJAX again, but it shows error.

Thanks for your help.

I found the solution, at least it worked in my case. I want to share if someone need it.

function renderForm($form, $form_state) {
  $form['submit'] = array(
    '#type'  => 'submit',
    '#ajax'  => array(
      'callback' => 'callbackAjax',
    ),
  );
}

function callbackAjax($form, &$form_state) {
  if (empty($form['#skip_validate']) && !$condition) {
    // Show dialog with confirm button
    // If confirmed, doing code in else clause
    $confirm_form = drupal_get_form('renderConfirmForm', $form, $form_state);
    $commands[] = ajax_command_open_dialog($confirm_form);
  }
  else {
    // Save data
  }
  ...
}

function renderConfirmForm($form, &$form_state, $main_form, $main_form_state) {
  $form['continue'] = array(
    ...
    '#ajax'  => array(
      'callback' => 'renderConfirmFormCallback',
    ),
  );
  $form['close'] = ...;
  $main_form['#skip_validate'] = TRUE;
  $form['#main_form'] = $main_form;
  $form['#main_form_state'] = $main_form_state;
  return $form;
}

function renderConfirmFormCallback($form, &$form_state) {
  callbackAjax($form['#main_form'], $form['#main_form_state']);
}


How to render field in hook_form_alter? I am trying to show a user profile field in node form.

function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id){
        $form['myfield'] = array(
            '#markup' => drupal_render(field_view_field('user', $account, 'field_myfield'));
        );
}

field_view_field() is not returning any thing.

Question is, the profile field of which user? The node author, or the current user?

In both cases you need to fetch the $account you are trying to pass to field_view_field.

For the current user:

global $user;
$account = user_load($user->uid);

For the node author:

$account = user_load($form_state['node']->uid);


How to disable breadcrumbs by default and enable only particular ones with Path Breadcrumbs module? I'm using Path Breadcrumbs module for displaying breadcrumbs on particular pages.

Is there a way to set breadcrumbs not to display by default for ANY page and enable only particular ones using rules created with Path Breadcrumbs module?

In module there's an option to disable breadcrumbs by creating a rule for each URL pattern and setting breadcrumb and title to "" but how can I trigger rule for ANY drupal URL - nodes, taxonomy, views, panel pages etc. And then make rules only for those URLs which really need breadcrumbs to be displayed?

There is a patch for the Path Breadcrumbs module that adds a setting to disable other breadcrumbs: https://www.drupal.org/node/2483091

The patch allows an easy one click disabling of other breadcrumbs.

Here is a screenshot of the setting on the patch breadcrumbs settings page (admin/structure/path-breadcrumbs/settings) as it is in the current version of the patch:


Number of Front Page Nodes Variable? I'm aware of how to change the number of nodes displayed on the front page. My question is whether there is a variable in Drupal, or a way of calculating the numbers of nodes displayed per page of front page content?

I've got a block module that prints out information according to the nodes that are being rendered in the main content area of the front page, so it needs a list of the nodes. If there is an array of nodes that can be accessed that would also work, but I can't find information on that, so I've been trying to calculate the items per page, but merely dividing the total number of front page nodes divided by the number of pages gives inconsistent results of course.

I could of course hardcode the number, but I'd prefer a programatic way for determining this value.

This value can be set in the site information admin settings form.

$count = variable_get('default_nodes_main', 10);

This should work for both Drupal 5, 6 and 7.


How to set the value of a hidden field using form_set_value? In form validation I have to set value of a hidden field. I tried like below

\Drupal::formBuilder()->setValue($form['maintenance_type'], 'R', $form_state);

form_set_value($form['maintenance_type'], 'I', $form_state);

Insert the the value in $form_state:

$form_state->set('store_value', 1);

And then later for example in submitForm():

$value = $form_state->get('store_value');

Don't use getValue() or setValue(), because this is for submitted values.

If you are migrating more forms from D7 to D8, use this as reference:

Use this as reference


A error creating filter - filter tips I want to create a filter text module for drupal 8.

emtfilter/src/Plugin/Filter/emtfilter.php

/**
 * @file
 * Contains \Drupal\emtfilter\Plugin\Filter\emtfilter.
 */

namespace Drupal\emtfilter\Plugin\Filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Text filter for highlighting PHP source code.
 *
 * @Filter(
 *   id = "emtfilter",
 *   module = "emtfilter",
 *   title = @Translation("Tipograf"),
 *   description = @Translation("Tipograf"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR,
 * )
 */
class emtfilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    if ($long) {
      return t('text1r-');
    }
    else {
      return t('text2r-');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
        return new FilterProcessResult($text);
  }
}

After clearing cashe everything is ok. But when I visit some forms with textfields second time, Drupal generates this error:

  Notice: _filter_tips(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Drupal\emtfilter\Plugin\Filter\emtfilter" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in _filter_tips() (line 350 of core/modules/filter/filter.module).
  _filter_tips('full_html', ) (Line: 378)
  template_preprocess_filter_guidelines(Array, 'filter_guidelines', Array) (Line: 293)

And my tips disappear. What am I do wrong?

I made a mistake in the letter case in the class file (emtFilter.php -> emtfilter.php)


Does entity_save() trigger the update event? Not quite sure if calling entity_save() from code will trigger the update event or not.

So, does it?

Assuming you're asking whether or not entity_save() invokes hook_entity_update(): no, it doesn't.

The controller class (or save callback function) for an entity type may well invoke it (for example node_save() does), but you can't rely on it for an entity type without checking the code first.


Why do I have to enter a recipient after selecting users in the VBO send emails operation? I'm using VBO module in D7. I created a table view listing users by some filter criteria. I want to send a mass mail to selected users. I'm using the VBO field bulk operations: user and selected the send email functionality. The view looks like that:

Selecting multiple users and hitting the send email execute button brings me to this form:

Why do I have to enter a recipient after selecting users in the view? What does that send email operation do if not sending emails to the selected users?
Is it my fault and I messed up the installation or did I miss some settings or configurations?

VBO does not provide the "send email" function. It is provided by core actions and it really doesn't know the context that it is being used in. Therefore, you need to insert a token in the "Recipient" field as mentioned in the help text just below the field e.g. user:mail , node:author:mail etc.  I can't tell for sure what the base table  your view is using based on your screenshot but it looks like you can use the token [user:mail].

If you would like to have this info prepopulated you need to use the views send module. It used to support VBO but it now provides it's own UI. It's a pain if you want to combine it with a VBO view as you get double checkboxes etc...

See http://drupal.org/node/575980 for more info


Drupal 7 Display a list of reference node in node being display I am new to Drupal 7.

I have two content types, they are 'school' and 'course'. In course content type, I used Reference module to create a field that reference to school (a school have many courses, and a course is belong to one school only).

And now what I want is, when I view a specific school info, the list of courses that belong to the school also be displayed beneath.

How can I do that in drupal 7 ? :D
Thank you in advance!

You need to create a view of contents filter by Course content type. Now I assume you have a field name field_school.

Add this field in Contextual Filter and select default argument Content ID from URL.

When this block will be added on node page, it will automatically filters the courses of that school. Otherwise pass the school id as argument to view. :)

Here is the screenshot :


alias the path of single - node views (pagination on single nodes) I would like to effectively replace the nodes with views that would show the "full content" of a node with items to display set to 1. (Each paged page of the view would thus include only one node and the pager - effectivly i'm trying to use views' pager for nodes).
Now, what I am missing is the possibility of having aliases of the paths that include given nodes. I would like the pages to have paths like site.com/myview/nodetitle, not site.com/myview/1.
The aim is to replace the links to nodes in a context of a given view by links to single - node views, thus obtaining views pagination on node-alike. So the "title" field would be linked to, say, site.com/myview/nodetitle, wichh would be the single - node - position in a that has the same cireteria etc as the one I am coming from, but with full node view and a views pager. I am trying to replicte the features from views-navigation.
Is there any way to achieve that?
EDIT: i do not want to use contextual filters, as I do want the view to include many nodes, with 1 node showing per page

I would not use views at all. Pathauto will help you with the aliasing. So, on hook_init you can set the pathauto pattern for that node type to be 'myview/[node:title]'. Such as this:

function myMod_init() {
  variable_set('pathauto_node_yournode_pattern', 'myview/[node:title]');
}

For the pagination, I'm not sure what your use case is like. If you could have the nids gathered via a db_query and passed to your 'page callback' function, you could construct your own "next" and "previous" buttons containing the correct href. You will find function such as drupal_get_path_alias() or url() to be very useful here.

If you wanted a pagination with proper numbering, you can look into EFQ. It has pager as a public method. Although, that will probably give you query like url such as ?page=1, etc. and not the nice alias pathauto had created for you.

All in all, more information about your usecase will be useful. But this method will give you a lot more flexibilities than using views IMO.


Multilingual site title I've got a problem translation my site title with the Configuration translation module. I set my set title to let's say XXX which is not displayed by the tamplte at all. Instead, it always attaches "| Drupal" string to the end of the node title.

When I click to add translation, translate the string to let's say YYY and save the form, everything appears to be saved correctly, the English version of my site even displays the correct title. However, the form for adding Site information translation still displays an "Add" button as if nothing had been added before and the default version of the site continues to display the "| Drupal" string even though my site name is set to XXX.

Has anybody else experienced the same behaviour?

Well, I have experienced a similar problem when manipulating with more language versions. In the config database table, I had two rows with the name system.site - one of them had a collection = "language.sk" and the other (full record) had an empty collection and in the data column langcode SK. So, I think the interface was confused, because there were two rows for one language. However, I do not know how the database got into this state.

So I have deleted the row with collection = "language.sk", cleared the cache and now you can change source site name and also create translations - it started to work. Please try this and let me now, if that works.