Form API managed_file doesn't show up I am working with Drupal 7. When I use the following code, nothing shows up in the form; when I change managed_file with file, everything is fine.

$form['mfile'] = array (
  '#type' => 'managed_file',
  '#title' => t('File to upload'),
  '#size' => 22,'#upload_location' => 'public://vm-files',
);

Do you know why this happens?

You have to set the #default_value (as you would nearly any FAPI element) if you want the current set value to show up on the form when you visit the page. I have code such as the following in my module:

  for($i=1,$z=MAX_FRONTPAGE_IMAGES;$i<=$z;$i++) {
  $form["frontpage_image_fid_$i"] = array(
    '#type'            => 'managed_file',
    '#upload_location' => 'public://site_theme_assets/',
    '#default_value'   => variable_get("frontpage_image_fid_$i", ''),
    '#title'           => t("Random Image #$i for Frontpage"),
    '#description'     => t('This image will appear on the frontpage of the  site and have line1 and line2 on top of it.'),
  );
  }

The only gotcha I have when trying to use managed_file is that after save, on edit I get an error about the File status. That's because you should notify the file_usage table that your module owns/uses the file upon upload, eg:

/** callback for fapi admin settings page form that uses managed_file elements */
function foundation_frontpage_admin_submit($form, &$form_state) {
  for($i=1,$z=MAX_FRONTPAGE_IMAGES;$i<=$z;$i++) {
    if ($form_state['values']["frontpage_image_fid_$i"]) {
      $f = $form_state['values']["frontpage_image_fid_$i"];
      // Load the file via file.fid
      $file = file_load($f);
      // Change status to permanent.
      $file->status = FILE_STATUS_PERMANENT;
      // Save.
      file_save($file);

      // I was receiving an error on Edit of a filled out form/file upload.
      // Managed file: the file used in the field may not be referenced
      // The solution is file_usage_add() to this module as commented here.
      //
      // http://drupal.stackexchange.com/a/4819/3279
      file_usage_add($file, 'foundation', 'variable:frontpage_image_fid_', $i, 1);

      variable_set("frontpage_image_fid_$i", $f);
    } else {
      variable_set("frontpage_image_fid_$i", NULL);
    }
  }
  drupal_set_message('Changes saved for frontpage.');
}


Programmatically geting teaser of a field other than body I need to get teaser of a custom field. I used the below code that I used for body.

$fieldContent = field_get_items('node', $nodeObj, 'my_field_name');
$teaser = field_view_value('node', $nodeObj, 'my_field_name', $fieldContent[0],'teaser');
//Below line prints an empty array
print_r($teaser);
$teaser   = drupal_render($teaser);

When I try the above code for the field body it works. What the code expects from the field to display teaser? How to fix this?

Go to your node type's display settings for the teaser view mode and verify that the field is not hidden.


How to change filename before it get saved without changing source URL using tamper plugin? I've URL which is mapped to file field (image) via Feed Ex.

I'm trying to change the filename before it's get saved using tamper plugins (e.g. concat or regex), however it is also changes the requesting URL causing saving the invalid image files which consist html with 404 error.

How do I use Feeds Tamper plugin to modify data (filename) after the file is downloaded but before it's get saved? Or I need to find some other alternative way of doing that?

It seems it's not possible using tamper plugins (as far as I've tried).

As workaround, this can be achieved by using hook_file_presave(), for example:

/**
 * Implements hook_file_presave().
 */
function mymodule_file_presave($file) {
  if ($file->filename == 'ShowImageXML.asp') {
    $filename = date("ymd", $file->timestamp) . '-' . $file->filesize . '.jpg';
    $uri = 'public://images/' . $filename;
    $file = file_move($file, $uri);
  }
}

See also a feature request: #2596841


Get Term ID from URL Possible to get the current URL then grab the term id from it.

com/fishing-report/lakename

lakename being the term. Can i get the Term ID?

Basically you would have to do:

$path = current_path();
$path_array = explode('/', $path); // Doing this you would get the array of all the elements that there in the url.

Once you have the array of items in the array, you would have to do

$term_name = $path_array[1];

So in $term_name you would have lakename, which is your term name.

Once you have the name, simply do

$term_object = taxonomy_get_term_by_name($term_name);

$term_object would have the object of the term.

For more detail: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_get_term_by_name


How to alter the Views UI config form Part 1: How do I add a form element (ie checkbox) to the field of a specific type (ie all image fields) inside the admin Views UI.  What code do I need include in a custom module.

Part 2: How do I save it to the database.

This is not a default view.
I am not creating a need field.  I am trying to alter an existing field.

You need to use Views handlers https://api.drupal.org/api/views/views.api.php/group/views_handlers/7.

Basically, you need to extend the handler class that is used by that field which in your case is field_image.

In order to start and make your custom handler work you need two basic functions to tell Views you mean some business with them. These are  hook_views_api() and hook_views_data_alter() function.

MODULE.module

/**
 * Implements hook_views_api().
 */
function uc_addons_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'uc_addons') . '/views',
  );
}

MODULE.views.inc

/**
 * Implements hook_views_data_alter().
 */
function uc_addons_views_data_alter(&$data) {
  dsm($data);
}

The hook_views_data_alter() function needs to be inside your MODULE.views.inc file.

Lastly of course is your handler w/c adds your field by extending the base handler as you can get more idea from the link. Also from my experience, the saving of values from fields are taken care by Views already.


How can I develop a custom theme from scratch? I wonder how to develop a custom theme from scratch. I understand the overall structure of Drupal theme. I've created an .info file and enabled the theme through the admin interface, but I get a blank screen.

I haven't yet coded any of the theme files. I'm unable to define html.tpl.php, page.tpl.php, node.tpl.php, region.tpl.php.

I do have empty css, js and images folders. In my templates folder I've an empty html.tpl.php, page.tpl.php, node.tpl.php, region.tpl.php, field.tpl.php.

Any suggestions?

Hello World

It seems that the current version of your theme works as designed: empty templates that result in a blank screen, that's exactly what "I" would expect. Try adding "Hello Umair" in any of those empty files, and see what you get next.

Start from an example

A much more effective approach however might be as suggested by longboardnode : copy from whatever theme you like, and apply the "same-as-except"-strategy.

Start from a base theme

Or maybe create a subtheme from your favorite base-theme (Omega, Zen, Bootstrap, ... there are plenty to pick from).

Follow the instructions in the documentation

An extremely basic example you may want to look at: Create a new custom theme with CSS alone. And if you're ready for it, study the Theming guide, especially the Theming Drupal 6 and 7 child pages of it.


What does the 'property_type' key do in hook_field_info()? If you look at the hook_field_info() from Physical Fields the returned array has two keys that aren't mentioned in the documentation: property_type and property_callbacks. Can anyone explain what these are for? (Bonus question, are there any other missing keys in the documentation?!)

They're not part of Drupal core, but are extra keys provided/used by the Entity Module. The comments in entity.api.php clear it up quite nicely:

For providing entity property info for fields each field type may specify a property type to map to in its field info using the key 'property_type'. With that info in place useful defaults are generated, which is already suiting for a lot of field types.
However it's possible to specify further callbacks, that may alter the generated property info. To do so use the key 'property_callbacks' and set it to an array of function names. Apart from that any property info provided for a field instance using the key 'property info' is added in too.

I'm afraid I don't know of any other undocumented keys, but a comment in the same file just above the previous ones notes:

This is a placeholder for describing further keys for hook_field_info(), which are introduced by the entity API.

I would just keep your eye on that file when future versions of the Entity module come out to see if any new ones have been added; property_type and property_callbacks are the only ones mentioned at the time of writing.


Alter Ubercart Billing/Delivery Panes with User Profile Info I'm trying to set a user's profile fields into the checkout process. A user must change these data only in own profile. The uc_addresses module is unsuitable for my needs. In the order form I need to hide these fields.

Right now I'm using uc_cart_checkout_form_alter to do this:

function my_module_form_uc_cart_checkout_form_alter(&$form, $form_state, $form_id) {
        // load user data
        global $user;

        $user_fields =user_load($user->uid);

        $first_name   = $user_fields->field_name['und']['0']['value'];

        // add data to order form
        $form['panes']['delivery']['delivery_first_name'][LANGUAGE_NONE][0]['value']['#default_value'] = $first_name;
}

But default value isn't there. Where did I go wrong? How can I fill out an order form (Delivery & Billing information) programmatically in Ubercart?

The billing/delivery address panes are driven by a custom uc_address form field. You need to alter it's #default_value object to alter the fields.

For example:

$form['panes']['delivery']['address']['#default_value']->delivery_first_name = $user_fields->field_name['und']['0']['value'];
$form['panes']['billing']['address']['#default_value']->billing_first_name = $user_fields->field_name['und']['0']['value'];


Calendar view doesn't display node titles upon first view, but will after Prev/Next are pressed Our calendar is doing some strange stuff. At first, all of the node title are missing.

But by pressing Prev/Next, they then appear

I can't think of what might be causing this issue.

Well, I did a comparison between our development server and production server via drush pml | grep Enabled | grep -i views on each server. I noticed that for some reason I left views_rss enabled on production but not development. After drush dis -y views_rss and drush cc all && drush cron, things appeared as normal.


How to change the redirect URL of a form that's already been set in a module? I'm using the node gallery module in Drupal 6, and I'm having some trouble modifying it to suit my needs. When the manage images form is submitted, the function node_gallery_manage_images_submit is called. At the bottom of the function is this code:

$form_state['redirect'] = 'node/'. $gid;

I need to change the URL of that to 'my_url' instead of node/123. Using the form_alter I can set $form['#action'] = 'my_url'; and when the form is submitted it goes to that page. But the module does a lot of image processing before then, so I have to use the redirect after that's all done. I also tried $form_state['#redirect'] = 'my_url'; but that did nothing. Replacing $form_state with $form does nothing either. Can anyone please help me out? I'm pretty new to Drupal forms and this is the first time I've really had to work with them. I know there has to be some way to do it, I just can't figure out how.

You should be able to achieve this by adding your own submit function to the end of the submit handler array and overriding $form_state['#redirect'] there. Example code:

function mymodule_form_node_gallery_manage_images_alter(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_node_gallery_custom_submission';
}

function mymodule_node_gallery_custom_submission(&$form, &$form_state) {
  $form_state['redirect'] = 'my_url';
}


How to reference existing taxonomy terms in a migration I'm trying to migrate nodes with a term reference field.  The terms are not migrated and already exist in the destination site.  There is a method in the migration class which is confirmed to already select the correct term ID on the new site.

When the migration is run an error appears:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'migration_db.taxonomy_index' doesn't exist:    [error]
SELECT 1 AS expression
FROM
{taxonomy_index} taxonomy_index
WHERE ( (nid = :db_condition_placeholder_0) AND (tid = :db_condition_placeholder_1) AND (status =
:db_condition_placeholder_2) ); Array
(
    [:db_condition_placeholder_0] => 2290
    [:db_condition_placeholder_1] => 4
    [:db_condition_placeholder_2] => 1
)
 (/home/vagrant/docroot/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:770)

The migration appears to be trying to get the term data from the migration database instead of the destination (default) database.

migrate plus yml:

...
process:
  field_section: Section
...

migration class:

class MyNodeMigration extends SqlBase {
  public function query() {
    return $this->select('TableA', 'ta')
      ->fields('ta', ['Id', 'Body', 'OriginalId']);
  }
 ...
  public function prepareRow(Row $row) {
    $row->setSourceProperty('Section', $this->convertToTermId($row->getSourceProperty('OriginalId'));
  }

  public function convertToTermId($original_id) {
    return $this->getDatabase()->select('TableB', 'tb')
      ->fields('tb', ['DrupalTermId'])
      ->condition('OldId', $original_id)
      ->execute()
      ->fetchField();
  }
}

-------------UPDATE-------------

I've also tried using a custom plugin.  The same error occurs.
Plugin class:

/**
 *
 * @MigrateProcessPlugin(
 *   id = "existing_term"
 * )
 */
class MigrateProcessExistingTerm extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $term = Term::load($value);
    return [
      'target_id' => $term->id(),
    ];
  }

}

Updated yml:

...
process:
  field_section:
    plugin: existing_term
    source: Section
...

I was able to solve the issue by moving the queries for the term ID to the process plugin.

/**
 *
 * @MigrateProcessPlugin(
 *   id = "existing_term"
 * )
 */
class MigrateProcessExistingTerm extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    db_set_active('my_migration');

    $sub_task_id = db_select('TableA', 'ta')
      ->fields('ta', ['OriginalId'])
      ->condition('Id', $value)
      ->execute()
      ->fetchField();

    $term_id = db_select('TableB', 'tb')
      ->fields('tb', ['DrupalTermId'])
      ->condition('OriginalId', $original_id)
      ->execute()
      ->fetchField();

      db_set_active('default');

    $term = Term::load($term_id);

    return [
      'target_id' => $term->id(),
    ];
  }

}

It seems like having the queries in the main class were confusing the migration into thinking the term data was in the migration source database.


Additional actions when logging using watchdog Is there a way to perform additional actions every time watchdog logs something? For example, I wanted to record, parse, and compile logs with additional information elsewhere, but still have watchdog perform its default function.

Is there any hook I could use?

In Drupal 7, you would use hook_watchdog() to achieve the task, which is exactly the hook implemented by dblog.module, the module that shows in  admin/reports/dblog the messages added with watchdog().

In Drupal 8, you need to implement a service that is invoked everytime a message is logged, for example with the following code.

mylog.services.yml

services:

  logger.mylog:
    class: Drupal\mylog\Logger\MyLog
    tags:
      - { name: logger }

src/Logger/mylog.php

namespace Drupal\mylog\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class MyLog implements LoggerInterface {
  use RfcLoggerTrait;

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = array()) {
    // Log the message, for example writing it in a file.
  }

}

The key is how the service is tagged. Without tags: [{ name: logger }], the service would not be used to log the message.

The example code is taken from hook_watchdog() and watchdog() removed. For an example of code implemented from Drupal core, see SysLog.php, which logs the messages in the Syslog server.

class SysLog implements LoggerInterface {
  use RfcLoggerTrait;

  /**
   * A configuration object containing syslog settings.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The message's placeholders parser.
   *
   * @var \Drupal\Core\Logger\LogMessageParserInterface
   */
  protected $parser;

  /**
   * Stores whether there is a system logger connection opened or not.
   *
   * @var bool
   */
  protected $connectionOpened = FALSE;

  /**
   * Constructs a SysLog object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory object.
   * @param \Drupal\Core\Logger\LogMessageParserInterface $parser
   *   The parser to use when extracting message variables.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LogMessageParserInterface $parser) {
    $this->config = $config_factory
      ->get('syslog.settings');
    $this->parser = $parser;
  }

  /**
   * Opens a connection to the system logger.
   */
  protected function openConnection() {
    if (!$this->connectionOpened) {
      $facility = $this->config
        ->get('facility');
      $this->connectionOpened = openlog($this->config
        ->get('identity'), LOG_NDELAY, $facility);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = []) {
    global $base_url;

    // Ensure we have a connection available.
    $this
      ->openConnection();

    // Populate the message placeholders and then replace them in the message.
    $message_placeholders = $this->parser
      ->parseMessagePlaceholders($message, $context);
    $message = empty($message_placeholders) ? $message : strtr($message, $message_placeholders);
    $entry = strtr($this->config
      ->get('format'), [
      '!base_url' => $base_url,
      '!timestamp' => $context['timestamp'],
      '!type' => $context['channel'],
      '!ip' => $context['ip'],
      '!request_uri' => $context['request_uri'],
      '!referer' => $context['referer'],
      '!severity' => $level,
      '!uid' => $context['uid'],
      '!link' => strip_tags($context['link']),
      '!message' => strip_tags($message),
    ]);
    $this
      ->syslogWrapper($level, $entry);
  }

  /**
   * A syslog wrapper to make syslog functionality testable.
   *
   * @param int $level
   *   The syslog priority.
   * @param string $entry
   *   The message to send to syslog function.
   */
  protected function syslogWrapper($level, $entry) {
    syslog($level, $entry);
  }

}

Notice that in Drupal 8, as in Drupal 7, it is possible to have different loggers active at the same time, so the log messages can be recorded in different ways at the same time.


Free-tagging user accounts Is it possible to free tag user accounts in Drupal 6? For example, a user with appropriate permissions would be able to add tags created on the fly to any user account. If I could limit which user roles could be tagged, that would be a bonus.

Eventually worked out how to do this: use Content Profile module to extend the user account with a node of a custom type, and then create a free tag for that node type.


create link for URL-based text field in content type Drupal 7 question: In my Events content type, I have a text field called RSVP URL. On the event page, it currently displays as

RSVP URL: http://example.com

However, I would like it to be a link, displaying like so:

RSVP URL: http://example.com

I'm not seeing a way to do this, except perhaps via adding the Link module?, but I'm a newbie who's never even installed a module before, and I'm wondering if there's another built-in way. Thanks.

Click on edit in front of your link field in your content type's manage field tab.

You need to change Text processing option to filtered Text.

Then while adding this content type just type the URL with HTML tag.

I hope this solves your problem without installing a module.


Make custom field added to comments available in comment.tpl.php I added a integer list field called "field_rating" to the core comments. Now I want to use the new field directly in my comment.tpl.php with it's display settings, but I just don't know how to do that despite this should be a no-brainer. Help is much appreciated.

All you gotta do is add <?php print render($content['field_rating']); ?>


Access EntityEmbedFilter process function in a preprocessor I'm getting the value of a wysiwyg field in a preprocessor then passing it to Twig in a #markup render array. Everything works as expected with the exception of embedded images. I've modified the list of XSS allowed tags to allow the drupal-entity tag. However, it seems that this is being passed to Twig after the EntityEmbedFilter has opened and closed.

I'd like to use EntityEmbedFilter process function to process the value of my field prior to passing it to Twig. However, when trying to instantiate an instance of EntityEmbedFilter with the new keyword, I get an an error because the constructor requires a configuration array.

Considering letting Drupal do the work for you. Instead of calling things yourself, just let Drupal render it for you using a specific text format, which is configured to use entity embed.

See how check_markup() works, you could call that, but since you seem to be in a context where you want a render array anyway, just do what it does and use #type processed_text with #type and #format.

If that is for some reason not possible, then you need to mark the resulting object as a safe string by wrapping it with an object that implements MarkupInterface, for example with Markup::create() although that is marked as internal.


Exporting results with Views Data Export not working as intended I have a view-based search (drupal 7, newest version of Views) with several exposed filters. By default it shows all results and users have to use the filters to narrow down their search.

I've added 'Views Data Export' module to allow users to download search results via CSV export, if they wish. However it's not working as intended.

I created the export view and attached it to the search view fine. I made sure pager in the export view was set to 'display all items' (otherwise it only shows around 10 results).

I set batched export to yes. I also set each filter to 'remember last selection'.

However, no matter which filters are selected, the data export still shows every record in the database on export.

Anyone know how to fix this? Ideally the export would just show the records displayed on the screen after using the various filters.

A possible alternative to consider for the fix you are looking for, is to consider an alternative module that can possibly address all of your requirements, such as the Forena module. Here are a few features of it, which seem to be part of your requirements:

Support for exposed filters (via report "parameters").
Save reports (= query results) in CSV format (CSV is one of the supported document types).
Create export view (= Write a report, e.g using the WYSIWYG report writer).
Yes or no include a pager (using the dataTables plugin via report "skins", which also implements the search box feature that dataTables offers ...).

There are many more features that come with Forena, as detailed also in its Community documentation. Refer to the demo site for some sample reports (shipped with the module), or the documentation included with the module (such as the supported document types, of which CSV is just one of them).

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.


Custom template file for taxonomy term in drupal 7 I need to create only one tpl.php file for all taxonomy terms in my website. I know taxonomy_term_page.tpl.php will do the required function in Drupal6.

For drupal 7 I had override the taxonomy-term.tpl.php. I see all the nodes associated to a term, is displayed at the last.

How can I hide those nodes?

taxonomy-term.tpl.php is used in Drupal 7. You can find it in ROOT_DIRECTORY\modules\taxonomy\taxonomy-term.tpl.php.
To override this template, copy it, place it in your theme template directory, and modify it. Don't forget to clear the cache to see the output from the modified template.

Do not modify any core files (including template files), in any case.

If you want to show only the details of taxonomy term then you can create a view of type 'Term referance' with suitable filter.


Views HTML List displays empty random regions I created a View with a HTML list format showing Rendered entities.
The first row displays 3 items properly, the 2nd row displays only 1 item, rows 3&4 are good, row #5 displays only 1 item...

You may see it at: http://dtodonline.com.au/30nYj/product-index

Would you know how to not have those "empty slots"?
Thanks

Not able to access your URL. May be it is because of width of the item. Adjust the width of the items, it will display properly for you.


user_access( ) - Printing list 'variables' you can plug into? Something I have seen many times, but never fully understood is what exactly to plug into user_access() (Want to get the correct terminology here too, do you just call them variables?). I have seen some basic ones like user_access('manager access'), manager being a made user? Another using user_access('access nodes links'), which I assume is just seeing if they can see/access the tab links on a node.

If there an easy way to get a common list of what you can plug into user_access()?

Thanks in advance

You can see all the permissions on the /admin/people/permissions page.


Is there a way to access the full list of results in a Solr search page? I would like to manipulate the order of the results in an Apache Solr search result.

I'm using apachesolr together with apachesolr_panels.
In hook_apachesolr_process_results() I can get the $results for the current page, but I'm looking for a way to find the full list prior to pagination.

Edit: I'm asking about the result set as I'm not in control of the solr server and can't manipulate the XML file.

Yes and no. In any sane situation, it is the solr server that is handling the pagination. In essence, the server receives parameters, rows and start that tell it which "page" it will send.

You could write custom code that would get you all the rows but that would require at keast one more query to the solr server. The first query (the default one) would find out how many results there are in total; the second one would fetch the whole set, setting rows to the total amount and start to 0.


What is the purpose of modulename.api.php? What is the basic concept behind hooks? refers to modulename.api.php.

Does this apply to Drupal 8? What is this file? Is there an example of how to code it somewhere?

An .api.php file contains the hooks that a certain module supports, and is available for reference.

It offers documentation and example code on how to use the hooks in other modules. It is not specific to Drupal 8 as several modules in Drupal 7 offer it as well.

It does not actually implement or call the hooks and is for reference only.

As for an example of how to write it, it depends on the different hooks your module implements. Explain the different input and return parameters, adding additional data alterations as you see fit.

search.api.php is one of many examples in core. Hooks are either invoked, as for example, in common.inc:

$updaters = \Drupal::moduleHandler()->invokeAll('updater_info');

That is the the current way in procedural code. In object-oriented terms, with Dependency Injection, refer to this example in ModuleInstaller:

$this->moduleHandler->invokeAll('module_preinstall', array($module));

There are also alter hooks, like this one in BreadCrumbManager:

$this->moduleHandler->alter('system_breadcrumb', $breadcrumb, $route_match, $context);


The directory tmp does not exist and could not be created I keep getting this error since updating to Drupal 7.5.8 and cannot get rid of it regardless of trying all I know. Even adding it / copying-pasting the previous tmp dir or changing the tmp file name (eg tmp3) doesn't solve it.  Any files placed in the directory are writable unless I need to add a new Drupal 'group' in security.

Any one know how to solve this update issue?

You didn't mention the actual (complete) value for the path of the "Temporary directory" you want to use. But something that should work, pretty sure, is like so:

Navigate (in your web browser) to relative path admin/config/media/file-system.
Copy the value you have entered for "Public file system path", assume it's some/path/files.
Paste the copied value (like some/path/files) in the field "Temporary directory", and append to that value something like /temp, so that it becomes something like  some/path/files/temp/
Hit the Save configuration button and you should be good to go (Drupal will, automagically, take care of the rest).


drupal7 : db_select node with multiple values field I have a problem with db_select, i want to return a node per row for each value of the multiple values field :

node_1 : value_1_of_the_multiple_values_field
node_1 : value_2_of_the_multiple_values_field
node_1 : value_2_of_the_multiple_values_field
...

here is my code with the join it only return a node linked to the values of the field :

$query = db_select('node', 'n')
->extend('PagerDefault');

// Add join with multiple values field ( a date )

$query->join('field_data_field_date_programme_culturel', 'fdfdpc', 'fdfdpc.entity_id = n.nid');
$query->fields('n');

any idea please?

I've often struggled with the join methods in the D7 database layer. When I've needed to use a join, I've just used db_query() and passed it my SQL string. I know that when calling the join() method, you must already have the object initialised. So:

$query = db_select('node', 'n');
$query->join(field_data_field_date_programme_culturel', 'fdfdpc', 'fdfdpc.entity_id = n.nid');

and you already have it like this so I don't think that's the issue. I'd suggest using db_query($sql).


Template suggestion for 'content' in custom page I need the equivalent for hook_preprocess_node for custom pages, which aren't nodes.

The particular page I need to theme is provided by the entity registration module 'node/10/register'. I can add theme suggestions for the page using hook_preprocess_page - but how to I add a theme suggestion for the actual content, so I don't have to rewrite the page.tpl.php?

Alternatively if there is an existing pattern to name the file then that would be even better.

You need to copy the file

entity.tpl.php

from the theme directory of the module : entity.

Paste it into your theme's template directory, and rename it to

registration.tpl.php

Other theme suggestions are:

registration__TYPE
registration__TYPE__VIEWMODE
registration__ID

If you want to have access to the preprocess function then add this function to your theme's template.php file :

function MYTHEME_preprocess_entity(&$vars) {
  //dpm($vars);
}


How add custom AcessResult reason? When i look at

  AccessResult::forbidden()

We can set a reason as parametter.

So i try this :

 public function access(Request $request, AccountInterface $account)
    {

        $userRole=$account->getRoles();

        if(in_array("administrator", $userRole) || in_array("agence", $userRole))
        {
            return AccessResult::allowed();
        }

        return AccessResult::forbidden('TESTTT');
    }

If a user try to access my page who call this custom check access, he got :

So it's in french but it's the default forbidden access message.
I try to custom this message, and i was thinking about the reason in parameter.

Any idea why i can't get TESTTT as message ?

As per function definition:

   /**
    * Creates an AccessResultInterface object with isForbidden() === TRUE.
    *
    * @param string|null $reason
    *   (optional) The reason why access is forbidden. Intended for developers,
    *   hence not translatable.
    *
    * @return \Drupal\Core\Access\AccessResultForbidden
    *   isForbidden() will be TRUE.
    */
   public static function forbidden($reason = NULL) {
     assert('is_string($reason) || is_null($reason)');
     return new AccessResultForbidden($reason);
   }

So the $reason is only intended for developers.


is there any Function to extract all the view modes for specific node? Is there any function which can give you all the types of view modes available for specific node?
Also is there any direct(UI) way to check it ?

Is going to edit->manage_display the only way to get the view modes ?

The code below will give me the list of view modes

$entity_info = entity_get_info('node');
$list_of_view_nodes = array_keys($entity_info['view modes']);


How can I check if a node references a Drupal Commerce product? Is there a short function in Drupal Commerce API that returns TRUE (or something else) if a given node references a product?

There isn't a short function, though that's not a bad idea for a feature request. However, it's not that difficult using the Field Info API to determine if a given node contains a product reference field. One method would be using field_info_instances().

With this function and your node object, you can retrieve an array of all field instances on your node with the following code:

$instances = field_info_instances('node', $node->type);

You would then need to loop over the returned instances and use field_info_field($instance['field_name']) to load the field info array and see if the type of any given field is commerce_product_reference. If so, then you know the node can at least refer to a product... but that doesn't mean a reference is actually established.

For that you'd need to make sure the node contained data for that instance. That could be as simple as checking if (!empty($node->$instance_name)), but it'll depend on how you're actually building / using these reference fields.

One simpler way to find if a product reference instance is on the node is possible if you know your reference field's name. For that you can use field_read_instance() with the following code to return the info array of the instance or FALSE if it doesn't exist for the given node type:

$instance = field_read_instance('node', $field_name, $node->type);

Hope those help, and feel free to open an issue in the Commerce issue tracker for any related helper functions under the "Developer experience" component. I suggest you spend time getting to know the Field Info / CRUD APIs, as they'll be very helpful to you in your Drupal 7 development.


all my edit button cannot work and got "Invalid form POST data" AJAX error I don't know why all my edit button doesn't work since yesterday. In the log report, I got an AJAX HTTP error with 200 HTTP Code and "Invalid form POST data." message. And when I clicked any "edit" button, I received an Ajax error without any response Text:

Here are some buttons I found which don't work any more:

From Feed Import Setting (edit button doesn't work):

From Content type Adding (add existing product button doesn't work):

Does anyone have any idea why I got this???

An AJAX HTTP error occurred is very general error and it can be related to many things.

Based on your provided information we can say it's a core callback (/system/ajax) and the callback exists (Result code: 200).

The main problem is that it returns the empty response. This is most likely caused by WSOD (white screen of death) which can be related to:

out of memory issue (increase memory_limit in your php.ini),
timeout issue (increase max_execution_time in your php.ini),
code issue (make sure you don't have any exit() or die() which terminates your code),
cache issue (so please clear your cache, including memcached/redit if you're using it).

To debug this, you should:

Check your watchdog table for any errors (e.g. drush ws --tail --full).
Check your PHP error log for any PHP errors.
Use XDebug PHP extension, after configuring it enable xdebug.auto_trace parameter (only temporary), then reproduce the problem and check the trace file for more details.


launching parser script once in 24 hours I have a file parser.php

$url = 'http://site.kz';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch , CURLOPT_USERAGENT , "Mozilla/5.0 ");
curl_setopt ($ch , CURLOPT_RETURNTRANSFER , 1 );
$link = curl_exec($ch);
curl_close($ch);

so all contents of the site -site.kz is in $content variable. If i call this script http://site.kz/sites/all/themes/mytheme/parser.php -> it starts to grab this page, right?

How can i make available that variable $link in a page.tpl.php? If i make include ('parser.php') then everytime i F5 my page → parser is going to work (creates load to the server).

If you don't want your script to execute on each page load, you have to set up a cron job, either via hook_cron() or a separate job.

To make a variable available in a template file, you have to use a preprocess function of some sort.

With these two elements, you should be able to make your script work and be integrated with Drupal.


How do I organize content based on date field in a Y > m > d hierarchy? In essence, I want to organize content based on a date field; first by year, and once a user clicks a particular year, it goes to months, and so on... possible?

For instance,
-2017
-2016
-2015

I click on 2016 views generated date link, I should see the following on the next page.

December,
November, etc...

and finally, if I click on November, I will get to the actual listing of content for November.

Edit:
I have already tried grouping by year, and then months. But it is not creating the hierarchy I am expecting. Should I create a display that groups content by years first? and then months?

So for Drupal 7: Take look at this description:
http://chrisshattuck.com/blog/how-create-monthly-archive-block-drupal-blog-views

This is basically an explanation of the "Archive" view (disabled by default) shipped with views. Take a closer look at it and copy it to apply a few minor changes.

It gives you a monthly grouping of your content if there is no argument passed. That is actually the trick. Instead of the "created" date of your content just use the date field you have as argument.


How to allow a role to add users without giving them a password? I have a situation where I would like a specific user role be able to add users without assigning them a password but I can't seem to find a way to do this. Has anyone done this before? I feel like this is something commonly done. Any help would be appreciated.

Here is the module I have and currently, this code just outputs at the top of the screen for all pages? This is my first module.

Here is my hide_some_fields.module file

function hide_some_fields_form_alter(&$form, $form_state, $form_id)
{

  global $user;

  if($form_id == 'user_register_form')
  {
    if(in_array('operator', array_values($user->roles)))
    {
      unset($form['account']['pass']);

    }
  }
}

Here is my .info file as well:

name = Hide Some Fields
description = Hides some fields. The password field when the operator adds patients.
core = 7.x

People need a password in order to log in to the site.
Therefore you need to allways insert a password when creating new users.
You can add a default password and set the field as hidden on a specific role but new users will need to know the default password in order to log in.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if($form_id == 'user_register_form') {

    $default_value = isset($form_state['build_info']['args'][0]['pass'] ? $form_state['build_info']['args'][0]['pass'] : 'DEFAULT PASSWORD';

    if (in_array('YOUR ROLE', array_values($user->roles))) {
      $form['account']['pass']['#default_value'] = $default_value;
      $form['account']['pass']['#access'] = FALSE;
    }
  }
}

EDIT:

Ok I took the time to work this out and therefor I want to adjust my solution:
In order to get this properly working you need to override the full $form['account']['pass'] array. This is because it has the password_confirm type as default, which has the extra confirm field, keeping this type will result in an empty password field on the node submit.
Clive is absolutely right, using a #default_value on a password field results in an error so we need to use the #value. Thas was the unsupported operand types error.
Also, in my first answer I added a condition so see if the form is used to edit a user but now I know that the registration form and edit form are two different forms calling the same user_account_form so we can remove the condition.

function mymodule_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if($form_id == 'user_register_form') {
    if (in_array('USER ROLE', array_values($user->roles))) {
      $form['account']['pass'] = array(
        '#type' => 'password',
        '#size' => 25,
        '#access' => FALSE,
        '#value' => 'DEFAULT PASSWORD',
      );
    }
  }
}

I tested this code and it works like a charm so if you have any problems with it feel free to contact me.


Trying to remove options form an exposed filter In drupal 7, I'm trying to remove an exposed taxonomy filter. This taxonomy filter has a depth of 2. I'm only trying to expose the parent item.

As a quick fix I'm trying (poorly) to remove them with the following theme function below.

<?php
function theme_preprocess_views_exposed_form(&$vars, $hook) {

    //  views-exposed-form-instructor-profile-list-page
    switch($vars['form']['#id']) {

        // instructor profile
        case 'views-exposed-form-instructor-profile-list-page':
            foreach ($vars['form']['term_node_tid_depth']['#options'] as $option) {
                foreach ($option->option as $key=>$v) {
                        if (stristr($v, '-')) {
                            print $v . '<br>';
                            $vars['form']['term_node_tid_depth']['#options']['option'][$key] = 'FILTERED';
                        }
                }
            }

            print_r($vars['form']['term_node_tid_depth']['#options']['option']);
            break;

        // do nothing
        default:

    }
}

In the end I'm trying to figure out what exactly to unset() any option that begins with '- child item'.

Instead try the following it will help you by using hook_form_alter()

function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  if($form['#id'] == 'views-exposed-form-[your-view-here]') {

    foreach ($form['tid']['#options'] as $term_key => $term) {

      // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == '-') {
          unset($form['tid']['#options'][$term_key]);
        }
      }

    }

  }

}

taken from the source


How do I disable/enable a module on all sites within a multi-site Drupal installation using drush? As an admin of a multi-site Drupal installation, I want to make module changes to all sites within that platform.  On a regular basis, I want to disable/enable a set of modules to ensure consistency across all of the sites.

Using drush (any version 4.x, 5.x, or 6.x is acceptable), how can I perform this task without repeating the same command across each site?

Drush has the ability to interact with each site within a multi-site installation via the @sites argument.  Anytime you are within the directory structure of your platform, the drush @sites command will target all sites rather than a single/no site.  In this way, any drush task can be accomplished across all sites.

Some concrete examples:

Disable the dblog (core database logging) and devel module on each site

drush @sites dis dblog devel -y

Enable the speedy module on each site

drush @sites en speedy -y

Change the admin theme for all sites

drush @sites vset --yes admin_theme "ember"

Check to see if any sites in the platform have the cdn module enabled

drush @sites pml --no-core --type=module --status="enabled" -y | grep cdn

These (and many more commands) work with any version of drush >= 4.x


What do you do in a Views field theming function to change the output? [warning: Views newbieism ahead...]

I've got a View working with the FullCalendar module, which shows items from one of my content types in the calendar.  The title of the item appears in the calendar on the day specified by the "target date" field; all of this is working fine.  I now want to change the string that shows up in the calendar from the title of the item to something different, which I'll work out based on the item being shown in the view.

This is a matter of theming, I presume.  I've defined a template file called views-view-field--fullcalendar--field-target-date.tpl.php in my theme's template folder.  Some dsm() statements in this file confirm that it is getting picked up by the Views system, and its $row and $view variables have appropriate values.  But nothing that I do in this file changes what's presented in the view -- I thought print "something" would do it, but it doesn't; I've tried setting the passed-in $output and other values to something on the hope that they would magically find their way back to some code that would print them, but again without luck.

So I seem to be in the right place -- what do I have to do to change what gets displayed on the page?

I seem to have stumbled into something that works:

In the Views control panel for my Calendar view, I went down into Format > Settings > Customize Fields, and clicked the "Use a custom title" checkbox.  After I did this, the system started paying attention to views-view-field--fullcalendar--field-target-date.tpl.php, and used whatever I printed as the title of the events in the calendar.

So far, all is well, although I'm not sure whether this is an inherent part of the Views system per se, or if it has something to do with the module's use of the fullcalendar jQuery plugin.  Other solutions/answers/explanations are of course welcome.


Using argument in title I am using a contextual filter for a view in Drupal 8. The contextual filter is a Taxonomy Term: name filter with a term relationship. It works correctly.

I'm now trying to override the title using this filter. In previous versions of Drupal, using %1 would have given me the argument. But not in Drupal 8. Is there a way to either get the argument or (even better) the term name into the title override?

or (even better) the term name into the title override?

1) Add Taxonomy term: Name as a field

Check Exclude from display
Uncheck Link this field to its taxonomy term page

2) Click on Title: and put {{ name }}


Is it possible to migrate data into multiple translations of entities? I'm running a multilingual migration of events (which are stored as nodes) that have keywords on them where there are keywords (stored as terms). The keywords  should be stored in a multilingual tags vocabulary.

The source is a REST API, and what I have for the keyword data looks like this:

array (
 'id' => 'yso:p360',
 'alt_labels' =>
 array (
 ),
 'created_time' => '2014-06-23T11:37:29.198000Z',
 'last_modified_time' => '2014-06-23T11:37:29.198000Z',
 'aggregate' => false,
 'deprecated' => false,
 'n_events' => 11709,
 'data_source' => 'yso',
 'image' => NULL,
 'name' =>
 array (
   'fi' => 'kulttuuritapahtumat',
   'en' => 'cultural events',
   'sv' => 'kulturevenemang',
 ),
 '@id' => 'https://api.hel.fi/linkedevents/v1/keyword/yso:p360/',
 '@context' => 'http://schema.org',
 '@type' => 'Keyword',
)

Is there some way to use for example EntityGenerate to create all the translations of the tags when importing the original languages of the events that has these tags?

Note:

I would like to avoid migrating all the keywords first. We only import a subset of the events, and we are only interested in the keywords that are used by those events.

The normal way of D8 migrations with multilingual sources is to create a configuration for each translation. This doesn't work in our case, as I chose to use entity_generate for the tags. If you have another suggestion, I am interested.

I'm missing some informations for all understand your problem but, to migrate an object which have many translation you need:
Create the initial entity in the source language of your choose and add translation to this entity. For example, for a taxonomy term:

$default_language = "en";
$other_languages = ["fi", "sv"];

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => 'my_vocabulary',
  'name' => $my_importer_object['name'][$default_language],
]);

$term->save();

foreach($other_languages as $language) {
  $term_object = [
    'vid' => 'my_vocabulary',
    'name' => $my_importer_object['name'][$language],
  ];
  $term->addTranslation($language, $term_object);

  $term->save();
}

Like it's a taxonomy term, it will be reference in your object like a entity references, with its tid. The link between translated version of the term and translated version of the node will be the language. If the term exist in the language of the node, Drupal 8 will used it automatically. If the term isn't translated in the language, Drupal will use the original language of the term, in which it had been initially created.


How do I get a field label in different languages? In a module (not a template), I need the label of a specific field in multiple languages.

$entity->getFieldDefinition('myField')->label() gives me the label in current/active language (let's say, English).

What doesn't work as expected is the following:

$entity->getTranslation('fr')->getFieldDefinition('myField')->label()

I would expect the label in French. Instead, I get the label English. How to get the French label?

You can load an entity's translation by using the entity repository service. The field configuration is an entity itself. So you could try this:

use Drupal\field\Entity\FieldConfig;

// Override language before loading field configuration.
$language = \Drupal::languageManager()->getLanguage('fr');
\Drupal::languageManager()->setConfigOverrideLanguage($language);

// $entity_type, $bundle, $field.
$field_info = FieldConfig::loadByName('entity_type', 'bundle', 'myField');

$label = $field_info->getLabel();

EDIT:

As stated by 4k4 within the comments, config entities don't behave like content entities. So in order to get their translations, you will need to override the language before getting their translatable strings. Adjusted the example accordingly.


Understanding database structure for auto-migration I am trying to come up with a good way to get this handed down Drupal project to work as smooth as possible. Ideally, my goal is to do changes local, and when that looks okay, I should be able to git push this to the server. Earlier I've made myself able to push structure changes through git hooks/post-receive, CodeIgniter Migrate and some bash scripts. This was worked out really neat, and I'm interested in similiar solutions for my Drupal project.

Ideally, I would like to upon git push have my php script generate a .sql file, send it to the server and let the server execute it so that it replaces live tables as ideal. Since our main page will handle products, orders and such that can't be overwritten, I can't simply just clone the database.

The thing I'm mostly puzzled out is, how do I tell what tables do what in my Drupal database? I have around 300 tables, and am not fully sure how dependent the tables are of each other, which that handles structure changes such as enabling and disabling modules and so on. Does anyone share an insight regarding this?

Maybe there's some easy solution for what I'm after that I've missed?

You can skip migrating the following tables:

accesslog
cache_*
sessions
watchdog

All the above contains material that you generally don't want to migate across sites.

The contents of the tables for built-in search will be regeneated by cron if you don't migrate them, but it may take up a lot of resouces if you've a lot content. But if this is not a concern, you can also skip migrating:

search_*

As for table names, Drupal relies heavily on namespace dicipline to avoid collisions.  So a module named foobar should only create tables with a name that starts with foobar_ (or just foobar if it only creates a single table).  In other words, you can tell what tables in the database that "belongs" to what module by their name.  This goes for both core modules and for regular contributed modules.  As for custom modules (i.e. modules that is managed outside the Drupal.org framework, you may find exceptions to this naming convention - but only if they're written by bozos :-).

If you look at your database, you may discover a lot of tables with names starting with field_.  These are of course from the (core) Field module, but I mention these specifically because these are the tables used for custom content types that are created using "Fields in core" (a key Drupal feature).

As for interdependencies between tables, looking at the fields in the tables that belong to the same module is usually enough.  Getting familiar with the Schema API is also helpful.  But to be honest: Sometimes you need to sit down and read source code.

As for creating and dropping tables, well behaved modules create datebase tables using hook_schema (found inside the module's .install-file) upon installation, and automatically drop the same tables upon un-installation.

Note that just pushing a module with git doesn't install the module.  It just makes it available for installation.  To install it, you either do it manually (using the administrator's GUI), or script it using Drush.

It is also useful to know that there are clear rules in the Drupal community of practice that a module should only write to its own tables.  If a client module want to write to another module's table, it must do so through the module's API, not by interacting with the database.  Module interdependency is tracked in the module's .info-file.  This means, for instance, that you'll not be able to disable a service module a client module relies on (provided their interdependency has been correctly declared).


Get list of custom fields and update their settings programatically I'm using D8's core contact form, I have added some custom fields and I want to change one of custom fields' settings config programatically.

I have tried this

\Drupal::service('entity_field.manager')->getFieldDefinitions('contact_form')

but I get error:

LogicException: Getting the base fields is not supported for entity type Contact form. in Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions() (line 204 of core/lib/Drupal/Core/Entity/EntityFieldManager.php).

Is there any way to get list of fields and update their configs and settings?

Try this one:

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('contact_message', 'personal');

You can change personal to your contact form bundle.


Get info from entity reference using PHP I'm trying to use PHP to get user IDs from an Entity Reference of users in a content type.

I have got as far as doing (where I actually get the NID from elsewhere):

$node = node_load(123);

$info = field_get_items('node', $node, 'field_my_users');

But how do I get the IDs from $info?

You just need to get the target_id from each of the field values, which you can do by looping through $info:

$uids = array();
foreach ($info as $field_item) {
  // Entity reference fields store their data in the 'target_id' column
  $uids[] = $field_item['target_id'];
}


Total count of two different content types in one View? Use case: How many Demonstrations and Deliverables are from each State?

I'm using a View with Aggregate but don't see a way add multiple content type counts.

Refer to screen capture of the page and view settings please.

The table in the screen capture is similar to this one:

The Views Calc module can be used to transform that table so that the calculations in the last rows (with Count, Sum and Max) get added to it.

By replacing the columns like '# Fish' and 'Weight' with 'Total Demonstrations' and 'Total deliverable ...' (as in the question), and by asking for only the 'sum' to be added, it should answer the question.

To ask for the 'sum', just select it from the selection list, similar to what is shown in this screenshot:

For more details (step-by-step instructions), refer to the community documentation about the Views Calc module.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


cache_token table doesn't exist after Drupal 6 to Drupal 7 upgrade I recently created a D6 site to import some content using the D6-only import_html module, then upgraded it to D7 (in a slightly roundabout way I can describe, but shouldn't be relevant to the question). Since doing so, whenever I enable new modules and am sent to /admin/modules/list/confirm I see Drupal error messages like the following:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal7_gimported.cache_token' doesn't exist: TRUNCATE {cache_token} ; Array ( ) in cache_clear_all() (line 169 of /Users/tomash/Sites/drupal7/includes/cache.inc).

The modules do seem to install correctly, but the error is annoying and alarming. I would just copy a cache_imported table from a clean Drupal 7 install, but I wanted to check whether this is the right approach in general, and whether the error points to deeper problems.
Relevant information, which I can add to

I had the Token module installed in the Drupal 6 installation
I've enabled the Drupal 7 version in the upgraded Drupal 7 installation
I'm running this all on my localhost, which has rarely yielded errors before

After enabling back your module have you run update.php to ensure all needed queries are executed ?
It seems its the first update the token module runs.

/**
 * Add the cache_token table.
 */
function token_update_7000() {
  $schema['cache_token'] = drupal_get_schema_unprocessed('system', 'cache');
  $schema['cache_token']['description'] = 'Cache table for token information.';
  db_create_table('cache_token', $schema['cache_token']);
}


Running functional tests on a non-English site When creating functional tests (extending BrowserTestBase) for a D8 site, how would I go about changing the default language of the site being temporarily created by BrowserTestBase?

I'm trying to run tests on a site in a non-English language, and I'd like to avoid confusion by using English terms etc. in test cases.

As far as I see, Drupal/Core/Test/FunctionalTestSetupTrait.php sets the default langcode to be 'en' (in the installParameters method) and there's no option to specify custom installation parameters. Besides hacking this manually, is there a more elegant, "proper" way of changing this behavior?

If that's not possible, then would it be possible to change the site's language after it's created, maybe in the setUp method of the test class?

I think there are a few ways. The simplest might be to override the installParameters() method to specify your desired language:

protected function installParameters() {
  // This will come back with the langcode set to `en`.
  $parameters = parent::installParameters();

  // Update to desired langcode:
  $parameters['parameters']['langcode'] = 'es';

  return $parameters;
}

I didn't find any tests in core that did it this way, but there are a few that change it during setup via the UI. (This example from LanguagePathMonolingualTest)

// Make French the default language.
$edit = [
  'site_default_language' => 'fr',
];
$this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));


How to export a module's configuration? I've set up a module on one site and want to export it to another site. From researching, I understand you can use Features to do this. However there is no documentation detailing this.

Any suggestions about how to do this?

Many

Drupalise Me Feature introduction

Phase 2 feature slides.

Code Karate Feature Series Video

Acquia Video Series

As far my experience features is not just about how to do it, but also how well you do it. Doing it in wrong way can make the development nightmare. Once you get acquinted with features, I would recommend you to look for features best practices. Do's and Don'ts for feature module.


Create Drupal 7 page specific tpl files without using node ID's i know you can crate custom tpl files for a specific page by doing the following:

html--node-999.tpl.php

But this doesnt work well if the node-id is going to change when switching environments or migrating stuff. What is the file naming convention for drupal 7 tpl's that are URL Path specific?

Happened upon this old question that didn't have a completely legit answer.

In short, you can set up templates based on path by using the formulae...

page--[front|internal/path].tpl.php

Put simply, if you want a specific page template for a custom page with a url of support, you would create a template named

page--support.tpl.php

or support/contact would be

page--support--contact.tpl.php

Of course you can and probably should use the node--[type|nodeid].tpl.php pattern if you are dealing with node pages.  But creating a template based on path is definitely possible.


How to create two nodes at a time? I have one cck content type and two fields in this content type 1. is First name 2. is Last name i am trying TODO when i fill this these fields and click on save button Automatically create Forum topic with the name of first name text box value.
 how it is possible ? plz help
i am using Drupal 6

You can do it easy with the Rules module.


How to apply patches on Pantheon? This is specifically a question about Pantheon best-practice workflow, which I'm new to.

I run from a Win7 machine and do not have a full dev environment set up locally: it's just too much hassle to get Windows to play usefully and smoothly as a dev space behind my hosted *nix worlds. So, I am in the habit of developing online.

With Pantheon there is no shell access, but there is git and drush.

I don't use git because the workflow there asssumes that I want to move something off of my local repository up to Pantheon (eg, if I have a local working environment I would apply the patch, then push the patched code to my Pantheon dev), but this is not my usecase.

Using drush seems like an option, but I can't figure out how/if applying a patch is supported.

So...

How to patch a contrib module on Pantheon given no local dev environment?

I'm not sure what you mean by moving something off of your local, but I really think your best bet is to use git and push the patch up, even if you don't have a local environment set up. You don't need a local server or database running, you're just altering code in the repo.

clone Pantheon dev environment locally
patch -p1 < name_of.patch
commit and push

You could edit the files manually using the SFTP mode, but I wouldn't recommend that.

Using Git with Pantheon


File upload disappears in Web File Manager I am trying to upload files to our Web File Manager (in Drupal 6.31), and while everything seems to work fine the file does not appear in the directory list afterward. It does not exist on the server either.

I checked the permissions on the default WebFM folder, and it is 775. I am logged in as the first (super admin) user. I am not receiving any error messages. There are no available updates for Drupal Core or WebFM.

What could be going wrong?

Thanks in advance!

This is a critical bug of Web File Manager module that sates "files are being deleted while browsing WebFM with Chrome" (Considering that you have been using chrome to upload files your Web File Maanger)
For more reference please refer to this.


field_info_field() deprecated, what's the equivalent? In Drupal 8 field_info_field() has been deprecated. The docs say to use this instead:

Field::fieldInfo()->getField($field_name)

I've tried various iterations of it, such as:

$foo = \Drupal\field\Field::fieldInfo()->getField('field_address');
$foo = \Field::fieldInfo()->getField('field_address');

But I keep getting an error similar to the following:

Fatal error: Class 'Drupal\field\Field' not found in /var/www/drupal/modules/custom/foo/src/Controller/FooController.php on line ##

What am I missing?

UPDATE

Thanks to Clive's answer, and especially for pointing me towards change records (which I've now subscribed to via RSS), I was able to generate various commands to get data about entity types, bundles and field "info/instances" in Drupal 8.

The data that was once available via field_info_fields() and field_info_instances(), is now available throughout the EntityManager, FieldConfig, and FieldStorageConfig:

$entity_type = 'node';
$bundle = 'course';
$field_name = 'field_address';
$foo = \Drupal::entityManager()->getFieldMap();
$foo = \Drupal::entityManager()->getAllBundleInfo();
$foo = \Drupal::entityManager()->getBundleInfo($entity_type);
$foo = \Drupal\field\Entity\FieldConfig::loadByName($entity_type, $bundle, $field_name);
$foo = \Drupal::entityManager()->getFieldDefinitions($entity_type, $bundle);
$foo = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
$foo = \Drupal::entityManager()->getStorage('field_storage_config')->loadMultiple();
// This one doesn't seem to work for me, see my comment to Clive for a workaround.
$foo = \Drupal\field\Entity\FieldStorageConfig::loadByName($entity_type, $field_name);

Here are some other calls that may be useful:

$foo = \Drupal::entityManager()->getAllViewModes();
$foo = \Drupal::entityManager()->getViewModes($entity_type);
$foo = \Drupal::entityManager()->getAllFormModes();

According to the change record:

field_info_field($entity_type, $field_name) -> FieldStorageConfig::loadByName($entity_type, $field_name)

So you should use \Drupal\field\Entity\FieldStorageConfig::loadByName from now on.

It's probably best to use change records and issues on Drupal.org itself for docs at the moment, rather than 3rd party websites - I think they have slightly more chance of being right and kept up to date when something changes.


How to hide the link for creating certain content type? I am trying to make a reservation system for equipment in a laboratory. People reserve equipment by creating "reservation" nodes. Some fields in the reservation node already have values, determined by the way the (registered) users reached the "form", and the values can´t be changed by them.
I don´t want the registered users to have access to create the reservation node through the "Add content -> Create Reservation node" way.
How to "hide" that option in the add content menu? (as they do have permission to create the reservation node)

In drupal 8, you can remove certain links from the /node/add page hook_preprocess_node_add_list():

function mymodule_preprocess_node_add_list(&$vars) {

  // Remove a few content types from /node/add page.
  $types_to_remove = [
    'dog',
    'cat',
    'fox',
    'rabbit',
  ];
  foreach ($types_to_remove as $type) {
    unset($vars['content'][$type]);
    unset($vars['types'][$type]);
  }
}

If you are using the admin_toolbar for drop-downs, you can remove links using hook_menu_links_discovered_alter().

function mymodule_menu_links_discovered_alter(&$links) {

  // Remove a few "node add" pages from admin menu.
  $types_to_remove = [
    'dog',
    'cat',
    'fox',
    'rabbit',
  ];
  foreach ($types_to_remove as $type) {
    unset($links['node.add.' . $type]);
  }
}


How to setup a Facebook page block for each user? Is it possible to setup Facebook block for each user? When a user registers or later in specific node he can copy/paste a link in text field that will result in his Facebook page block.

I know how to setup views contextual to show block for each user based on user's id or nid, so that part is covered.

I'm presuming you want to do something like a Facebook Likebox embedded iframe (e.g. https://www.facebook.com/plugins/likebox.php?my_user_facebook_page_details...) with the user supplying his own URL in his user account profile.

If that's the case set up your block view to render your user's URL field with a custom template. Under the Views UI in Advanced > Other > Theme, the Information link will give you a list of template names (e.g. views-view-field--field-my_user_field.tpl.php) that you can put in your theme's template directory and some boilerplate code (found via the link next to the template names). You can alter the template such that the $output is wrapped in a iframe src attribute.

Flushing the cache should rebuild everything so that your block's URL field now renders as an iframe on the user page (if you've configured your contextual filter correctly). It probably should be noted that rendering a user-supplied iframe URL is dangerous so you probably should be filtering out non-Facebook URLs.


Calling two namespaces for formbuilder and controller in d8 I have a d8 form as follows ,and am calling a new class by including the file in the formbuilder class , But its throwing me a class not found error ,although am including the class in the form builder and namespace in the calling class .

    namespace Drupal\module_name\Form;

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

    //included class
    require_once './' . drupal_get_path('module', 'gasf') . '/includes/config_class.inc';

    class ClassName extends ConfigFormBase {

      public function getFormId() {
        return 'class_name';
      }
    /**
     * General form for switching all nodes from one user to another.
     */
      public function buildForm(array $form, FormStateInterface $form_state) {
      $Config = new ConfigClass();
      $operations = array(
          'IP -> vm name',
          'vm name -> IP',
      );

    $argument = empty($argument) ? '' : $argument;
    $operations = empty($operations) ? '' : $operations;

    $form['argument'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter argument here'),
        '#default_value' => $argument,
        '#description' => t('Depending on operation: tcp/ip adress or vm name'),
    );

    $form['operation'] = array(
        '#type' => 'select',
        '#title' => t('Operation:'),
        '#options' => $operations,
        '#description' => t(''),
    );

    $form['submit_lookup'] = array(
        '#type' => 'submit',
        '#value' => t('Lookup'),
    );

    return $form;
}

and in the config_class.inc i have

namespace Drupal\module_name\Controller;
namespace Drupal\module_name\Form;

class ConfigClass {

}

But its calling the latest namespace only , that is when i use namespace Drupal\module_name\Form; its working properly , But it wont take effect the namespace Drupal\module_name\Controller; namespace  .That will through error on calling the class from controller ! . How can i use the namespaces for both formbuilder and controller class ? Or is there any other workarounds ?

A class can only be in one namespace. There's never a scenario when a class being in two namespaces could be useful, and the language doesn't allow it.

I have no idea what you're trying to achieve, there's no mention of that in your question, so again I'll just reiterate (3rd time now!) that you should learn what namespaces are, what autoloading is, what PSR4 is, and how to use them. Otherwise you're just going to spend your time banging your head against these trivial PHP language issues, and get very little done.


Calculating duration between two dates I am using Views Calc for Drupal 7 to calculate duration. I have some questions:

If use Date (Unix timestamp) and subtract end date from start date of my date field with time it gives me seconds then I divide it with 86400 (the seconds in a day) it gives me number of days.

My code in Views Calc:

( %field_data_field_we_from_date.field_we_from_date_value2 -
  %field_data_field_we_from_date.field_we_from_date_value ) / 86400

which is great;

however:

If I use date (not UNIX time stamp) and with no time only year, month, and day then it gives me a number which I don't understand what it represents. If I divide it with 86400, the answer does not look correct. My problem is that we don't need to add time in the field. The end-user doesn't like to see time field with date.
When I try to use NOW() it give error in Views Calc setting which says NOW value is not allowed here! I need NOW() - my_date_field to get age and other duration which do not have end date field.
ROUND() function also doesn't seem to be working.

Any help would be highly appreciated.

You can do a little tweak.

After you get the only date in YYYY-MM-DD string format, concate 00:00:00 as time to the string. then you can get unix time format by using function strtotime() that takes a string date format and returns an integer of time format (unix).

Hopefully this helps you getting the correct duration.


Why are my if/else statements in page.html.twig ignored? in my theme template of page.html.twig (theme is a subtheme of classy core theme), my if statements to render a region or not are completely ignored by twig template engine. The regions (e.g. the first sidebar are always rendered.

Code of my page.html.twig:

    {{ page.header }}

  {{ page.primary_menu }}
  {{ page.secondary_menu }}

      {% if page.navigation %}

        {{ page.navigation }}

    {% endif %}

  {{ page.breadcrumb }}

  {% if page.system_messages_area %}

    {{ page.system_messages_area }}

  {% endif %}

  {{ page.highlighted }}

  {{ page.help }}

      {# link is in html.html.twig #}

        {{ page.content }}

{# /.layout-content #}

      {% if page.sidebar_first %}

          {{ page.sidebar_first }}

      {% endif %}

      {% if page.sidebar_second %}

          {{ page.sidebar_second }}

      {% endif %}

  {% if page.footer %}

      {{ page.footer }}

  {% endif %}

Code of my theme.info.yml:

name: mytheme
type: theme
description: Based on classy core base theme.
core: 8.x
# Defines the base theme
base theme: classy
# Defines libraries group in which we can add css/js.
logo: logo.png
libraries:
  - mytheme/global-styling
# Regions
regions:
  header: Header
  navigation: Navigation and Menus
  system_messages_area: Area for system messages
  highlighted: Featured
  help: Help
  content: Content
  sidebar_first: First sidebar
  sidebar_second: Second sidebar
  footer: Footer

Maybe someone could help me to find the mistake, as far as I can see everything is at it's right place.

Thanks in advance

Best regards phil

I would check, if the page render-array contains the element sidebar_first. You can do this with

{{ dump( page|keys) }}

in your page.html.twig (or use devels kint function for that). The |keys filter will prevent you from memory overflow if your page is big.

If this is the case, then your template is ok and you don't have to look at twig, but to search, what else is in the render array and where it could be originated.


How to create a custom home page template? I've built a few drupal sites, and always end up creating a content type for Home Page so that I can have a custom template for my home page content, however it seems excessive to have a whole content type just for this. Is there a better way to have a custom home page template?

Wordpress has the front-page template, is there something like that for Drupal?

Yes : https://www.drupal.org/node/317461

  In Drupal 7, copy the page.tpl.php file and name it page--front.tpl.php.

Copy the file in your sites/all/themes/yourtheme/templates file (and then clear the caches of your site)


Drupal - block deleted - how to retrieve I just posted this to StackOverflow, but then I noticed this group, so apologies if this is a duplicated question.

We're running version 6.14 of Drupal (old, I know). On of our users recently deleted a block by accident in a series of rotating images. (Administer > site building > block). So now the block shows up as a blank, or "n/a".

She did manage to add another block in its place, but apparently that doesn't help - the n/a still displays. What is the solution to this problem?

The problem was that the new block the user created had a block number of "8", whereas the original block that was deleted had a number of "2". The fix was to go into custom themes for the homepage, edit page.tpl.php, and change the "module_invoke" to refer to the correct block


Add and/or option to Drupal Views' Contextual Filters? How can I add the "and/or" option to Drupal Views' Contextual Filters panel? I added it to Filter Criteria, but I can't seem to get it for Contextual Filters.

You can achieve your requirement by installing Views Contextual Filters OR module. By default contextual filters are in AND condition.

  The module provides a views plugin which modify query to support OR
  conditions for contextual filters.


Body Summary field showing literal ampersand character code in view I have a Drupal 8 site where we've created a view, and decided to use the summary field instead of the trimmed body field, so that we could have more control over it.

However, I got a bug report that the page had funny characters. When I looked, I found that a literal ampersand character, &, was changed to the HTML code &amp;.

Thinking this was some weirdness introduced by our settings and configuration, I built a view on a clean install of Drupal 8.7.3 and generated some nodes with devel_generate. Sure enough, the ampersand HTML code appeared.

Node:

View Page preview:

View Page:

So, I want to get this to display a regular ampersand, as the user entered it.

I found this question explaining how to modify a twig template to use the raw value, but I'm not sure that's what I want to use. I don't want raw values for the whole field-- users could enter HTML in the summary field; I just want a non-encoded ampersand.

How do I get unencoded ampersands in the summary field in a view?

Edit leymannx recommended to uncheck Display any HTML as plain text on the text formats filter. However, both on my test fresh install and my real site, that filter is not checked, for any format.

I did my fresh install from downloading the Drupal core, and I think leymannx  user composer, so I am going to try that, to see if I get the same behavior as he does.  Also, I'm not going to install the devel modules to generate content, I'm just going to do one by hand.

These are screenshots from my fresh install:

Also a screenshot from my actual environment:

So, from those settings, it doesn't seem like the filter is what's causing this behavior.

Edit 2 I found something that I now suspect as perhaps the source of the error. The view on the fresh install is a view of files. I did not find the summary field in the list of fields, so I added a body field and re-wrote it with {{ body__summary }}. This is the config export yaml of the view I created.

This is to confirm and clarify the issue according to my findings.
1. I was able to reproduce your findings by using a fresh Drupa 8.7.3 install and after importing your view in which you used the {{ body__summary }} rewrite.

2. I was able to reproduce the error by enabling Display any HTML as plain text option in Basic HTML text format.
3. I was also able to reproduce the error by rewriting the view field output and choosing {{ body__value }} which basically prints the raw value of the body field.

My opinion is that 2 & 3 are normal behavior and it should be expected that in these particular cases the raw HTML is displayed. However, in 1, it seems a bug because the summary shouldn't be displayed as raw HTML; it should follows the same rules as the selected format.
I suggest to open an issue in Drupal issue tracker telling them about 1; maybe there is a reason behind this behavior, or if somebody already knows the answer, please elaborate.

Regards


Choosing between template files and custom module I wanted to add some custom functionality in my Drupal website, so I read some  tutorials (first, second ) and  decided to create custom template files for specific forms & exposed filters I wanted to change. And it worked perfectly!

But when I had to pass the changes to the original site I had to change the code a bit, so I tried with a custom module this time (not using template files) and it also worked like a charm!

I'm confused because both templating and custom modules can be used for providing the same functionality. But which is better - in terms of stability, performance, code reuse etc. ?

That depends on what you would like to accomplish.
When it is just pure templating (markup, styling, theming) you can do this with template files just fine.

But when you want to include custom logic (programming), it is better to create a custom module where you put the hook() implementations and/or preprocess functions etc...and then define a temaplate file there.

Does this offer some clarification for you?


Views 3 Template or UI question I have a text field that contains multiple values. That field does not always contain any values. The field needs to have a label when displayed.

IOW, the row should look like one rows below

CoAuthor: Person X, Person Y

or

CoAuthor: Person X

Here is my issue: When I use the view UI to add the label I get

CoAuthor: Person X, CoAuthor: Person Y

When I use the template,

print $fields['field_coauthor']->content;

I can not hide the field when empty so I end up with

CoAuthor: (and no value)

Is there a way to add a conditional to the template so that I do not end up with a label and no data? Or configure the view to include the label once... and not add it for every entry?

I am actually a bit puzzled by your View result, because the default settings for fields should give you:

CoAuthor: Person X, Person Y

when there is more than one author (and this I presume, is what you want?)
And since Views also have a setting: "Hide if empty" under *No results behavior", it should be trivial to get this right using fields.
Anyway, this is how I've set this up using Views:
First, I click on Format - Show: Content and switch that to Fields.
Second, I tick Provide default field wrapper elements and Hide empty fields.
Third, under Fields I click Add and add the "CoAuthor" field. I tick Create a label, and Place a colon after the label. Under Multiple field settings, I tick Display all values in the same line.  I also tick Simple separator and make sure it is ,  (comma followed by space, which is the default).Then under No results behavior, I leave No results text blank, and tick Hide if empty and Hide rewriting if empty.
Fourth, I navigate to Format - Show: Settings and tick to make sure CoAuthor is an inline field.
After doing all this, the output should be nothing if there are no CoAuthor, and for the other two cases:

CoAuthor: Person X
CoAuthor: Person X, Person Y

As for using a template, you should be able to wrap the PHP generating the output in a test that checks for a non-empty field, e.g.:
if (!empty(print $fields['field_coauthor']->content)) {

I not sure where the template fragment you post come from, so I haven't posted the full code, but I hope you get the idea.


Verify that salt.txt was located and being used by Drupal? In my settings file in Drupal 8, I am specifying a location for hash-salt to a file outside of the docroot.

Example:

$settings['hash_salt'] = file_get_contents('/salt.txt');

I don't see anything in the status report or way to verify that Drupal was able to locate this file on the webserver and it is using it. I tried setting it to a broken path and/or file that doesn't exist, I even removed the line. However I don't see any noticeable change, so, how can you tell that this setting is being respected?

You can check this with drush by using Settings::get('hash_salt'):

drush ev "var_dump(\Drupal\Core\Site\Settings::get('hash_salt'))"


Use a field's values in database to populate an exposed filter's options I have a content type with a field named year (integer).

In a view, I'd like to expose this field to the user as a filter.

Instead of the default text boxes, I want to populate select lists with the values in the database for that field. Then the user will just have to click to select.

My php code writing is on copy-paste level.

I am using D7.

This topic migth be useful for you.

You can also create taxonomy vocabulary years and than select filter will be able to use in views.


Is it possible to force redirection from PayPal to the website after successful payment? I'm using PayPal WPS with Ubertcart, and want to track the conversions using Adwords.

Is there any way to force true redirection back to the website within Ubercart?
The redirection in PayPal settings is already set to "On", however the users are still being asked to click to go back, or proceed to their PayPal settings page.

This results in losing the conversions.

Any ideas how to force the clients back directly to the website via Ubercart / custom module?

Thanks!

The answer is unfortunately no.

PayPal will always display this as an option to the client, so you can't force the redirection back after the payment has been completed.


How to get the parent comments (in a custom module)? I'm writing a module that uses flag to handle notifications, and one of the options is to be notified of replies to a given comment.

I can implement without problem hook_comment_publish($comment), but I want to get all of its parent comments so that I can pick up the users that flagged them.

So, how can I retrieve all the parent comments of a given comment (if any)? I noticed that in taxonomy there is a taxonomy_get_parents($tid) but I can't find anything similar for threatened comments.

This code does the trick:

  $threads = explode('.', $comment->thread);
  $thread = "";
  $pnids = array();
  for($i=0;$i<(count($threads)-1);$i++){
        $thread .= $threads[$i];
        $local_thread = $thread."/";
        $result = db_query('SELECT c.cid FROM {comment} c WHERE c.nid = :nid AND c.thread = :thread AND c.status = :status',
        array(':nid' => $comment->nid, ':thread' => $local_thread, ':status'=>'1'));
        foreach ($result as $record) {
            $pnids[] = $record->cid;
        }
        $thread .= ".";
  }

However this code produces 1 DB query for each parent. I don't know if it is feasible/better to include all the :thread in a single query with OR.


Why are the commands implemented by a custom module still listed after uninstalling it? I registered a new command via Drupal Console using drupal generate:command. I associated the command with a custom module, but after uninstalling the module and removing the module folder, the command still appears when issuing a drupal list command. I couldn't find anything in the Drupal Console documentation relating to this.

How do I let Drupal Console know my module is being uninstalled, so that it doesn't list its commands anymore? Does the module needs to implement a specific method for that, or do I need to run a Drupal Console command for this?

Problem solved. Issuing drupal module:uninstall my_module removes the command from the Drupal Console command list.


Locked myself out after enabling misconfigured Google Authenticator I somehow managed to lock myself out of a Drupal 9 installation after setting up TFA with Google Authenticator login. So, i know my user1 name, my user 1 password, but TFA doesn't allow me backend access, because the app is misconfigured. I still have FTP, DB and SSH access.
I already did this two years ago on another site. That time I added a line to settings.php that granted admin role to anonymous user. But I cannot find this solution anymore.
Any help would make my day!

I post this as an answer, because someone might be as stupid as I am :)
I browsed various old backups and found the settings.php line that grants admin permissions to anonymous user, and it worked.
If you add:
$config['user.role.anonymous']['is_admin'] = 'true';

in your settings.php, every anonymous user is admin. That way I could get back into admin panel and uninstall TFA and Google Authenticator. Deleted the line, logged back in as user1 and installed both modules again.
Handy way to do it, if you don't have drush. But not recommended for production sites obviously.


Attempt URL alias for spanish version of page - "The path */* is either invalid or you do not have access to it." Drupal 7.59. We have the page whatever.tld/thanks and whatever.tld/es/thanks.
I'm trying to setup whatver.tlp/gracias as a URL alias for es/thanks and it says "The path 'es/thanks' is either invalid or you do not have access to it."

The page itself is a tpl.php file referred to by a view and has individual blocks on it that are translated.

This translation stuff is beyond me. I have a dev site to practice on so I'm happy to try out any ideas. The following (apparently) applicable modules are enabled:

GTranslate
Block languages
Internationalization
Menu translation
Multilingual content
String translation
Translation sets

As @prkos mentioned enable the languages module. In the Configuration/Regional and language/Languages settings you select the code you wish to use for your languages. The choice is obviously yours but when I have a multilingual site I prefer to use the ISO language code to help define the languages on the site.


Getting the $user object of a logged out user based on a username and setting its status As mentioned in the question here Using user_load() and user_save() to change the status of a logged out user, I want to be able to access the $user object of a logged out user based on a username and set the user status to active with user_save().

As advised, I put my code in a custom module and implemented hook_menu() with a page callback. However, I still don't fetch $user.

UPDATE: I've managed to get what I wanted: I'm indeed fetching the $user object by a username passed as a parameter and I manage to change the user's status. BUT, i'm not doing this the proper way. Here's the code inside mymodule.module:

<?php
function mymodule_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    // set user's status to blocked upon registration
    case 'insert' : {
      user_save($account, array('status' => 0));
      break;
    }
  }
}

function mymodule_init() {
  // needed due to Drupal's menu caching. Otherwise, mymodule_menu() won't be called
  menu_rebuild();
}

function mymodule_menu() {
  $account = user_load(array( 'name' => $_REQUEST['user'] ));
  user_save($account, array('status' => 1));
}

As you can see, I implement hook_menu() but there's no page callback. A working page callback would solve me 2 issues:

I would like the user activation functionality to be available only from a specific page in Drupal and i'd like to restrict access to that page.
Performance - currently, the menu_rebuild() is called on each and every page request on Drupal.. not pleasant at all :)

When I tried putting a page callback in the mymodule_menu() function and debugged the code, I saw that the page callback wasn't even fired. Here's what my initial code looked like:

function mymodule_menu() {
  $account = user_load(array( 'name' => $_REQUEST['user'] ));
  $items['auth'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array($account),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page(&$account) {
  menu_rebuild();
  user_save($account, array('status' => 1));
}

Why isn't my page callback function fired with this code? How can I tell Drupal to rebuild the menus or to clear the menus cache only for a certain page?

Avner

What is wrong in your code is that the implementation of hook_menu() is gathering the arguments for the callback, when that hook is only called in specific moments (as I reported in my previous answer).

Rather than doing as you do, I would rather use the following code:

function mymodule_menu() {
  $items['auth/%user'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page($account) {
  user_save($account, array('status' => 1));
  drupal_goto('<front>');
}

In this way, Drupal will automatically get the user ID, and pass to the page callback the user object for that user. drupal_goto() is necessary as the page callback is not showing any output; you can redirect the user to any pages you want. (I chose "<front>" because it's a path that is always defined, in Drupal).
If you need to use a username, then you need to use a loader function that loads a user object knowing the username. As in Drupal there cannot be two users with the same username, it should avoid the user being acted upon is not the desired one.

function mymodule_menu() {
  $items['auth/%mymodule_username'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page($account) {
  user_save($account, array('status' => 1));
  drupal_goto('<front>');
}

function mymodule_username_load($name) {
  return user_load(array('name' => $name));
}

The code defines a new wildcard argument; if "%wildcard" is the name of the wildcard, then Drupal will look for the wildcard() function that needs to return FALSE in case of error; in that case, Drupal will return the "page not found" error (404).

Important I used the same value you used for "access callback," but it is not something that should be done, in this very specific case.
The reason is that the menu callback alters a user account; imagine what should happen if a user with a blocked account could do if he knows of this URL: He could enable his own account very easily. This is because the entry "access callback" you are using is saying "everybody can access this menu callback," which also means that Google, or any other search engine could enable a user just visiting the URL the search engine has found in some way.
In general, the rule is to restrict the access to a menu callback that alter some data, which includes also the case the menu callback deletes data.


UC Orders and Webfrom Submissions in same view Does anyone know a method to create a view with both 'UC Orders' and 'Webform Submissions'?
I am using 'UC webfrom pane' to collect some extra info on checkout but am really struggling to add this data to a view with order data.

What would be a possible way to do this? Help is much appreciated.

check this out... I had the same issue and was able to solve it: http://archive.org/details/DisplayWebformSubmissionDataInViews


How do I place the registration form in the front page? I am using Drupal 7.

I clicked on Structure > Block > Add Block; I filled in the block title and block description. In the block body, I put in this code.

<?php
  $_GET['q'] = 'user/register';
  print drupal_get_form('user_register');
?>

I set the text format to PHP (PHP wasn't in the drop down options of text formatting so I added PHP to it), and I clicked on save block.

The block is now created but it's just empty. I can't see any sign up form.

Can someone please put me through? I'm new to Drupal.

I just discovered that I had to activate PHP Filter in core modules (administration > modules). So when I activated PHP Filter module, the registration block I created now shows the word "Array", and also some error in the log.

  Notice: Undefined index: user_register in drupal_retrieve_form() (line 764 of C:\xampp\apps\drupal\htdocs\includes\form.inc).
  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'user_register' not found or invalid function name in drupal_retrieve_form() (line 799 of C:\xampp\apps\drupal\htdocs\includes\form.inc).

  Notice: Array to string conversion in eval() (line 3 of C:\xampp\apps\drupal\htdocs\modules\php\php.module(80) : eval()'d code).

However, the "create new account and login" menu is now showing; it is only not showing in the block I created for it. What is showing in the block is "Array"; when I click on either "register" or "log in," it takes me away from the front page (to the register page).

The user register form id is user_register_form. Please try it like:

$form = drupal_get_form('user_register_form');
print render($form);


Using entity_lookup inside an entity_generate migration process plugins I'm trying to use an entity_lookup process plugin inside an entity_generate process plugin. The YML looks like this

field_validation:
    plugin: entity_generate
    access_check: false
    entity_type: node
    source: validation_name
    value_key: title
    bundle: validation
    ignore_case: true
    values:
      title: validation_name
      body: validation_description
      field_validation_type:
        plugin: entity_lookup
          access_check: false
          ignore_case: true
          source: validation_type

The error I'm getting is

  Uncaught PHP Exception
  Drupal\Core\Config\UnsupportedDataTypeConfigException: "Invalid
  data type in config xxxxxx, found in xxxxxx : A colon cannot be used
  in an unquoted mapping value at line 282 (near "  source:
  validation_type")." at xxxxxx line 117, referer: xxxxxx

Because I'm relatively new in using the Migrate/Migrate Plus modules, I'm not sure if the error is triggered because I'm doing something wrong with the syntax or just because I can't use entity_lookup inside an entity_generate. So, the question is: can I do something like this, or I'm forced to use a separate migration instead of entity_generate and the call it with migration_lookup?

[later edit, just for context]

my field definition:

-
 name: validation_type
 label: 'Validation Type'
 selector: $.Description.Validation[*].Type #item_selector is set to $.Schema[*]

the relevant part of the source JSON:

{
  "Schema": [
    {
      "Description": {
        "Validation": [
          {
            "Type": "CUSTOM_TYPE",
            "Description": "lorem ipsum"
          }
        ]
      }
    }
  ]
}

It seems that you actually can use entity_lookup inside entity_generate. The problem here was with the wrong indentation bellow plugin: entity_lookup. Yup... it was that kind of "bug" (feeling embarrassed) :)