How to add a new tab to user profile in administration? How can I add a new tab to user profile beside View(active tab) and Edit. I want to add for instance New User Tab which will be visible only by administrator (not by the user itself).

I want to add in this tab some informations related to the user and to make some associations with specific nodes related to the user.

If this is for Drupal 7, you should take a look at the profile2 module. It allows you to create a profile entity where you can add any fields. It also creates tabs on the user page via permissions.

In general to create tabs, you need to create menu local items. Views 3 support this, and it is also possible to create such a tab with hook_menu by setting the type to MENU_LOCAL_TASK. There are some requirements to the path of the url to make this work, but this is all well documented at the drupal API reference, linked to above.


A Multi-step Form to display Database Data at the End I'm fairly new to Drupal but I'm building a site using Drupal 7. Most of the stuff is pretty standard Drupal things, but one of the things my stakeholders want is a tool that does the following (and I'm not sure the best way to implement this using Drupal 7- suggestions appreciated!):

A multi-step form (with 1 question per form) with checkboxes and radio buttons only.
Data is saved temporarily for users. At the end of the form when users request their recommendatios the site displays a list of resources (from the database) FORMATTED in a specific way (ie. image, text, and link to resource) IN ORDER of relevance BASED ON the selections they made in the form itself. And all of this should be displayed in a list view.

I'm imagining some sort of FORM API + Views interaction but like I said I'm new. Any suggestions from the community?

Don't really need the views to make it much complicated. It is all about creating a module. Here is a basic format.

In Drupal, start by creating a simple module. Two files should be created: The .info file and the .module file. For the sake of simplicity call the module multiform.

multiform.info
name = Multi Form
description = Creates a multi-step form.
core = 7.x
package = Custom
version = 7.0

Now that have the .info file, and go create the .module file. The first thing  to add is a menu entry to the page in which the form will show on. Implement hook_menu() inside the module like this:

/**
 * Implements hook_menu().
 */
function multiform_menu() {
  $items['multiform'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Multi Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('multiform_primary_form'),
    'access callback' => TRUE,
  );
  return $items;
}

hook_menu() was implemented with a page callback that renders a form. This function will register a menu item for us to use as our form page.

Add the wrapper form. The reason it need a wrapper form is because the other forms will need to be contained. Without it they are just separate forms. The wrapper form will glue them together. A submit handler must also be created.

    /**
     * Form implementation of primary multiform.
     *
     * @see hook_menu()
     */
    function multiform_primary_form($form, &$form_state) {
      // Check to see if anything has been stored.
      if ($form_state['rebuild']) {
        $form_state['input'] = array();
      }
      if (empty($form_state['storage'])) {
        // No step has been set so start with the first.
        $form_state['storage'] = array(
          'step' => 'multiform_first_form',
        );
      }

      // Return the current form
      $function = $form_state['storage']['step'];
      $form = $function($form, $form_state);
      return $form;
    }

    /**
     * Submit handler for the primary multiform.
     *
     * @see multiform_primary_form().
     */
    function multiform_primary_form_submit($form, &$form_state) {
      $values = $form_state['values'];
      if (isset($values['back']) && $values['op'] == $values['back']) {
        // Moving back in form.
        $step = $form_state['storage']['step'];
        // Call current step submit handler if it exists to unset step form data.
        if (function_exists($step . '_submit')) {
          $function = $step . '_submit';
          $function($form, $form_state);
        }
        // Remove the last saved step so we use it next.
        $last_step = array_pop($form_state['storage']['steps']);
        $form_state['storage']['step'] = $last_step;
      }
      else {
        // Record step.
        $step = $form_state['storage']['step'];
        $form_state['storage']['steps'][] = $step;
        // Call step submit handler if it exists.
        if (function_exists($step . '_submit')) {
          $function = $step . '_submit';
          $function($form, $form_state);
        }
      }
      return;
    }

$form_state['storage'] is used to store which step of the form that is on. Each time this wrapper is called it will call the next step in the sequence of forms. Add first form with a few example fields. Notice that the $form_state['storage']['step'] is storing this function as the default first called.

    /**
     * Menu callback form. First of three.
     */
    function multiform_first_form($form, $form_state) {
      if(!empty($form_state['storage']))
        $values = $form_state['storage'];
      $form['user_info']['username'] = array(
        '#type' => 'textfield',
        '#title' => t('User Name'),
        '#size' => 15,
        '#maxlength' => 15,
        '#default_value' => isset($values['username']) ? $values['username'] : NULL,
        '#description' => t('The user name that will appear to other users. You should not use your real name.'),
        '#required' => TRUE,
      );
      $form['user_info']['first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#size' => 32,
        '#default_value' => isset($values['first_name']) ? $values['first_name'] : NULL,
        '#required' => TRUE,
      );
      $form['user_info']['last_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Last Name'),
        '#size' => 32,
        '#default_value' => isset($values['last_name']) ? $values['last_name'] : NULL,
        '#required' => TRUE,
      );
      $form['user_info']['email'] = array(
        '#type' => 'textfield',
        '#title' => t('E-mail Address'),
        '#size' => 32,
        '#default_value' => isset($values['email']) ? $values['email'] : NULL,
        '#required' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
      );
      return $form;
    }

This is a simple form that asks the user for some basic information. $form_state['storage'] is used to store the values of each form. As the form progesses it will populate the content here if returned. Easy enough. Now going to skip the validation hanlder, but that should be easy to code. The important part is the submit handler where we will be storing the user's data. Below is an example of the first submit handler.

    /**
     * Submit handler for the first form.
     *
     * @see multiform_first_form()
     */
    function multiform_first_form_submit($form, &$form_state) {
      $values = $form_state['values'];

      // Save values to the form storage, add the next step function callback
      $form_state['rebuild'] = TRUE;  // This is very important to have!
      $form_state['storage']['username'] = check_plain($form_state['values']['username']);
      $form_state['storage']['first_name'] = htmlspecialchars($form_state['values']['first_name']);
      $form_state['storage']['last_name'] = htmlspecialchars($form_state['values']['last_name']);
      $form_state['storage']['email'] = check_plain($form_state['values']['email']);
      $form_state['storage']['step'] = 'multiform_second_form';
    }

The first thing to do is make sure `$form_state['rebuild']` is set to true. This will allow the next form to be returned for rendering rather than a reload. Any value that collected should be placed in `$form_state['storage']`. The last part is setting the next step. This information will be sent to the wrapper form and will process the next form. In this case it is `multiform_second_form()`. In this form there will add checkboxes. The first part of the function is to make sure if checkboxes have been set previously that they are reset. Take a look.

/**
 * Form that is called second
 */
function multiform_second_form($form, &$form_state) {
  // Make sure the default values for the checkboxes are set correctly.
  if (!empty($form_state['storage'])) {
    $values = $form_state['storage'];
    if (!empty($form_state['storage']['food'])) {
      foreach ($form_state['storage']['food'] as $value) {
        if (!empty($value)) {
          $default_values[] = $value;
        }
      }
      if(empty($default_values)) {
        // Storage and experience are set, but no values were selected.
        $default_values = array();
      }
    }
    else {
      // Storage was set, but experience wasn't.
      $default_values = array();
    }
  }
  else {
    // Storage is not set.
    $default_values = array();
  }

  // Set options
  $checkboxes = array(
    1 => 'Pizza',
    2 => 'Hot Wings',
    3 => 'Subs',
    4 => 'Salads',
    5 => 'Garlic Bread',
    6 => 'Pasta',
    7 => 'Cake',
    8 => 'Ice Cream',
  );

  $form['additional'] = array(
    '#type' => 'fieldset',
    '#title' => t('Additional Information'),
    '#collapsible' => FALSE,
  );
  $form['additional']['food'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Food you like'),
    '#options' => $checkboxes,
    '#default_value' => $default_values,
  );
  $form['additional']['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company'),
    '#size' => 32,
    '#default_value' => isset($values['company']) ? $values['company'] : NULL,
    '#required' => TRUE,
  );
  $form['additional']['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Additional Information'),
    '#description' => t('Please provide information about your job'),
    '#size' => 32,
    '#default_value' => isset($values['message']) ? $values['message'] : NULL,
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('multiform_second_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
  );
  return $form;
}

The first part may seem confusing, but just gathering what the user has picked before (in case they went to another portion of the form and came back here). Here doing the same thing as the other form, but now with two submit forms. One will take to the next form and one to the previous form. See how the submit handler handles this:

/**
 * Submit handler for the second step.
 *
 * @see multiform_second_form_start()
 */
function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['food'])) {
      $form_state['storage']['food'] = $input['food'];
    }
    if (isset($input['company'])) {
      $form_state['storage']['company'] = htmlspecialchars($input['company']);
    }
    if (isset($input['message'])) {
      $form_state['storage']['message'] = htmlspecialchars($input['message']);
    }
    $form_state['storage']['step'] = 'multiform_first_form';
  }
  else {
    $form_state['storage']['food'] = $values['food'];
    $form_state['storage']['company'] = htmlspecialchars($values['company']);
    $form_state['storage']['message'] = htmlspecialchars($values['message']);
    $form_state['storage']['step'] = 'multiform_third_form';
  }
}

The submit handler checks to see what button was pushed. If the back button was pushed it will set the step back to the previous form, if not it will set the step to the next and final form (at least for this form). Make the last form a nice and simple terms of use with a finished button.

/**
 * Form that is called third
 */
function multiform_third_form(&$form, &$form_state) {
  $form['terms'] = array(
    '#type' => 'fieldset',
    '#title' => t('Terms of Use'),
  );
  $form['terms']['terms_text'] = array(
    '#type' => 'textarea',
    '#title' => t('Terms of Use'),
    '#default_value' => t('I agree to the terms of use'),
    '#disabled' => TRUE,
    '#resizable' => FALSE,
  );
  $form['terms']['terms_checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => t('I agree to the terms of use'),
    '#required' => TRUE,
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('multiform_third_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  $form['#submit'][] = 'multiform_third_form_submit';

  return $form;
}

Simple like the others, this last form just collects some more information. The storage of information, creation of users, etc can be placed in this form's submit handler.

/**
 * Submit handler for the third step.
 *
 * @see multiform_third_form()
 */
function multiform_third_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['back']) && $values['op'] == $values['back']) {
    // The user pushed the back button. Clear out the terms checkbox.
    $form_state['storage']['terms_checkbox'] = NULL;
    $form_state['storage']['step'] = 'multiform_second_form';
  }
  else {
    $form_state['storage']['terms_checkbox'] = htmlspecialchars($values['terms_checkbox']);
    $form_state['storage']['step'] = 'multiform_form_complete';
  }
}

Done! Well, maybe. Notice the last part, calling another form. This is just to get the user to a new page and say "

  You have completed the form

". You could redirect to a new page or anything else you want. Here is the code for multiform_form_complete().

/**
 * The complete form (Thank you page) for parent form templates.
 */
function multiform_form_complete($form, &$form_state) {
  $form['message'] = array(
    '#markup' =>  t('Thank you for submitting the form!'),
  );
  return $form;
}

Please have a try with this module. Modify it according to requirements. Let me know if any questions or comments about this process. It is rather long so didn't get much time to explain every detail!

Get more about multi-step form from the Drupal support here.
https://www.drupal.org/node/717750


drush migrate:status comes back with SQLSTATE [hy000] [2002] No such file or directory Using drush on my macOS. Using Nginx and MYSQL through brew. Website is running fine. The other drush commands work fine, drush cr, drush cc, etc. But running drush migrate:status or drush ms results in

 error SQLSTATE [hy000] [2002] No such file or directory

in terminal. same for all migrate drush commands.

Running Drupal 8.8.5 Lightning Distro.

My settings.php is set up 127.0.0.1 but still no luck.

I had this problem when upgrading/downgrading php to work with drush migrate. Check if the mysql.sock is right in php.ini:

First check what php.ini file is used in terminal:

php --ini

Then open the php.ini file and change/add:

pdo_mysql.default_socket=/Applications/MAMP/tmp/mysql/mysql.sock

or the mysql.sock you are using. To find your mysql socket in terminal use:

mysql_config --socket


best way to restrict endpoints such as /node or /filter/tips I am looking for the best way to restrict access to drupal pages such as /node, /filter/tips and /filter/tips/plain_text etc.

Do I add rewrite rules to the .htaccess file?

One way to restrict access to specific paths is to use the Custom Permissions module.

It allows you to create path based permissions at /admin/people/custom_permissions.

Then you can configure which roles have those custom permissions as you would any other permission at /admin/people/permissions.

I probably wouldn't use this solution if I had a very large number of paths to restrict but it's a very usable solution for a few pages, especially if you still want admins to be able to access them.

.htaccess restrictions are also possible if you want to go that way.
That would mean there would be no database load involved in restricting access, which might be a consideration for very high traffic sites but would generally be negligible for an average site.


Trying to access PHP library from within another namespace I'm a little new to the concept of Namespaces in PHP/Drupal, and I'm trying to figure out where I am going wrong here.

I've got this custom PHP library under the /libraries folder - let's call it ilib. And inside of ilib, there is another directory called lms.

Anyway, I've written a little module that will connect with ilib (or I am attempting to get it to connect with it), called ilib_connect.

I am trying to do a test function inside a custom page with a controller for the page, as such:

namespace Drupal\ilib_connect\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use ilib\lms;

/**
 * Controller routines for page example routes.
 */
class iLibController extends ControllerBase {

function ilib_connect_test() {
  $lms = new \ilib\lms;
  \Drupal::logger("ilib_connect")->notice("<pre>" . $lms . "</pre>");
  $lms->AddLMSActivity();
  return "fake markup";
  }

}

However I am getting the error:

Error: Class 'ilib\lms' not found in Drupal\ilib_connect\Controller\iLibController->ilib_connect_test() (line 17 of modules/custom/ilib_connect/src/Controller/iLibController.php).

So I'm sorta having trouble pulling any classes from ilib into scope.

How exactly do I pull a third party library into scope in a situation like this? What about in a .module file?

What exactly am I misunderstanding here?

EDIT: Oh and just to be clear, this is how I am registering the custom library with Composer:

"autoload": {
"psr-4": {"ilib\\": "web/libraries/ilib"}
}

EDIT 2 - question to Clive:

Ah, so say I've got a file named AddLMSActivity.php inside of libraries/ilib/lms, setup like this:

namespace ilib\lms;

class AddLMSActivity
{

}

How would I access it exactly?

ilib\lms\AddLMSActivity?

When you use use you need to provide namespace + classname. This is what you are doing already, so

use ilib\lms;

Should be replaced with

use ilib\lms\AddLMSActivity;

If you want to use the AddLMSActivity class.


How do I add code to browse for a file in a Drupal Form? I am trying to add items to a form (in code) similar to the add image item in the Drupal Add Content form that has the Browse and Upload buttons.  In Firefox, the Browse button invokes a Pop-up window to search files on the user's computer and returns the selected file & path to the associated text box. I would like to review the code in Drupal to understand and duplicate the action. Thus far I cannot locate the code in core modules (its big in there and a file search does not find the word "Browse"!).  Does anyone know where the add content form is, or a reference site that explains it, or how to code it?

I recently created a few custom blocks with image upload and preview fields. Here's the relevant code that should be helpful for you:

function mymodule_block_configure($delta = '') {
  // Uploaded image path is saved in a variable.
  $pic_path = variable_get('mymodule_pic1', FALSE);
  $form = array();
  if ($pic_path) {
    $form['preview'] = array(
      '#markup' => '<img src="'. image_style_url('mymodule_img_preview_style', $pic_path) .'" alt="'.t('Preview').'" />',
    );
  }
  // Image upload field.
  $form['image'] = array(
    '#type' => 'file',
    '#title' => t('Upload image from your computer'),
    '#description' => t('Allowed extensions: jpeg, jpg, png, gif'),
  );
  return $form;
}

function mymodule_block_save($delta = '', $edit = array()) {
  // Functionality to validate and save the file.
  $validators = array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg'));
  $file = file_save_upload('image', $validators, file_build_uri('mymodule_images'), FILE_EXISTS_REPLACE);
  if ($file) {
    $file->status |= FILE_STATUS_PERMANENT;
    $file = file_save($file);
    variable_set('mymodule_pic1', $file->destination);
  }
}


Allow another role to edit only parts of any node I have nodes with a "topic" field that is a taxonomy reference. Nodes are submitted by users and users can only edit their own nodes.

How can I allow a "moderator" role to be able to edit the topic fields for any nodes but not any other fields on those nodes?

The Field Permissions module will allow you to do exactly this.

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


How Batch Works Around the PHP Timeout The Drupal 7 documentation introduces the Batch API as:

  Functions allowing forms processing to be spread out over several page
  requests, thus ensuring that the processing does not get interrupted
  because of a PHP timeout...

I took this to mean that Batch handles the timeout-related issues for the developer.

However, other posts (ie. How does the batch API work internally?)
imply that it is the developer's responsibility to tell Batch how much work to do before waiting for another user to arrive and Batch to be invoked again --- thereby avoiding the timeout.

If the latter is true then I assume Batch does not guarantee that jobs won't be timed out. Does Batch provide any guarantees? Is it up to the developer to guess how much Batch can process before timing out?

Thank you!

Batch simply says "I will do N number of things (at most) and then do a page refresh ... and do more."

If you say do 5 items per job chunk that take 5 seconds each you would be fine with the default php timeout value of 30 seconds.

If you say do 20 items per job chunk that take 5 seconds each, your workload per request is too high and will likely timeout.

Remember when your in PHP the lifecycle of a page is request in -> response out. And that your webserver keeps each thread alive for a finite amount of time. You have to work around that timeout -- which the Batch API helps you do.

Running stuff from say Drush, server side using community modules such as Migrate can help you completely avoid timeouts if need be.

EDIT

Also bear in mind that every page request is a full drupal bootstrap and Batch API picks off where it left off. That is one of the most expensive operations when using the Batch API, reloading drupal every N items. That's why people have been working on server side techniques to create nodes, import content, etc. Batch API is great for simple, repetitive tasks. But it tends to fall apart in either complex, or very very large datasets.


make field group repeatable I am using Field Group module and I would like to make certain group repeatable if needed, like adding a plus (+) icon next to it. Is that possible? and how?

You could try the Field Collection module. It allows you to group fields and add more of these "collections" inside the same node. Works great for slideshows for instance when you don't know how many images the site editor wants to use and you need custom fields (like big headline, small headline, promo text, link etc) grouped with the image.


how can I override theme_image() on a custom node template, only Can anyone explain how to override theme_image() but only on a specific custom node template? (i.e. node--artist-page.tpl.php)

As I understand you shouldn't put things like theme_image() in a .tpl file, but the theme devel module it's not offering up any candidate function name overrides except mythemename_image(), which would apply to all images on all pages.

As I understood your problem, you need to redefine theme_image function only for custom template. I found following link for you that can help you to resolve your problem.

How to redefine default theme_image() function?

Another way is just override theme_image() function that you don't want to follow:

Find the original theme function.
Copy and paste it into your template.php file.
Change the beginning of the function name from theme_ to yourthemename_.
Save template.php, clear the site cache, and reload!

Keep us posted with what you figure out.


Drupal 7 module recommendations for mailman listserv? From what I've seen the only mailman integration module is Mailman Manager which is only D6.

Does anyone know of another module or any other tool that I could use to implement the same functionality for D7? I.e.:

administer the lists
allow users to subscribe
unsubscribe
etc ...

you can try http://www.drupal.org/project/simplenews .. i personally use mailchimp with the drupal mail chimp module drupal.


How to add CSS classes to a Views-generated block? (NOT to its generated content, the block itself!) I don't know why, but Views doesn't add "human-readable" CSS class names (like e.g. the machine name of the view) to the blocks it creates (it only adds its classes to the generated "content" part when adding classes to the "CSS class" part in the view editor (see the screenshots below!)).
It only adds the usual block block-views, and possibly contextual-links-region CSS classes to the block(s), and generates a unique id (not class) like this: block-views-3d8f7966168beeec655c8ead69336789 (because its delta is this generated hash code).
It doesn't make sense to write CSS rules for these classes and ids (like .block-views-3d8f7966168beeec655c8ead69336789 { /* ... */ }), because these classes/ids might change when altering the Views block.

How can I add some custom CSS classes in an implementation of hook_block_view_alter(), if I cannot even identify these blocks because of their generated hash delta?

I do not want to use Block Class, because I feel it's like an overkill for just adding some classes to one or two Views-generated blocks (BTW I checked the module, and I feel SELECT css_class, module, delta FROM {block_class} query in block_class_preprocess_block() like an overkill, because it checks ALL the added classes, even if the block is hidden...).

So I would like to solve it from my own module.

EDIT

An example:

My view with the machine name and the added CSS classes:

The generated block's HTML code in the inspector:

First. You have "hash" - because you view machine name is too long.

Second - you can add your own classes to view


Render key and value of a field I have a field (list integer) and I would like to render its keys and values. I found field.html.twig but within I only have access to item.content which is the value. I would also like to access the key.
I also had a look to theme_preprocess_field(&$variables) but I'm not able to get the correct keys.

I tried

  foreach ($variables['items'] as $key => $item) {
    $variables['items'][ $key ]['key'] = $key;
  }

Unfortunatelly this only gives me the array positions 0,1,2 ... But I would like to have the actual keys from my list, i.e.

100|red
200|green
300|blue
400|black
...

Here is how you can get the list field key and value

function themename_preprocess_field(&$variables, $hook) {

    if ($variables['field_name'] == 'field_test') {

        foreach ($variables['items'] as $key => $item) {
            $list_field_value = $item['content']['#markup'];
            $list_field_key = $variables['element']['#items'][$key]->getString();
        }

    }

}

Note: replace field_test with the actual field machine name, do not replace field_name.


Best way to create subsites? What's the best way/module I can use to automatically create subsites, like drupalgardens.com.

Is there a module to do it? Can I use drush for this?

If you want something like drupalgardens (aka new sites), you can use drush site-install, but you will still need to create the site directory and what not.

If you have a basic template for the new sites you should probably create an install profile or feature module and have it set everything up.


Flag Friend (D7): add link in block I have created a custom block (that resides with path visibility of users/*).

I have written some PHP code to allow users to message each other (D7 Privatemsg module):

<?php
// Get user object.
if ($account = menu_get_object('user')) {
  if ($url = privatemsg_get_link(array($account))) {
    return l(t('write a mail to this user'), $url, array(
      'query' => drupal_get_destination(),
    ));
  }
}
?>

In that same block, I would like to add another snippet to show a Flag Friend link. This would give me one block with two links: one for mail, one for adding/removing friendship.

Does anyone know the PHP code for flagging a friend?

I think the method below should do the trick. Don't think it is available in the flag_friend module's API.

/**
 * Gets the friend/unfriend link for a given user.
 *
 * Depending on the flagging user's current friend status with the target
 * user, the label of this link will show up as 'Add friend' or 'Remove friend'.
 *
 * @param stdClass $account
 *   Target user object. Defaults to the currenly logged in user.
 *
 * @return mixed
 *   FALSE or
 *   Formatted flag/unflag link otherwise.
 *
 * @see flag_friend_flag_default_flags().
 * @see flag_create_link().
 */
function flag_friend_get_friend_flag_link($account = NULL) {
  if (!isset($account)) {
    global $user;
    $account = $user;
  }
  return flag_create_link('friend', $account->uid);
}

Do note that the flagging user is assumed by default to be the currently logged in user which fits your use-case anyway.

Access check happens implicitly. So, if the current user does not have access to friend/unfriend a given target user, then this method will return FALSE.


Can I change the order in which hook implementation by different modules are called? In D6, I use a contrib module, but I would like to override a small bit of its behavior. I have a custom module for that, but my implementation of the relevant hook is called before the implementation in the contrib module, and so the contrib module's version "wins".

Is there any way to change it, and force my own hook to be called last?

Here are the specific details:

I would like to remove the default "Anonymous" user name for unregistered users in the comment form.  I created a small custom module, tweak_comment_form, that implements form_alter hook and removes the default value from the name field (see the answers to my previous question about that).

However I also use a contrib module called RealName, which also implements form_alter. RealName does what I want for registered users (replaces user name with "real name"), but re-assigns default value to the name field.

Yes, very simply, you need to set the weight of your module to be heavier. There's a few ways you can do this, but if your module is a contrib module being release back to Drupal.org then the best way is to set it in hook_install() with code like:

db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULE'");

Alternatively you can use the Utility module to set module weights from the module page, however this is only for your personal installation.


How do I get a list of all taxonomy terms assigned to a node? I have a node and want to get all the taxonomy terms assigned to the node.

In drupal 6 I could use $node->taxonomy and the taxonomy_* functions but these don't exist in drupal 7.

Taxonomy terms are implemented in fields in Drupal 7. Assuming you have defined a taxonomy field named field_category for your content type, you can access it as:

$language = 'und'; // or will be provided by some Drupal hooks
foreach ($node->field_category[$language] as $delta => $value) {
  $term = taxonomy_term_load($value['tid']);
}

If you don't have access to the field name, probably the easiest way for nodes is to query the database directly:

$results = db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid', array(':nid' => $node->nid));
foreach ($results as $result) {
  $term = taxonomy_term_load($result->tid);
}

Keep in mind though, that you may end up dealing a jumble of terms from different vocabularies if you have more than one taxonomy field.


How to turn off panels in-place edit bar I know this maybe a silly question but how do you hide panels in-place editor bar?(The bar that has layout adjustment buttons.) I found a post that said there's a on/off setting on general settings page that I can use to hide it but I couldn't find that option. I need to hide it because that toolbar is covering Theme developer checkbox. I can't disable the module either because it's in used. Any suggestion?

Click on the "Panelizer" tab of your content type then click on "Full page override" (or whatever view mode that is panelized" and then under settings you will see:

Standard
In-Place Editor

Click the standard.

The In-Place Editor setting is what is creating the tool bar at the bottom.


Show newest nodes for each taxonomy term in Views A block with taxonomy terms and an overview of the newest nodes for each taxonomy term. Every news sites uses this idea.

Business: Article 1, Article 2
Technology: Article 1, Article 2
Sports: Article 1, Article 2

Only article 1 for every node has a teaser and picture...

Any idea how to do this with just one view? You can make a view for each term, but I don't like that idea...

I was trying to achieve a similar thing. I've managed to create a view that gets one article for each taxonomy term using 'Taxonomy term: Representative node' under 'Advanced > Relationship'.

There is also 'Content: Taxonomy terms on node' there which might be more what you're looking for.

Once you've got the relationship you can pull out fields and base filter criteria on that relationship. My view only returns 1 content type for instance.

Make sure your view is on Taxonomy not Content.


Drush hangs out on dl commerce_kickstart in recent days new version of Commerce Kickstart 2 was introduced (v2.55).
I tried upgrading my current installation (v2.54) using drush:

drush --debug dl commerce_kickstart

unfortunately after this line:

Verifying signature for bzr version control engine. [3.27 sec, 42.21 MB]
Executing: bzr root profiles

I'm stuck with this , please give any some tips.
I'm using 7.4.0 drush version.

I'm using drupal 7.60 with Commerce kickstart 2.55 now. I've figured it out. The problem was with the missing command line prompt asking to continue the installation in the current directory.
After debugging drush I noticed that i needed to type "y" than the process started to continue. Anyways it was very strange but finally it worked.


Custom personal contact form with webforms We want our users to be able to contact each other directly, but not give away the email address of the user account.

Personal Contact forms do just this, however, we need a few more fields and other triggers to happen alongside this. Things that webforms already does.

What I'd like to do is use a %get parameter to pass the id of the user they are contacting into the form, and pre-populate the email into a hidden field. This will allow me to use the webform email function to notify user 2 that user 1 would like to contact them.

So there are two users involved. User 1 = logged in user. User 2 = the person they are contacting.

The url would be mysite.org/webformid?uid=2

Where the uid is the id of contact 2.

Using that id, the webform could pull their email into a hidden form field.

Is this possible?

Heather.

You can use hidden fields in your webform which are associated with user's details, such us email, id etc.


Create config object with array containing key-value pairs We have a custom module, mymodule, that we want to use to create a config object for so that it can contain an array of key-value pairs. We need to be able to click button Add More on the form that will add more key and value fields that will be mapped together.

How can we create a form that would not only display existing key-value pairs, but also provide option to add more?

Goals:

On the admin Form, MyModuleForm be able to see existing key-value pairs.
Add more key-value pairs.
Key and value are text fields.
Use the config_object within the mymodule.module file and fetch all the key-value pairs.

Below is what we tried, but got stuck on how to add the Add more functionality and how to properly store customKey and customValue into an array.

MyModuleForm.php

class MyModuleForm extends ConfigFormbase {
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'mymodule.settings'
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mymodule_settings';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.settings');
    $form['customKey'] = [
      '#title' => $this->t('Key value for array.'),
      '#type' => 'textfield',
      '#default_value' => $config->get('customKey'),
      '#maxlength' => 255,
      '#required' => TRUE,
    ];
    $form['customValue'] = [
      '#title' => $this->t('value for array.'),
      '#type' => 'textfield',
      '#default_value' => $config->get('customValue'),
      '#maxlength' => 255,
      '#required' => TRUE,
    ];

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

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration
    $this->configFactory->getEditable('mymodule.settings')
      ->set('customKey', $form_state->getValue('customKey'))
      ->set('customValue', $form_state->getValue('customValue'))
      ->save();

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

To add an add more button you'll need to create a callback function that will increase the number of fields necessary and rebuild that part of the form based on that information. You can make a new config variable based on some sort of index as you do a loop through all the necessary fields.

I haven't tested this so the syntax might be off but here's the basic idea in an example I wrote.

public function buildForm(array $form, FormStateInterface $form_state) {
        if (empty($number_of_member_fields)) {
            $number_of_member_fields = $form_state->set('number_of_member_fields', 1);
        }
        $forms['members_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => t('Member types'),
            '#attributes' => [
                'id' => 'names-fieldset-wrapper'
            ],
        ];
        for ($i = 0; $i < $number_of_member_fields; $i++) {
            $form['members_fieldset']['memberType'.$i] = [
                '#type'          => 'textfield',
                '#title'         => t('Name'),
                '#default_value' => $config->get('memberType'.$i),
            ];
        }
        $form['members_fieldset']['actions']['add_name'] = [
            '#type'     => 'submit',
            '#value'    => t('Add one more'),
            '#submit'   => array('::addOne'),
            '#ajax'     => [
                'callback' => '::addmoreCallback',
                'wrapper'  => 'names-fieldset-wrapper',
            ],
        ];
    }
    public function addmoreCallback(array&$form, FormStateInterface $form_state) {
        return $form['members_fieldset'];
    }
    public function addOne(array&$form, FormStateInterface $form_state) {
        $number_of_member_fields = $form_state->get('number_of_member_fields');
        $number_of_member_fields++;
        $form_state->set('number_of_member_fields', $number_of_member_fields);
        $form_state->setRebuild();
    }


Change display order of View block in Content area of page I have a dynamic view block that is set to display in "content" region of a Basic page. The Basic page has a field that i want to display at the bottom (i.e. after view block)
Question: I cannot figure out how to change display order, so that page displays View block first, then a field from Basic page. Thanks in advance!

Try out the Field as Block:

  Field as Block provides an easy way to display one or more fields of the current node in a block.


Drupal 7 views - distinct not working with ordering by multiple (date) field I have "Episode" content type and some "Showing from" date field in it which is repeating (more than one value can be added). Then I have a view that list episodes ordered by that field, which works, but I want to exclude same episodes. Now if episode has i.e. 3 times that fulfill filter criteria episode will be listed 3 times. I checked "Distinct" option but it doesn't help - still episode is listed 3x.
Actually I'm not very sure how Distinct works - is it possible to select a filed that has to be distinct (if yes - how?) or it works for all fields? I would like to set distinct on episode nid of course.

Apply a filter on the date field
Select the operator: 'Is equal to', and type '0'

  When you have a multiple value field, the field has a list or array of values. delta=0 is the first value

https://www.drupal.org/node/1872262#comment-6869736


How to dynamically consume external RSS feed and display content Drupal 7 with feeds module? Is it possible to consume an external RSS feed with the feeds module - without turning the content into nodes - and display it in a view? I attempted to do this using the aggregator module as described here: External RSS Feed in View and it looked great at first, but then I discovered this bug where the aggregator does not update. https://www.drupal.org/node/2344795. I am now trying to do the same thing with the feeds module, but I don't see a way to have it not create nodes out of the data. I just want it to be dynamic and not create content nodes on my site. Thanks for the help.

I have sucessfully used Views XML Backend in situations like this.


Multiple select do not save for my custom field with custom widget I'm trying to save multiple values from multi select option form which I created in the custom widget with:

$element['labs'] = array(
  '#type' => 'select',
  '#options' => $list,
  '#multiple' => 'multiple',
  '#title' => t('Labs'),
);

The biggest problem is the values won't save! As I know the delta should increment automatically if cardinality is set to more than 1.

1) I can't change cardinality or some other setting after activating the field in the edit field form

2) I can't see my custom field in the field type list to select from if I try to alter existing widgets:

'default_widget' => 'options_select',
'default_formatter' => 'status_field_options',

How could I extend standard list field type to populate the multiselect with my own generated data?

OR

How could I write my widget that Drupal let me save multiple values with different delta?

The values won't save when you don't have any storage to write into.

Make sure your widget implements hook_field_schema() and provide necessary schema for a field structure in your .install file. E.g.

/**
 * Implements hook_field_schema().
 */
function MYMODULE_field_schema($field) {
  switch ($field['type']) {
    default:
      $columns = array(
        'value' => array(
          'type' => 'text',
          'not null' => FALSE,
        ),
      );
      break;
  }
  return array(
    'columns' => $columns,
    'indexes' => array(
      'value' => array('value'),
    ),
  );
}

Then in hook_field_info() make sure you've FIELD_BEHAVIOR_DEFAULT for multiple values behavior, e.g.

/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_field_widget_info() {
  return array(
    'my_widget' => array(
      'label' => t('Default'),
      'field types' => array('select'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

When implementing multiple field properties as part of one widget (such as address field), please check: How to override default cardinality for the field widget?

For complete example, check existing modules under field core module or check field_example module (part of Examples).


Display Author Pane in view (with Display Suite View Mode) I'm new to Drupal, but I couldn't find an answer for my problem in any other thread.

I've installed and configured Author Pane and I'm able to see it in places like a node page or advanced forum topic.

Now I'm creating a View that returns a list of nodes, and configured one of its Display Suite view modes for displaying each result (this view mode includes the Author Pane block for that content type).

The list of nodes is displayed OK, but the Author Pane is not being shown. The section of the view mode layout where the Author Pane should be displayed is empty.

I've already tried making a relationship with Author and setting the Author:name as one of the view's fields (I've read sth like that in some other posts), but nothing changed. It's like Author Pane cannot find any user context information.

Can someone help me with this issue ?

As a (maybe) related issue, I have another view that ends up in a block, which should also display the Author pane. This block appears at the bottom of a node page, which also has Author Pane configured. In that view block, Author Pane is actually being display for each results but always with the information of the user of the page's node! So, every secondary node related with the primary node displays the same Author information as the primary node, instead of its own author's information. I think both issues are related. There is some problem with Author Pane trying to get user information from views.

Thanks everybody in advance!

For anyone who ends up in my same situation, I will post the answer.

Author Pane is only prepared to be displayed on full view nodes, but not in View's lists or Display Suite custom view modes. This is because calling the function "menu_get_object()" will not retrieve anything.

What you need to do is to alter Author Pane's function "author_pane_get_block()" or find a way to implement a hook to do the same thing properly.

I quickly edit the first condition removing the numerical condition of arg(1) and after $node = menu_get_object() line, I check if node is not set, and in that case, I assign $node variable the current view node from somewhere in the context. (in my case, I could get it from Display Suite context, but you can get it from anywhere, including (in the worst case) the stacktrace arguments.

Hope this helps someone!


Where should I download libraries for modules through composer? I've started to use Drupal 8 and some modules requires some libraries.
For example search api solr. When I'm installing these libraries via composer it downloads the libraries into directory of the module.
For example modules/contrib/search_api_solr/vendor.
I don't think that it's correct because contrib modules should be stored in clean state.

What the right way to install libraries for modules via composer?
Where should I store them?

Install Composer Manager, then you won't need to think about it:

  Composer expects each project (Drupal installation, in our case) to have a single composer.json file listing all required packages. Composer Manager allows each contributed module to ship with its own composer.json file, listing the module-specific requirements. It then merges the requirements of all found modules into the consolidated composer.json file. This results in a single vendor/ directory shared across all modules which prevents code duplication and version mismatches.


CKeditor via CDN optional plugins The latest Drupal Ckeditor Module 1.14 loads the Ckeditor library via CDN.
The table on http://ckeditor.com/presets-all shows the 5 possible packages to be used via CDN.
I am using the Full-all package.
This package has a lot of optional plugins.

How can I activate these optional Ckeditor plugins in Drupal ????

In the CKEditor profile area if I am hearing you correctly:

  admin/config/content/ckeditor


How to only allow specific users to edit certain "fields" when creating content? I want to be able to hide specific fields form users on the create content form. For example, I might let any authenticated user create an article but only the editors can use the upload a picture field and the category field.

Use the Field Permission Module. This will provide the functionality you're looking for.


Search API vs. Apache Solr Search I have been using the Apache Solr Search module in Drupal 6 and am looking at the Search API for a Drupal 7 install. I have seen some discussion here but I am looking for any reasons for choosing one or the other.

Is there a reason to choose one over the other? If so, why or why not? I have heard there may be complexity issues and/or performance issues with Search API. Is this true?

I've tried using both and I can say this: it depends on your situation.

Currently, the stable 7 release of the ApacheSolr Integration module can only index nodes.  So if you have non-node entities that you need to index, you have to use the still in progress multientity patch for it.  ApacheSolr Integration can store a lot of different data of content when configured properly.

The Search API does index entites and has a lot of wonderful stuff written for it.  However, Search API only fetches the id of the data you are searching for.  This means to load any more data other than the ID will require an entity_load, hitting your database or whatever caching layer you put in place.  For search-heavy sites, this might not be the most optimized solution.

Here is a great presentation given at drupalcon chicago about the ApacheSolr Integration module, minute 16 for mentions to Search API.


Why is the drupal.org site not using the more recent Drupal version? Seems to me that if drupal.org is encouraging people to use Drupal 8, that they should be leading by example and migrate their own site to Drupal 8.

On drupal.org:

<meta name="Generator" content="Drupal 7 (http://drupal.org)">

Is there a reason why they've released Drupal version 8 but they themselves are still using Drupal version 7? Should the fact that they have not migrated give us any suspicious reasons why we shouldn't quite yet?

Drupal.org is huge website the migration can take some time. The migration from Drupal 6 to Drupal 7 was finally done 2 years ago and it took forever. Moving forward to Drupal 8 is going to take a lot time. I do not see that happening like in 3 to 4 years.

Moving to Drupal 8 is not a higher priority right now for Drupal.org, compare to adding new features and improving the current website.

Drupal.com is a smaller website is been running Drupal 8 since Beta.


How do I embed a 2nd level menu block? I need to embed the 2nd level menu that show up in my 2nd level page /maintenance

in the next level page /maintenance/add-task

Drupal does not have this kind of setting, I'm looking a lot in the core files to try to figure out the proper API code to embed, one of my attempts:

$block = \Drupal\block\Entity\Block::load('block_modules_menu_second_level');
$variables['menu_second_level'] = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

That code is for a simple block, or a custom block.
How to evoke the drupal core menu level 2?

What am I missing?

Not quite sure, whether I got you right. Here's my guess:
Depending on which theme you use, it may be that it is not a problem with the menu template. In my case, the (main) menu was configured to show only one level in the block settings.

I found out by chance, here is how to change it:

Go to https://<yourdrupalpage>/admin/structure/block
on the respective menu block item (e.g. main menu) click configure
adjust the number of visible menu levels to your needs

that should to the trick


Multisites with subdirs for each site I'm starting with Drupal and I would like to have one instance of Drupal on my dev plateform with each project in a subfolder:

I don't want to have to change my host (and my customers hosts)
I need to keep drupal in a subfolder on my domaine (mydomain.tld/drupal)

Every website should be accessible like this :

mydomain.tld/drupal/customer1.com
mydomain.tld/drupal/customer2.org

I know that I have to add some configuration in sites/sites.php and I tryed:

$sites = array(

    'mydomain.tld.drupal.customX.com' => 'customerX.com'

);

But it looks like the rule is not used and I have a not found error...

Could you help me with that?

You need to create subfolders like this:

yourdomain.com/drupal/sites/site1.com

yourdomain.com/drupal/sites/site2.net

yourdomain.com/drupal/sites/site3.org

and park domains site1.com , site2.net , site3.org to folder yourdomain.com/drupal/


PayPal handling with Simple Payments? I'm using Simple Payments to handle PayPal processing in a module I'm building (See previous question).

The first part is fine -- it sends data to PayPal okay, but now that users can pay, I need to write the post-transaction handling code (which will ultimately store that the transaction succeeded in the database.). I'm supposed to use hook_simple_payment_process, but there's very little documentation. In its entirety:

/**
 * Passes a completed payment to the module that created it for processing.
 *
 * @param $payment
 *   A payment to be processed.
 *
 * @return
 *   TRUE if the payment was successfully processed.
 */
function hook_simple_payment_process($payment) {
}

What am I supposed to do with this...?

Thanks!

You need to process the payment. In your case you could mark that the invoice has been paid, maybe in storm or a custom table.  $payment should hold all the info about the payment that you need. I guess some of the info depends on your module as well.

Anyways when you have processed the payment you should return TRUE which will make the simple payment module mark that payment as being processed. I imagine that there is an interface that will allow you to see if a payment hasn't been processed, which would happen if an error occurred while processing.


How do I check the image's view mode in the image.html.twig template? I'd like to detect the custom view mode (Structure > Display Modes) selected for an media entity (image) and then be able to have html output based on the view mode. Specifically I have a custom view mode named 'top_banner' and would like to change the formatting of the default  element when this view mode is selected. Here is what I have in my image.html.twig template:
{% if view_mode == 'top_banner' %}
    <img{{ attributes.addClass(banner) }} data-cover/>
{% else %}
    <img{{ attributes }} />
{% endif %}

This however does not seem to detect the view mode. Currently the image is output in the default format <image {{ attributes }} />.
The image is a media entity field and is part of a Paragraph type named x_banner. The x_banner Paragraph is then referenced on the x_page content type.
I've searched and can't seem to find an instance where this is implemented in the field.html.twig
or image.html.twig template.
Any assistance with this would be greatly appreciated.

If you're using a Media entity, you can check the view mode in the media template: media.html.twig:
From the media.html.twig file documentation:

view_mode: View mode; for example, "teaser" or "full".

This would let you add the class to the image parent <div>.
If you want to target only images, you can do this:
media--image.html.twig
And if you want to target only images with the view mode abc, you can do this:
media--image--abc.html.twig


Generating Content Type at once It is very time consuming to define fields, set their types and validation while creating a content type. It's a nightmare if the fields are exceeding in numbers (say more then 10).

Is there any way to define all the fields, their types, structures, validations one time on a page and generate the whole content type at once?

There is none, and there probably will not be one. Drupal is modularised, pluggable system. Each and every module can provide it's own field types, validators, widgets. They have custom settings defined in their modules. There are per field settings, and settings specific for a field in a given content type. Module to provide it all on one screen would need to know about all these modules and their form elements, and there are no hooks for that now. It would be a big job to hack it together with what's provided.


Update imported feeds to only get one taxonomy term per node I have used feeds to import some nodes with taxonomy term reference.

The source XML is the following one.

<items>
  <item>
    <title>Test 1</title>
    <body>Test body 1</body>
    <term>My_term_foo</term>
    </item>
</items>

First import is OK. I edited <term>My_term_bar</term>, and started importing a second feed.
After the second time, the node has both "My_term_foo" and "My_term_bar," but I need only "My_term_bar" from the second import.

Is there any hook_feeds_node_item_presave() I can use to alter the values being imported?

EDIT:

My final code of hook_nodeapi inpired by sel_space:

switch ($op) {
      case 'presave':
        if ($old_node = node_load($node->nid)) {
          $taxonomy = array_diff_assoc((array) $node->taxonomy, (array) $old_node->taxonomy);
          if (!empty($taxonomy)) {
            $node->taxonomy = $taxonomy;
          }
        }
        break;
    }

If data needs to be modified before it is saved use this module : Feeds tamper

For advanced modification use hook_nodeapi in drupal 6 with the insert parameter , with hook_nodeapi load the old node like this :

$old_node = node_load(node->nid);
$node->taxonomy = array_diff($old_node->taxonomy,$node->taxonomy)

So now you are sure that the $node contain only the new value , Hope this  will help


Getting path alias on the base of term id Foolowing is the code to display breadcrumb, it will display the results like this Parent1/Parent2/Parent3/..

$var1=taxonomy_get_parents_all("term_id");
for($j=sizeof(intval($var1)) ; $j>=0 ;$j--)
{
  print $var1[$j]->name."/";
}

Here I want to compute the path alias for each parent, any suggestions?

To get the alias of a term : drupal_get_path_alias('taxonomy/term/[tid]').

Just a suggestion : To print the breadcrumbs you should try Custom Breadcrumbs module.


Feeds: Hook after Import done I am wondering how to implement a Hook after the import of one of my importers is finished. The last imported node and the name of the importer itself would be the parameters that i need to have at this time.

Background/Usecase:

The site I'm working on is built to control IT-projects. After the user imports the bill-positions (each one a row in a CSV file => node in Drupal), which happens monthly, the site has to check if all bill-positions for a customer have been invoiced.

This is only one example, there are many other examinations that need to be done after an import is done.

I read the Feeds API & documentation, but I didn't find anything useful.

P.S. I'm pretty new to open source and Drupal itself; so please correct me if I am missing any guideline.

I have never used this, but you can try hook_feeds_after_import.  You will likely need to kpr the $source parameter to the hook.

You may also be able to something with Rules.  Feeds events don't appear in Rules (unless there is a module I don't know about), but you may be able to trigger on the node save and update events filtered to the content type(s) that you are importing to.


Referenced Entity as an Exposed Filter I have 2 Content Types: Activity and Event.
For each of Event node, there will be an Entity Reference field which References Activity Node.
Example:
Event:

Title: Hiking in Utah
Activity: Hiking (Entity reference field referencing Activity node hiking)

I am Referencing Activity In an Entity Reference Field in Event Content type...
How can we use "Referenced Entity" within Views and make them available as Exposed Filters ?
In the end I want the Referenced Entities to be visible in a Dropdown field and filter results on selection.
I've had a look at EVA, but i am unable to understand if that can be used to accomplish this.

You have to actually go into your entity reference field settings on your content type and enable the following:

Render Views filters as select list.
Provides a select list for Views filters on this field. This should not be used when there are over 100 entities, as it might cause an out of memory error.

This will then allow your exposed filter in views to be rendered as a select list.


How would I monitor if a new entity had been saved? I am creating a module that I want to run when an entity is saved. I have used rules in the past but the overhead on the module means that I cannot use it. Is there another way that I can do this?
Thanks

If you need it to run for all entities, then your module can implement hook_entity_insert() for new entities and hook_entity_update() for changes to existing ones.

If you just need to target specific ones (node, user, etc), then most of the modules that implement entities also have insert and update hooks.


How can I setup multiple database connections? Can anyone help me to setup connection with multiple databases connection in Drupal 8? I have database on the same server and I want to access it along with default Drupal 8 database.

This is done in the same way as in Drupal 7: You can add the database credentials in your settings.php file.
$databases['default']['default'] = array(
  'database' => 'drupal8',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['external']['default'] = array(
  'database' => 'external',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

You will now have two connection options, default and external. You can tell Drupal to use the external connection using \Drupal\Core\Database\Database::setActiveConnection('external') and switch back to the default one with \Drupal\Core\Database\Database::setActiveConnection() once you don't need anymore the external connection.


How can I have Exposed filter of Flag type in views? I want to add Exposed filters of flag types in Views.

I have many flag types and I want users to be able to select their favorite Flag type to show result.

You can follow these steps:

You can create taxonomy terms for your flag types.
Add  term reference (taxonomy reference) field in your content type pointing to flag taxonomy.
In your view, add filter of taxonomy terms then and check exposed filter checkbox.

You can use Better Exposed Filters module for better UI.


How can I distinguish dynamic pages on a hook_menu? function mymodule_menu_local_tasks(&$variables) {
   if ( request_path == 'yadda') :
   ....
}

I can do that.. but the problem is I want to include this for the tabs on user/$id/edit and I'd rather not do regex or check the beginning and end of the string...

Is there some way I can pull a variable that relates to that specific page type?

You can tell if you're on a node page with menu_get_object(), but other than that it's difficult. menu_get_object() can return other objects than a node, but you need to know the type of entity before you call it (not much help in your situation). There's no generic solution that I know of in Drupal 7.

There is the drupal_match_path() function though, which you can use with wildcards, e.g.

if (drupal_match_path(request_path(), 'user/*/edit')) {
  // On a user edit page
}


"Send email" action not working to send email to poster of comment I have successfully set up email notifications on my client's blog for administrators when new comments are posted and am now trying to set it up to send a thank-you email to the poster of the comment as well. I set it up using triggers and actions as described here.

I put in [comment:author:mail] in the "Recipient" field on the action configuration form as suggested in the note right below that field, but it seems that it never sends the email. I initially tested it using my own email address and it worked fine, then I posted a comment as an anonymous user using two different email addresses of mine but never received an email. Why is [comment:author:mail] not working? I'm using other variables in the body of the email (e.g. [comment:node:title]) and they're working fine.

I tried using Maillog as @tenken suggested below, which verified that the problem isn't with mail delivery but rather with the email not being populated correctly:

Here's a screenshot that shows the email to the administrator is working correctly, but not the thank-you email:

This question can be very hard to answer -- email is tricky as PHP just hands off your email to the underlying/remote mail system. I suspect nobody can tell you exactly what's wrong without in-depth examination of your setup.

But, the Mail Developer module will allow you to "try" to send and log raw emails without actually sending them, you can likely look for differences between mails that do send -- and the emails you think are not sending correctly.

  Maillog provides an easy possibility to log all Mails for debugging
  purposes. It's possible to prevent the mails to being sent, so there
  is no need for an extra mail server to test the mail functionality of
  other modules or the drupal core. Additionally you can immediately
  display the mail through the devel dpm() facility.

  If you like to upgrade from a previous dev release, please disable,
  uninstall and reinstall again. There's no upgrade procedure yet.

Also see the similar modules on the project page -- for additional tools to debug and resolve your problem.


How to filter view results by currently logged-in user's (NOT AUTHOR'S) role? I have a view which displays node titles. Each node has different role assigned. Currently no matter what role user has, he sees all the node titles. How do I filter view results, so that it would only display nodes, which has the current user's role only?

In Filter criteria, you can choose current user, with the help of which you can filter view with current logged in user.


How can I save an Advanced Action on Drupal 7 installation when there's no save button? I am at the 'edit / configure an advanced action page' and I try to create or edit one of my "send email" actions (admin/config/system/actions/configure/...) However, I notice that the form has no save button.  It's not there whether overlay is on or off.  How do I save it?  My core and modules are all up to date as of today.  I am logged in as adminstrator and have rights to do everything (I checked that).

Here's my setup:
Drupal core 7.15
Includes: Aggregator, Block, Blog, Book, Color, Comment, Contact, Contextual links, Dashboard, Database logging, Field, Field SQL storage, Field UI, File, Filter, Forum, Help, Image, List, Menu, Node, Number, Options, Overlay, PHP filter, Path, RDF, Search, Seven, Shortcut, System, Taxonomy, Text, Toolbar, Tracker, Trigger, Update manager, User

Modules

Backup and Migrate 7.x-2.4
Chaos tool suite (ctools) 7.x-1.2
Content Access 7.x-1.2-beta1
Entity API 7.x-1.0-rc3
Features 7.x-1.0
Feeds 7.x-2.0-alpha5
Job Scheduler 7.x-2.0-alpha3
Mailhandler 7.x-2.5
Pathauto 7.x-1.2
Rules 7.x-2.2
Strongarm 7.x-2.0
Token 7.x-1.2
Token Filter 7.x-1.1
Webform 7.x-3.18
Release notes

Includes: Webform

Themes
The Morning After 7.x-1.0-beta3.

The Module "Token 7.x-1.2" is the culprit.  By disabling this module, the Save button again appears on the page.  Of course, to disable the Token module, I must also disable two other modules first.  Hence it's not a fix at all but a work-around because I have to re-enable this module for PathAuto.  I will attempt to submit an issue with the Token module.


Returning custom array in lazy builder callback I have to return a custom array from a lazy builder callback and then loop through that array in a Twig template for a custom block. Here is my code so far:
Custom block:
public function build() {

return [
  '#theme' => 'custom_theme',
  '#variables' => [
    '#lazy_builder' => [static::class . '::lazyBuilder', []],
    '#create_placeholder' => TRUE,
  ],
];
}

The callback
  public static function lazyBuilder() {

  //code above
      foreach ($vars as $var) {
        $arr[] = [
          'title' => $var->getTitle(),
          'body' => $var->body->value),
          'summary' => $var->summary->value,
        ];
      }
    }

    sleep(3); // For testing only
    return $arr;
  }

In my twig template
{% for var in variables %}
  <div>{{ var.title }}</div>
{% endfor %}

For each item I want to display its title, body and summary. Everything works fine if I return from the callback an array which has #markup inside, but I need to return my custom array.
If that's not possible it would be also OK if a lazy loaded the whole block not just the content inside it.
Thank you.

I have to return a custom array from a lazy builder callback

You can return multiple #markup elements nested in the render array, also other render elements like #plain_text, which is more safe to output a title containing user input:
  'title' => ['#plain_text' => $var->getTitle()],

For the body field you need a more complex render element, see How to safely render node body on a custom variable?

and then loop through that array in a Twig template

You can't loop through the array in the theme because you have set-up the variable to be lazy-built. The array doesn't exist at this point, only the placeholder. The array needs to be a proper render array which can be rendered recursively as explained above.

If that's not possible it would be also OK if a lazy loaded the whole
block not just the content inside it.

Blocks are lazy-built by default and placeholdered when meeting the auto-placeholder conditions. See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


Is it possible to make a entity reference field translatable and keep content in existing translations? In our current project we use entity reference fields widely. There is quite a lot of content that already has translations.

Now we would like to enable translations of some of these entity reference fields.

When I did so I noticed that only the original language version of the nodes keep the contents of the fields - the translations show up with an empty entity reference field.

Did I just stumble into yet another Drupal gotcha? I looked through Drupal 8's issue queue but could not find anything related.

Normally you don't need to make the entity reference field translatable to translate the content. This is only necessary if you want to define for each language different target ids.

But this is a different issue. If you enable translation for a field the translated fields have not yet content. This is not specific to reference fields, it is the same for all field types. Only when you create new translations the field values are copied, so that the form is prefilled with the untranslated values. So if you change the field structure in this way and you want to start with all existing translations prefilled you may need an update script for the existing field data.


Load library dynamically depending on settings My theme has a few settings that can be adjusted, one of them is style.

I want to load the libraries depending on the styles, but without writing them in the .libraries.yml

function my_theme_library_info_build() {
  $libraries = [];

  return $libraries;
}

function my_theme_library_info_alter(&$libraries, $extension) {
  $tmp_theme = theme_get_setting( 'my_theme' );

  $libraries['my_theme.theme']['css']['theme'] = [
      'css/themes/' . $tmp_theme . '.min.css' => [],
  ];
}

This is what I've got so far but I have to clear the cache after changing the style.

I would implement this slightly differently. What you can do is combine all the different style css files into one, and use a className prefix instead of a file name prefix. So instead of having foo.min.css and bar.min.css you'll have 1 css file that's always included but has body.foo {} and body.bar {}  styles in them.

Of course this gets easier with a preprocessor such as SASS: for every element you want to style you can wrap it in their respective body.foo or body.bar parents, without having to manually write body.foo in front of every element you want to style. So I highly recommend you use something like SASS for this, but it's not required at all.

The advantage of this method is I think it avoids problems with caching different CSS files since you're using only one. Also if your original goal of having separate CSS files was to keep them neat and separate then you can do that with your SASS files and they can be compiled into a minified single CSS file by your SASS processor.


commerce multicurrency module currency menu selector not switching currency in Shopping cart I am using commerce_multicurrency module for multi currency support. This module provide two blocks for switching currency of site. One currency menu selector which give enabled currency as links and another block which give enabled currency as select list. I enabled both of the block in header block of site. When i choose any of the currency from these blocks it switch currency of all the products displayed in pages either through views or any other way.

Selecting currency also switch the currency of the cart page in <site-url>/cart but it doesn't switch the currency of shopping cart block placed in header of site. Currency switching in this block is very inconsistent. Sometime it display the selected currency sometime it not. Sometime it show the previous selected currency when i switch any of the currency. This currency switching behavior in shopping cart block works fine when i switch currency on /cart page. It switch the currency of the cart at both places

Total displayed in cart page with individual product price.
Total displayed in header shopping cart block.

But on other pages of site this shopping cart block on header doesn't work as expected. I searched for this issue but didn't find any. I googled this issue also searched the module issue queue and https://drupalcommerce.org/discussions

Thanks in advance.

Here is answer which finally worked for me.

https://www.drupal.org/node/1853638#comment-9385053


Translation for node references not working properly I have two content types: product feature and product. Both can be translated. If I create English product and assign many product features (by node reference inside field collection) and then create translation (ex. French) for this I have rewritted product features. Then I can select Product features translated previously to French. English product have English product features and French product (translated) have French product features (also translated).

PROBLEM:
When I modify French node (change product features to French) my English node is also changed (product features are French).

Did I missed something?

The only solution I found is to remove all elements in field collection of translated node and add them once again - with properly translated elements/values.


Parameters in URL go away after Login On my Drupal 7 site, I am using the Prepopulate module to pre-fill a field based on a parameter in the URL for authenticated users.

An example of a URL is:

  http://website.com/node/add/content-type?edit[field_test][value]=123456

When accessing the URL as an anonymous user, Context shows the login block.

After logging in, it redirects the user back the same URL BUT without the prepopulate info.

Simply something like:

  http://website.com/node/add/content-type

Is there anything that can be done so that the information in the URL is not lost after logging in?

You can use a destination parameter in URL to retain those values. There is a good read on drupal.org (https://www.drupal.org/docs/7/theming/overriding-themable-output/how-to-add-a-destinationurl-to-the-request-new-password)

Let me know if you need any help.


PHP filtered page is cached With a few years of Drupal 6 and 7 experience, I've happily made my first Drupal 8 installation. In my previous installations of Drupal I've used custom made PHP code that does a lookup in a personal database. I still need this in Drupal 8.

I've managed to install the PHP filter, and scripts are executed fine, but the page becomes cached, and changes in my database are not seen before I edit the page or empty the cache manually. Inconvenient, to say the least.

According to documentation, PHP filtered pages will not be cached, but evidently my page is.

Any suggestions?

PHP filter is an unrecommended module and you should not use it. It not a secure option and the site maintenance is too difficult.

My recommendation is avoid this module and implements a dummy module with this functionality.

If you decide to use in any case, as you told correctly this pages should not been cached but it depends of your cache config and the place where the php-text is located. I mean, you can use the php filter text in a view or in a block (for example) and the cache behavior will be different.


8 - How do I check if a comment is from original poster? I have a page where written articles are displayed. The following is a article written by Canada_Girl1993.

As you can see, the author of the article is displayed at the top.

Now, other users are able to comment on this article, as well as the author of the article. But how can I check if a comment is from the author of the article, so that I can add some styling or html to it?

Actually, before you write any code... D8 automatically adds a 'by-[entity-type]-author'(e.g. by-node-author) class to the <article> tag of each comment, if commenter and author are the same.
This is defined at line 73, in comment.html.twig file(at least this is the case in Bartik theme file), so please take advantage of it :)


Configuring the temporary directory I have recently moved a site from a localhost to a VPS. I have managed to make the public and private files writable; however, I am not sure where to find the temporary folder and how to change the permissions. I keep getting this message:

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

I am using Virtualmin, Drupal 7, and a Debian server. My current temporary directory is /tmp.

Check  Administrator -> Configuration -> Media -> File System to personalize your tmp path. Make sure to use relative paths and have the right privileges for the Apache user.

I personally like this article fix file upload. He has good observations. It worked for me.

Recently, I downloaded my site to my Mac computer. It happens that in my Mac I was using mod_userdir for Apache and I forgot that in /etc/apache2/users/nameofuser.conf I need to set AllowOverride All, otherwise I will have the following message:

  The specified file temporary could not be copied because the destination directory is not properly configured.


Get a list of available migration destination plugins how can I get all available migration destination plugins?
A way to ask with drupal console?

like listed on Migrate destination plugin examples

With Drupal Console:

$ drupal debug:plugin migrate.destination

Or short:

$ drupal dpl migrate.destination

gives:

------------------------------------------ ---------------------------------------------------------------------------------------
  Plugin ID                                  Plugin class
 ------------------------------------------ ---------------------------------------------------------------------------------------
  component_entity_display                   Drupal\migrate\Plugin\migrate\destination\PerComponentEntityDisplay
  component_entity_form_display              Drupal\migrate\Plugin\migrate\destination\PerComponentEntityFormDisplay
  config                                     Drupal\migrate\Plugin\migrate\destination\Config
  d7_theme_settings                          Drupal\system\Plugin\migrate\destination\d7\ThemeSettings
  entity:action                              Drupal\migrate\Plugin\migrate\destination\EntityConfigBase
  entity:base_field_override                 Drupal\migrate\Plugin\migrate\destination\EntityBaseFieldOverride
  entity:block                               Drupal\block\Plugin\migrate\destination\EntityBlock
  entity:block_content                       Drupal\migrate\Plugin\migrate\destination\EntityContentBase
  entity:block_content_type                  Drupal\migrate\Plugin\migrate\destination\EntityConfigBase
  entity:comment                             Drupal\comment\Plugin\migrate\destination\EntityComment
  ...

With drush:

$ drush php
>>> array_keys(\Drupal::service('plugin.manager.migrate.destination')->getDefinitions());

gives:

=> [
 "entity:block",
 "entity:comment",
 "entity:comment_type",
 "d7_field_group",
 "field_group_entity_form_display",
 "field_group_entity_view_display",
 "entity:file",
 ...
]


Apache Solr support for custom entities Does apache solr module supports the indexing of fields attached to custom entities?

If you want to get an easy to use search, you should consider using Search API where you can use a Solr backend and index entities, fields and even relations to other entities.

The apache solr module is more an API to Solr then a ready made search engine (though the module does offer some various search addons), which means you can index whatever you like, but you might need to write some code for custom entities.


10,000+ nodes vs. 1 node with 10,000+ field collection items I need a sort of term database with around 3 fields that won't be used during normal site operations.. Only when I, the administrator, add content.

I'm wondering about how to minimise performance impact for regular users.. My intuition tells me that a field collection would be better so the nodes table is smaller.

I will be likely be using some code to add data from APIs and Rules to fetch the data by property.

Which should i use? I don't have much interest in creating a custom entity type unless it's really easy.. I want image and audio fields and I don't know if that complicates things.

Loading 1 node with like 10,000+ field collection items sounds like performance suicide if you don't limit the amount of items being loaded and displayed initially. And having to open a node with 10,000+ field collection items only to maybe add or edit one item will be really big pain then.

With nodes, much likely you'll never display all of them at once. You very likely will have them organised in Views. Limited display, pagers, filters, lots of caching possibilities. When you want to add a node, you'll have a fresh node form, loaded in milliseconds. Plus you will have a much larger number of contrib modules available dealing with sortability, searchability, orderability and a lot of other -abilities that come in handy when organising content. Also when it comes to content import.

Go for 10,000+ or even 1,000,000+ nodes. That's what Drupal is made for.


Revert views missing. Any workarounds? In Drupal 8 reverting views to their original (in the core, custom or contributed module) became difficult. Supposedly the module config_update would allow reverting a view, but that promises to be a more laborious than simply clicking a link like we were used to in Drupal 7.

I was wondering if it would be possible to make selected views read-only? That way administrators with Views UI permission would have no edit link forcing them to work with a duplicate.

Hints on how to accomplish this? Any other possible workarounds?

A simple workaround without an additional module would be to copy and paste the content of the yaml file views.view.[view-id].yml you find in the module's /config/optional folder to www.mysite.com/admin/config/development/configuration/single/import.

Select the configuration type "View" and add the first line containing the UUID from the active configuration (switch to Export - Single item).

If you have to do this on a regular basis then the recommend way is to manage the configuration with Git, see this tutorial Using Configuration Management and Git to Track Drupal 8 Configuration.


How do I add JS files inside libraries conditionally based on versions of IE7 and IE8? In Drupal 8, how would you load a JS file inside a library to only load on IE8 but not lte IE7?

I have the following added which correctly loads only on IE8 and lower.

js:
    js/script.js: { browsers: { IE: 'lte IE 8', '!IE': false } }

But, how would I only load this on IE8? and also how would I load a different js file for IE7? Would this work for example:

js:
    js/script.js: { browsers: { IE: 'IE 7', '!IE': false } }

You have the right idea. You can do what you've done for IE7 with IE8 as well.

js:
  js/script7.js: { browsers: { IE: 'IE 7', '!IE': false } }
  js/script8.js: { browsers: { IE: 'IE 8', '!IE': false } }


Customize create content page I'm wondering if there's a way to customize the create content page (not the content display page), including recordering and repositioning things.

ATM it's "Title" on top, followed by "Body" on the bottom, followed by other fields like "Upload" and "Save".

Is there a way to customise the labels, reorder and repositon this page?

For example: To move "Upload" on top and in the middle, followed by "Title" and "Body" below it while changing the label of Body to "Description", and changing the caption of the "Save" button to "Submit"?

Thank you very much.

Yes, it is possible. Firstly you need to read and understand the Drupal 7 Template (Theme Hook) Suggestions documentation to render and rearranging field items.To alter Title , Body, Save etc you will need to understand hook_form_alter, it is used for altering a form and hook_form_FORM_ID_alter is a smarter way to do the same as hook_form_alter.There is a cool hook_form_alter tutorial hope will help you.


Adding parameters to $header links Is there a way we can specify which link to use to sort a drupal table, or atleast, specify some parameters to the header links?

To be more clear, my table uses the following link when I click on the headers to sort the table: http://mysite.com/node?sort=asc&order=Name

What I would like the header link to look like is this: http://mysite.com/node?nid=123&pager_element_id=3&sort=desc&order=Name

Is there any way we can give the parameters to the header links?

The code that outputs the links for the table header is contained in tablesort_header().

$cell['data'] = l($cell['data'] . $image, $_GET['q'], array('attributes' => array('title' => $title), 'query' => array_merge($ts['query'], array('sort' => $ts['sort'], 'order' => $cell['data'])), 'html' => TRUE));

The function is called from theme_table(), which is the theme function used to render a table.

What you can do is implementing your theme function that is then used to render the table your module is outputting. There isn't any other method, as theme_table() is not getting any parameter that changes the URL for the table header; as such, implementing hook_preprocess_table() would not achieve anything.

To implement a theme function, you need to declare it using hook_theme().

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_table' => array(
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
    ),
  );
}

Once you declared the theme function, you can use it as you used theme_table(), simply replacing any call to theme('table', /* the rest of the arguments */) with theme('mymodule_table', /* the rest of the arguments */). Notice that in hook_theme() the theme function is referred as mymodule_table, but the PHP function is theme_mymodule_table().

The code you need for your theme function is the same used by theme_table(), except that instead of calling tablesort_header() it will call your own function.

foreach ($header as $cell) {
  $cell = tablesort_header($cell, $header, $ts); // Replace it with the call to your function.
  $output .= _theme_table_cell($cell, TRUE);
}


How to include attributes of the MySQL table to hook_schema() schema in drupal 7? I am creating a table using hook_schema()

I am referring phpMyadmin to create a new table. In the phpMyadmin there is a
column 'Attributes'

which has values as 'unsigned' or  on update CURRENT_TIMESTAMP'
I have a row in a table which is of type 'timestamp' and has attributes 'on
update CURRENT_TIMESTAMP'.
How can I  include this attribute on update CURRENT_TIMESTAMP in the hook_schema() ?

Also there is  a default column in phpMyAdmin how can I add that in hook_schema() ?

the first time I created a hook_module_name.install a table was created as it was specified in the hook_schema()

Then I uninstalled that module but the table was not deleted ?
Now I even removed the .install file cleared the cache , even after this  a table is not created. What can be the solution to this problem.

What I have checked is that it is entering into hook_schema function but the table is not generated at the database. Any hints on this would be appreciated.

You can't use an ON UPDATE unfortunately - Drupal's schema API doesn't give you that sort of dbms-specific control.

You can use unsigned for unsigned and default for a default value though:

$schema['some_table'] = array(
  'fields' => array(
    'some_field' => array(
      'type' => 'int',
      'not null' => TRUE,
      'unsigned' => TRUE,
      'default' => 0,
    ),
  ),
);

See the Schema API docs for the full list of data types and usage.


Is it possible to change the _alt_ text wording for images in one place? Is it possible to change the alt text wording for images in one place, as the wording used does not pass validation?
The website contains a vast amount of pages, most of which with images having poorly worded alt text. Most of the images are inline, but some have been uploaded with the image field.

The site is running Drupal 7, if this makes any difference.

If the images are all inline (i.e. part of the body content of the node) then there is no easy way to change the alt text in one place because these images have not been abstracted into the Drupal system. If these were fields or part of the files table, it might be possible to quickly update these using PhpMyAdmin or some other database solution but at this point your best options are

brute force (just what it sounds like, a painful node-by-node fixin' of the alt text).
try a search and replace option of the body text. I've used the scanner module for this kind of operation and recommend it as it has robust regex support and (most importantly) a rollback option.

Neither of these are great options but they're the best you can do given the circumstances. Which to choose depends on a). how many nodes you have to deal with, and what kind of alt text you have to add. If you're adding the same alt text to every image, scanner is your answer but if you have to evaluate and update each image with appropriate alt text (ex for 508 compliance), brute force is the way to go.


Displaying fields in multiple rows for one node with Views format In a view I need to display a node's fields in multiple rows, how can I achieve that?

The node contains:
Port1Name
Port1Arrival
Port1Departure
Port2
Port2Arrival
Port2Departure
Port3Name
Port3Arrival
Port3Departure

I need the display to be in a table as (for example)

Port Arrival Departure
Istanbul 1/1/11 2/1/11
Mersin 2/1/11 4/1/11
Mykanos 5/1/11 6/1/11

When I used table, it puts all fields on the same row, as it detects the view contains only one node.
I tried with grid..played with settings, no luck.
I tried Views Secondary Row and it only works when I need to have two rows, not more...

How can I achieve this with views formats?

Drupal 7 Field API handles this case very well. I rewrote the Office Hours module using the Field API. Each row has day of week and time open and time close. This would be exactly the same for you except instead of day or week it would be port, time open would be time of arrival and time close would be time of departure.

The solution is to build a custom module with Field API in Drupal 7. Are you using Drupal 7?


Content type adding page is not displaying properly I have a content type and added fields to that . But when try to add a content (the page url is base_url/node/add/content_type) it appear as an administral adding option (Means its not showing the main navigation and side navigation and header images) . Why is it like that ? One thing i noticed that its breadcrumb appear as Home >> Add content, but in real it should be ( that appear in my staging server as Home >> Node >> Add content and appearing the side navigation and main navigation menus )  . I installed node module too .  How could achieve that ?

For admin users you can change this at the bottom of theme settings:

/admin/appearance

☑  Use the administration theme when editing or creating content

On the staging server you probably testing this with a non admin user account, so you won't see a difference there.


css not working in node reference view i am working on a development site. i am on hold because of two problems.

i have two content type A and B. i created a view for B content type. i used node reference in content type A  and call the created view so it display view fields rather than only title of nodes.   my problem is that when i start type any title in this field it display the options in autocomplete but it display white spaces, i add css but it is not working

so the main question is css not working in node reference view result
i added a view in the same manner for a field. i want to add radio button on each result of view ,and when we click on radio button it's value copy in another field of content type.

Thanks , plz help me

Can you get the regular node title to show up? Is the node title important? I am wondering if Automatic Entity Label could help you at all. Formerly Auto Node Title. https://drupal.org/project/auto_entitylabel
You may want to look at Rules and VBO. Creating a Rules Component "Action Set" and adding it to a Views Bulk Operations could handle this use case. Make sure you set the permissions properly when you create the Action Set (there is a collapsed field set called "Settings" when you edit a Rules Component that contains permissions settings for each Component)


Replacing a certain character pattern in a textfield when saving an entity I got an entity type containing a long text field. If a user types in a certain character pattern ("xX" for example), this string "xX" should replaced with "×" (the proper symbol for multiplication) after saving the entity.
I looked at hook_field_presave and hook_field_attach_presave but don't know how to use correctly.

This is the code i tried in a custom module:

function replace_multiplication_symbol_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['name'] == 'field_technical_description') {
    foreach ($items as $delta => $item) {
      if (isset($item['value'])) {
        $items[$delta]['value'] = str_replace('xX', '&times;', $items[$delta]['value']);;
      }
    }
  }
}

So, hook_field_presave, according to the documentation, "Defines custom presave behavior for this module's field types." So unless your defining a field type in your module, this is the wrong hook to use.

Instead, your gonna want to use hook_field_attach_presave. $entity_type will contain the type of entity the save is being called from (node, user, etc). $entity is the full entity object, which you can just go ahead and edit.

For example, a very basic function like so:

function replace_multiplication_symbol_field_attach_presave($entity_type, $entity){
  if(!empty($entity->field_field_technical_description['und'][0]['value'])){
  $entity->field_field_technical_description['und'][0]['value'] = "test";
  }
}

would, whenever an enity is save, check for the field field_field_technical_description and switch it's value to "test," if it's value was not null.


How do I add a child to an HTML Tag render element? I need to reproduce this with render elements:

Can't figure this one out!

Please see the drupal API page on this.

A simple example could be:

// Shows how #prefix and #suffix can add markup into an array.
t('Using #prefix and #suffix') => array(
  '#markup' => '

',
  '#prefix' => '
',
  '#suffix' => '
',
),

or you could use children

t('using children demonstration') => array(
  '#markup' => '',
  'child1' => array('#markup' => '

'),
  'child2' => array('#markup' => '

'),
  '#prefix' => '
',
  '#suffix' => '
',
),


trigger attribute AJAX using custom select element I'm currently theming the product page for a Drupal Commerce site. Our frontend developer has insisted we use his custom "fancy" select dropdown for the attributes, which is causing a bit of a theming headache!

I have implemented his jQuery successfully, and when a user changes the fancy select option, it changes the "selected" option of the hidden select element too.

The problem is that none of the Drupal AJAX calls to update the price  are fired when we change the selected attribute option via jQuery.

Does anyone know how I can force the onChange AJAX call for attribute options via jQuery?

Thanks in advance!

I had the same problem and I managed to find the solution.

You need to call .attr and .trigger

    $('ul.choose-product-quantity li').click(function(){
      var quantity = $(this).children('.product-quantity').text();
      $('.form-item-attributes-field-product-qty input')
      .filter(function(index){
        return $(this).attr("value") == quantity;
      })
      .attr('checked', 'checked').trigger('change');
    });

See attached screenshot as well. Good luck. !

Custom attributes selector (image)


entity reference with multiple values? I've added a new field to a content type, using the Entity Reference module.

The new field is to allow entry of up to 4 related articles (curated content - chosen by the admin) per article.
I've set the field to allow up to 4 values - but using the 'Autocomplete (tags style)' widget it doesn't seem possible to enter more than one option.

Any suggestions/solutions?

To select multiple items with "Autocomplete (tags style)", you must enter a comma-separated list in the text box. Otherwise, if you want to enter the values in separate text boxes, use the plain "Autocomplete" widget type.


Use math in the fields I want to use some math function in the field.
Is there any editor to support all of the mathematics functions?
For Example log,Radical and etc?

You could use the Computed Field module, which allows you to write custom PHP functions to determine field values.  You will of course need to be familiar with PHP.