Drupal Commerce: Print order for warehouse I followed Drupal Commerce: Print order? solution:

  Through Rules you can achieve this by creating a Rule within the Rules
  module:

  First step create a custom rule at
  /admin/config/workflow/rules/reaction/add Select the React on event:
  "Completing the checkout process" Add a new Action: "Send mail" Once
  you add the email addresses from/to, than add the replacement fields
  in the body text of the email. I suggest:
  [commerce-order:order-number], [commerce-order:type],
  [commerce-order:commerce-line-items]. But you can figure that part
  out. Save your Rule.

I receive the email but I do not have a proper list of ordered products, instead I have numbers. One per article but the change on each order even if the articles are the same.

How can I have a proper order listing in the email?

You will want to use the Commerce Message module: https://www.drupal.org/project/commerce_message

This module provides a !order-summary token which embeds an order's line item summary. This token only works, however, if the Message bundle has the message_commerce_order field.

You can either programmatically add this to a new Message bundle. Or, the easy route, clone the default admin notification and adjust as needed!


Cannot target #id as menu link? Drupal 6

How can i allow drupal to accept #idname as link? When I put # I cannot submit the form. Is there a way to do this?

You have five options.

Use the https://drupal.org/project/special_menu_items module
Do something like node/16#gohere (I'm not sure if you have a static page this is for)
Create a module to either edit a menu item or add one
Backport the https://drupal.org/project/void_menu module
Make your own module to do this :)

Sadly there is no way to do this by default.


Seemingly random  being added into views node header for content type I've got what seem to be random empty
s appearing whilst displaying a custom content type as a teaser in a pretty standard blocks display through Views. Now this is only a problem because it's adding dimension and padding, which can be aleviated but I'd actually rather like to get to the bottom of why it is happening.

        ...

We've created a subtheme of Zen and only have the following files overriden:

block.tpl.php
node.tpl.php
node--news_story.tpl.php
node--product.tpl.php
page.tpl.php
views-view--page.tpl.php
views-view-unformatted.tpl.php

I've cleared the views cache, cleared all caches, not got "compress JS/CSS" etc. selected, rescanned the template files but it makes no difference.

I've not added any custom classes to the views display settings, I've not done anything funky in the custom content types either, not the default/teaser displays. Nearly everything is as it is by default. And we're not using grouping, which I've read can be a problem.

In our custom "news_story" template (and the product one too) we'd carried over something in the header from an old build. This was displaying an empty h3 but commenting it out fixed it completely. And it was not in the rendered HTML at all. Unlike the other blocks, like the Features section.

  <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished || !$page || $title): ?>

        <?php //DONT DO THIS WITH THE H3: it injects it even if the field_news_category is ignored?>

      <?php
        //hide($content['field_subtype']);
       //hide($content['field_field_news_category']);
      ?>
      <?php print render($title_prefix); ?>

However, we've not overriden the other custom content types and I can't find anything in any of the other templates that has any h3 or anything. I've looked through Zen and there's nothing there. I've looked through the Views module and in the Theme folder there was a h3 in "unformatted" so I overwrote that and commented out the
 ...

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

And since we're using the "unformatted" format I can only presume that's all that's needed. I also tried commented out the
 in the views-view-unformatted.tpl.php file in the Views module's Theme directory. And clearing Views caches with Drush. But somehow there's still a h3 getting in there...

<h3> in the views-view-unformatted.tpl.php is outputted only if you use Grouping setting in your view. So commenting that out is a bad idea.

Looking at your markup I can say with confidence that h3 is produced by either one of the following templates:

node.tpl.php
node--news_story.tpl.php
node--product.tpl.php

Good point was made by rhuffstedtler, about checking which template is producing the markup.

find settings.php file and uncomment the line (usually last line) that says:

$conf['theme_debug'] = TRUE;.

Then refresh your page and check the source HTML code. You'll figure out from there which template you should be modifying.


How do I find out which Contrib module is compatible with PHP 7? Drupal.org misses a PHP version field. As far as I can see, I have to go through the issue queue or .info file for every third-party module to find out which PHP version is supported. Is that correct?

Sort of.

The PHP version isn't a required key for module .info files, and it's a minimum version of compatibility anyway. So a module could declare itself as requiring PHP5.6, but still work absolutely fine under PHP7. Or it could not declare a minimum version of PHP at all, and still work under PHP7. Or it could declare PHP5.6 as minimum, but not work at all in PHP7. You get the idea.

So yes, you need to check on a case-by-case basis to find out which will work under a specific version of PHP.


How to display custom token in custom block In a Drupal 8 website I created a custom token that is working in basic page.

Then I created a custom block with a WYSIWYG field :

class Myblock extends BlockBase {

  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public function getMachineName() {
    return 'my_custom_blcok';
  }

  public function label() {
    return $this->t('Block label');
  }

  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['my_field'] = [
      '#type' => 'text_format',
      '#format' => 'content_manager',
      '#title' => $this->t('Field name'),
      '#default_value' => isset($config['my_field']['value']) ? $config['my_field']['value'] : '',
    ];

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->setConfigurationValue('my_field', $form_state->getValue('my_field'));
  }

  public function build() {
    $config = $this->getConfiguration();
    $content = $config['my_field']['value'];

    return [
        '#theme' => 'simulator_block',
        '#content' => $content,
      ];
  }
}

If I type My content [module:my_token] in the WYSIWYG.

The following content is display :

My content [module:my_token]

How can I replace the token ?

Place the formatted text in a render element processed_text:

 $content = [
    '#type' => 'processed_text',
    '#text' => $config['my_field']['value'],
    '#format' => 'content_manager',
  ];

  return [
    '#theme' => 'simulator_block',
    '#content' => $content,
  ];

Configure the text format to include the token filter.


View translation path I have a View with an path like example.com/en/news. I translated the view with Views translation. Works like a charm. But how and where do I translate the path to something like example.com/de/neues?

a very simple way would be to add a new alias yourself by accessing "/admin/config/search/path"

however, if you have translation set up correctly, that path should already exist.  I think maybe your translation set up is done in a non-standard way.  could you describe it in detail?


How to edit the user created date? For node, we can change the created date easily, what about user ? Is there any easy way or module that can expose this field for editing instead via database ? I have many old users to be keyed in again manually into drupal, so I need to change this date of creation at the time of creating the user.

I haven't done this before, but if you have a module that loaded a user account, perhaps using user_load(), you can manually re-set the $account->created.  Clues given in the user_save() function.  Let me know how you get on...

code will look something like this:

$account = user_load($users_uid_here);
$account->created = $date_timestamp_here; // eg. REQUEST_TIME
user_save($account);


Images instead of radio buttons or dropdown list? I would like the user to choose the category when he creates a new node content. However, instead of radio buttons or dropdown list I would like to have selectable images, with exactly the same logic. Is it possible to somehow ovveride radio buttons / dropdown lists with options being displayed as images? So, for example instead of a radio button with 'Cars' label I would like to have a picture of a car, then for the next category another picture, etc. Any advice appreciated.

You can accomplish this with a combination of a little JQuery and CSS.

Here's some starting points

http://codeloaded.com/fullscreen-preview/jquery-image-checkbox
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://codecanyon.net/item/jic-jquery-image-checkbox/full_screen_preview/676874
http://boedesign.com/blog/2008/06/08/imagetick-for-jquery/

Then use a custom module to load the JS when needed using drupal_add_js() typically instantiated with a hook_form_alter().

Something like this:

/**
* Add example.js to content type 'car' create/edit form for example.module
*/
function example_form_alter(&$form, $form_state, $form_id) {
if ('car_node_form' == $form_id) {
  drupal_add_js(drupal_get_path('module', 'example').'example.js');
}

You can find more examples for detecting different forms and patterns on the hook snippets page.


Filtering CCK views by path I've created a View in Drupal 6 which I am using to display a list of events. I would like to be able to filter the view by year via the path like this:

http://www.mysite.com/events -> gives me all events
http://www.mysite.com/events/2011 -> gives me the events in 2011
http://www.mysite.com/events/2010 -> gives me the events in 2010

I see that you can specify arguments in the path, but I can't seem to be able to access that argument to use within the filter controls for the view. Any help would be greatly appreciated.

You want to add a filter and use "Date: Date (node)" not "Node: Date" for a CCK date field. Then, you can choose "Select" and granularity of "Year". Once you expose the filter, you will get a drop down list to choose a year to filter by. The paths will need to be arguments, as you've found out. But, they will work separately. If you want the drop-down to only work with those specific paths, I think you have to create your own select box.


How to override the user edit page using Panels? I am trying to override the user edit page in Drupal7 using Panels. I checked the selection rule as user being edited are one of authenticated and administrator.
However, when I try to add a context to it and select the context User being edited, it asks me:

Enter the name or UID of a node
(A user edit form)

What do I write in here, any suggestions? Am I on the correct track or do I have to add any other context or relationship as well?
I also tried giving different path and ID but then I get some kind of ajax error.
Ps: Below is my screen shot, what do I enter in the first field?

user_edit panel default context is the current edited user. Why do you need to add an additional context with a user?

If you need to access to user values you can use the default context. For example you can use %user:uid in order to load the user ID which is being edited.


url() not providing links to correct language alias using i18n in D7 We have a site that features two languages, EN (primary/default) and JA.  On one content page, we link to another node using it's nid: url('node/123').  In EN, this returns the alias and not the node based url.  When in the JA language, this returns a url like /ja/node/123 which then shows text in the EN variant when we expect JA.  There are aliases set for both EN and JA, which both point to the same desired URL like: /products/new-fancy-product and their respective node id urls.  In EN, url returns this alias correctly.

Also, if I change /products/new-fancy-product to /ja/products/new-fancy-product in the address bar, I get the correct JA version of the page as I want.

Why is url not returning me the correct alias instead of the node id path, which then just shows EN content?

Use l() function to generate a link.

  Formats an internal or external URL link as an HTML anchor tag.

  This function correctly handles aliased paths and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.


How to get a field third party settings for every content entity forms Can someone explain or post an example of how to get a third party field settings on every content entity forms?

I'm looking for a generic code where a form can be customized (like calling a custom validator) if any field present in that form is having the third party settings that I have defined.

It could be a node form, a block form, a paragraph etc.

Implement hook_field_widget_form_alter() to alter form elements of any content entity form.

For example how to add a validate callback when you have third party settings stored in the field configuration:

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition instanceof \Drupal\field\FieldConfigInterface) {
    $mymodule_settings = $field_definition->getThirdPartySettings('mymodule');
    if (!empty($mymodule_settings)) {
      $element['#mymodule_settings'] = $mymodule_settings;
      $element['#element_validate'][] = 'mymodule_element_validate';
    }
  }

}


Get view and process content I'm trying to build an infinite scroll with views using a custom ajax callback function, every view has only 1 node displayed. What I would like to do is use the offset to load the correct view. To be clear, I already tried views infinite scroll and infinite scroll modules and for various reasons I cannot use them.

What I got so far is this:

$view = views_get_view('frontpage');
$view->set_items_per_page(1);
$view->set_offset($offset);

$view->execute_display();

This gives me back the right markup with the right node.

My question is, what if I want to process the node loaded in the view before getting back the markup? Is this possible? I've looked through the view API multiple time without finding something suitable.

You can display anything using Views: Nodes, users, comments, fields. Drawback is - Views object does not particularly care about the type of data. As long as handlers can process it, it works. But that means it cannot really expose methods related to the kind of data displayed. It might be possible to hack around it, but it's not the way it was designed to work.


How do you do download the files folder from the Acquia cloud service? I just setup acquia cloud and have a site setup. I've did a git clone to my local desktop along with downloading the DB manually. But how do I get the files downloaded to my local desktop so I can do my own local testing?

Is there a quicker way to do this via drush to get the latest files and db pulled down?

You can read up on some drush specific tasks that you can do in this Elevated Third blog post

Acquia supplies drush commands and aliases that tie into Acquia Cloud API calls. So you can actually simply use the alias and the rsync drush command:

drush rsync --progress @sitename.env:%files @localenv:%files

You can also create and download Acquia database backups with the ac-database-instance-backup and ac-database-instance-backup-download commands.

Also, if you want an "all-in-one" solution, the newer versions of Acquia DevDesktop tie directly to your Acquia cloud account and can get database and file syncs automatically.


Entity reference no sorting by field I have a problem that I have not been able to find the solution. I have an entity reference field for a node to display specific news I need them to be sort them by the date they were created by the latest. In the field settings there is an option to  sort by created but it is not applying the sorting. Is there another way that I can sort them maybe using rules, or programatically. Any idea what I am doing wrong? I cannot use views for this particular problem because each node display different news, do it manually is not an option either because I am creating the content using web services.

NEWS ORDERED BY THE LATEST

September 12, 2012
lorem Ipsum is simply dummy text of the printing and typesetting industry.

June 12, 2012
lorem Ipsum is simply dummy text of the printing and typesetting industry.

May 12, 2012
lorem Ipsum is simply dummy text of the printing and typesetting industry.

You can always use the  Views: Filter by an entity reference view  option from Entity selection mode and then create a view as per your sorting options and filters and select the view in the select box which shows up.


Alter module js for on custom page I have a small problem with altering js code loaded from custom module. I need to change the js script from a module for a custom page

Module code code :

function module_script_src($environment) {
  $script = '';
  $script_id = variable_get('script_id', '');
  $script_hash = variable_get('script_hash', '');
  switch ($environment) {
    case 'prod':
      if ($script_id && $script_hash) {
        $script = '//example.com/' . $script_id . '/lib-' . $script_hash . '.js';
      }
      break;

    case 'dev':
      if ($adobe_dtm && $site_hash) {
        $script = '//example.com/' . $script_id . '/lib-dev' . $script_hash . '.js';
      }
      break;

  }
  return $script;
}

The goal is to change $script just for one custom page, i try to add case for my custom page, simply new case to module

 case 'custom page':
       if ($node && $node->nid = "my_node_id"):
     $script = '//example.com/' . $script_id . '/custom-' . $script_hash . '-.js';
  }
      break;

But it does not work, if it possible in module to load custom is for the specific custom page?

In the switch statement you provide, you are switching over $environment variable. It sounds like it will never be passed a URL or 'custom page' value.

You are also trying to use $node object but you have not loaded it from your code. You are also not passing $node as an argument. Also an $adobe_dtm variable is used but never defined. Plus, you are using = to do an equality check, you need == or ===. = is assigning 'my_node_id' to your variable instead of compare it.

In order to have a $node object present in this function, you need to do one of two things to get it:

$node = menu_get_object('node');
$node = node_load(arg(1));

Then you can just add this after the switch statement:

function module_script_src($environment) {
  $script = '';
  $script_id = variable_get('script_id', '');
  $script_hash = variable_get('script_hash', '');

  switch ($environment) {
    case 'prod':
      if ($script_id && $script_hash) {
        $script = '//example.com/' . $script_id . '/lib-' . $script_hash . '.js';
      }
      break;

    case 'dev':
      if ($adobe_dtm && $site_hash) {
        $script = '//example.com/' . $script_id . '/lib-dev' . $script_hash . '.js';
      }
      break;

  }

  if ($node = menu_get_object('node')) {
    if ($node->nid == "my_node_id"):
      $script = '//example.com/' . $script_id . '/custom-' . $script_hash . '-.js';
    }
  }

  return $script;
}

You may need to think through the cases involved in building the script value. It looks like the switch statement is not even necessary, because $script value is basically the same - in which case you can clean up the code by simplifying it.


Field with author link in node i am building a website where many users will be able to add specific content. I want each content-node to have a link to the the authors profile page. I am using profile2 for users profiles and the alias of link in the node must be the "Company Name" field and not the username.

How can i achieve this?

Thank you!

Why don't you just use Views, and place that view towards the bottom of the article or that content type?

The views will be based on a user relationship with the node uid (the author's user id).

All those fields you require you can add to the user profile (admin/config/people/accounts/fields) - Company Name, Byline etc etc? And then display them via views.


How to Map files if I have fid in Drupal 6 table and field in Drupal 7 content type? I have a drupal 6 database in which custom table is used to store the details. In the custom table a column fid contains the fid of file.

I have migrated the files and it migrated successfully. I mapped the node fields to that fid. I have added the following code :

$this->addFieldMapping('field_image', 'fid')->sourceMigration('ExFiles');

It showing me following message :

The specified file 3424 could not be copied to public://3424.

I want to know how to map files from custom table field?

I think you also need to specify the file_class:

$this->addFieldMapping('field_image', 'fid')
  ->sourceMigration('ExFiles');

$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');

This is explained in the file migration docs; without the class, the source is assumed to be a URI and not a fid.


Why can't Drupal write to the database after migrate/restore? When I want to do more development on a live site, I usually make a copy of the files and database on my local LAMP install and play with it there.

Now I'm finding that if I copy the database to local using Backup and Migrate or importing/exporting with phpMyAdmin, the local Drupal can only read from the database. It displays pages, but any edits or admin changes don't get saved. No errors, just nothing changes.

I've tried clearing all caches and running update.php. I'm running the same Drupal version live and locally. If I install Drupal locally from scratch, no problems at all.

What am I missing here... or is there a better way to achieve production/live cloning?

It was a schoolboy error on my part. I didn't have mod_rewrite enabled on my local environment, so clean URLs weren't working.


Is it possible to add fields definitions in entity? I created an entity using drupal console and now I would like to add fields to it. These should be references to other entities. I want these fields to be added programmatically, in the code. Ideally in the entity class so I can use entity methods to load referenced entities. How do I do that?

Thanks.

When you create an entity using Drupal Console you'll find such a field as example already defined in baseFieldDefinitions(), which references the user entity:

$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Authored by'))
  ->setDescription(t('The user ID of author of the {{ label }} entity.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

You can define as target other entities:

  ->setSetting('target_type', 'my_other_entity')

BTW the two last two lines of the example make this base field configurable in UI. You can set this to FALSE if you don't want that anyone can change the configuration you've made in code.

You can customize this, for example if you want a dropdown select element:

  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 5,
    'settings' => [
    ],

To implement code to load the referenced entities extend the field widget OptionsSelectWidget, add a custom plugin id to the annotations my_options_select, which you can use for the type in the example above

    'type' => 'my_options_select',

and override the plugin methods to load the options. For simple cases use hook_options_list_alter, this hook is invoked by the widget base class method getOptions().


Migration from a remote database PDOException I'm setting up a database migration. For now, I'm using the ssh tunnel to access the remote databse.

Here is the configuration in the Migration class:

<?php
...
Database::addConnectionInfo('for_migration', 'default', array(
  'driver' => 'mysql',
  'database' => 'database',
  'username' => 'user',
  'password' => '****',
  'host' => '127.0.0.1',
  'port' => '1000',
  'prefix' => '',
));

// Conect to the remote $databases
$query = Database::getConnection('default', 'for_migration')
    ->select('Content', 'ct');

// Better descriptions for wineid and name; best_vintages is added in prepareRow()
$source_fields = array(
  'id' => t('article ID'),
  'contenido' => t('Contenido'),
);

// Create a MigrateSource object, which manages retrieving the input data.
// Tell the source class not to try to join the map table.
$this->source = new MigrateSourceSQL($query,
    $source_fields,
    NULL,
    array('map_joinable' => FALSE)
    );

$this->destination = new MigrateDestinationNode('article');

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'id' => array('type' => 'int',
                           'not null' => TRUE,
                           'description' => 'Article ID',
                           'alias' => 'id',
                          ),
        ),
        MigrateDestinationNode::getKeySchema(),
        'for_migration'
    );

// @todo Mapped fields
$this->addFieldMapping('body', 'content');
?>

When I try to access the migration UI page the count of items is correct, but I get and error when I try to load the task page to visualize the mappings and elements.

DOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Content ct LIMIT 1 OFFSET 0' at line 1: SELECT FROM {Content} ct LIMIT 1 OFFSET 0; Array ( ) in MigrateSourceSQL->fields() (line 211 of /Users/brightsitesSM/Sites/devdesktop/independentpoc-dev/docroot/sites/all/modules/migrate/plugins/sources/sql.inc).

Probably there is something missing in the code as the SELECT in the SQL query is empty.

Here are the screenshots of the migration page:

... and the task page error:

The problem with the code is the connection to the database. There aren't fields in the select.

SELECT FROM {Content} ct

To solve that one of the solutions is adding ->fields('ct'); to the database connection. This will select all the fields from the table ct:

SELECT ct.* FROM {Content} ct


drupal_add_js does not add javascript on after_build I'm using the following line to add JavaScript code to my module form:

$form['#after_build'][] = 'myModule_after_build'

In myModule_after_build(), I add the Javascript code with calling drupal_add_js('myJavascript','inline').

Unfortunately, it seems that the JavaScript code is added only during the first page call.
I would like to pass some arguments to JavaScript, and manipulate the content of the JavaScript, according to the options in the form.

Is there any configuration that I can set to add 'myJavascript' with different arguments to every button click?

#after_build is called every time the form it built. I've used this myself many times to add JS to forms. Most likely you have a flaw in the script or after build function itself, or you are using cached data when creating the script to display.

If you posted your code, we could provide a better answer.


How to change date format in the webform date element? I have added a date element to my webform.
Now I want to change the date format for the date element.
I have used the following code.
function my_module_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
  if ($element['#type'] === 'date') {
    $element['#date_date_format'] = 'd/m/Y';
  }
}

But I can still see the date element like this.

And when I try to submit the form and I get an error on date field.
Also is there a way to change the date format in the email which webform sends?

The date format in the field depends on the operating system settings. So it will display the date format according to the format set in your OS.
For the date format in the email, You need to change it from admin/structure/webform/config/elements in the Element formats section by setting the default format for the date field.


Drupal Commerce Rules if Paypal Payment Method is Selected What's the best event trigger for the following:

Remove all Taxes if Payment method selected is Paypal.
Add %3 to Total if Payment method selected is Paypal.

Thanks.

You can use the event

'After updating an existing commerce order'

on condition

'Selected payment method comparison' under commerce Payment and select its value to 'Paypal'

Now in action add 'Remove taxes applied to a line item' and another action 'Add an item to list' to add %3 amount to total .

It will perform accordingly.

Hope it will work for you!


Creating config schema file for mutable data I have a custom module where I need to have a couple different types of configuration, both immutable and mutable. The immutable portion contains a feed URL for a couple different sites, so I have /my_module/config/install/my_module.settings.yml set up like this:

sites:
  site1:
    channel_url: 'http://www.site1.org/feed/channels'
  site2:
    channel_url: 'http://www.site2.com/feed/channels'
list_time: 24

That works fine, and I can read from it via $config-get();.

The second part of my settings involves mapping of tids between the two sites (used for importing video nodes from one site to another. My initial thought was to modify the settings like so:

sites:
  site1:
    channel_url: 'http://www.site1.org/feed/channels'
    mappings:
      1: 1
      2: 2
      3: 3
  site2:
    channel_url: 'http://www.site2.com/feed/channels'
    mappings:
      7: 7
      8: 8
      9: 9
list_time: 24

However, since this is mutable, it appears that this isn't allowed (based on the error messages I get when I try to run $config->set().

From what I'm finding, it looks like I need to have a separate schema config file for my mapping data. I'm still wading through docs, but if someone could verify if I'm correct in my thinking and maybe provide a sample of what my schema should look like, I'd appreciate it.

UPDATE: Reading through this change record, it appears that I can write to my settings file if I declare it in my form class in getEditableConfigNames(), which I've done:

protected function getEditableConfigNames() {
  return ['my_module.settings'];
}

It also appears that, according to the error message I get, I need to retrieve it with \Drupal\Core\Config\ConfigFactoryInterface::getEditable()

Drupal\Core\Config\ImmutableConfigException: Can not set values on immutable configuration my_module.settings:sites. Use \Drupal\Core\Config\ConfigFactoryInterface::getEditable() to retrieve a mutable configuration object in Drupal\Core\Config\ImmutableConfig->set() (line 27 of core/lib/Drupal/Core/Config/ImmutableConfig.php).

Just keep swimming....

UPDATE2: Base on @berdir's comment below, I'm showing what I have, since in my original question, I didn't state that I am already using the ConfigFormBase class:

class MyModuleAdminForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildform(array $form, FormStateInterface $form_state) {
    $form = array();
    $channels = array();

    // build form here

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

  /**
   * {@inheritdoc}.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  protected function getEditableConfigNames() {
    return ['my_module.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $config = $this->config('my_module:settings');

    foreach($values as $site => $mappings) {
      if (is_array($mappings)) {
        foreach ($mappings as $source_channel => $target_channel) {
          $config->set('sites',[$site => ['mappings' => [$source_channel => $target_channel]]]);
        }
      }
    }
     $config->save();

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

However, this still gives me the same error. Am I using $this->config() incorrectly? Or do I still need to use getEditable() somewhere?

Mutable or Immutable has nothing to do with config schema, that's something else.

getEditableConfigNames() only works if you actually implement \Drupal\Core\Form\ConfigFormBase and $this->config().

Otherwise you need to explicitly get the config.factory service or \Drupal::configFactory() and then call getEditable() on that, instead of get().


How do I extract individual fields from rendered user? I am developing a community website. We have two separate types of members -- regular members and business members. Business members can access subscription options to sponsor the chapter (website) but the members are not able to access these subscriptions.

I am using lm_paypal for the subscriptions, as it seems to do just what we need it to do.

My only problem is that lm_paypal hardcodes their information in the user profile. THere are three blocks it places on the user profile (or rendered user): a donations block, an active subscriptions block and a block to allow you to subscribe and unsubscribe from subscriptions.

Here is the function in lm_paypal_paid_averts that does this (I think!)

/**
* Implements hook_user_view().
*/
function lm_paypal_paid_adverts_user_view($account, $view_mode) {
global $user;

// In the "my account" view area show all paid_adverts
if (user_access('administer lm_paypal') || $user->uid == $account->uid) {
$account->content['paid_adverts'] = array(
  '#type' => 'user_profile_category',
  '#title' => t('PayPal Paid Adverts'),
  '#weight' => 6, // under History which is 5.
);
$account->content['paid_adverts']['subs'] = array(
  '#type' => 'user_profile_item',
  '#title' => t('Adverts you paid with us:'),
  '#markup' => lm_paypal_paid_adverts_list_nodes($account->uid, 10),
);
 }
}

The only way I can see to display this information is by using the "Rendered User" field in Panels, which displays a lot of other things, including history, recent content, etc. It also displays it on all user profiles, regardless of whether the user can actually access the subscriptions or not (my members can click on the link, but they get access denied page). I would like to have the subscription blocks showing only on the business member profiles and the donation blocks showing on all profiles.

What I need is a way to pull out just this lm_paypal information from the rendered user so that I can display it in its own block and set access control on it so only business members can actually see the subscriptions.

I've been googling for an answer to this for almost a week and found a few different solutions that may work, but require extra modules to be installed and it seems like a lot of extra weight for just needing a piece of a whole. I've found some answers regarding placing code in places, but I have to admit, I'm so close to having this presentable, I'm slightly terrified of trying too many things and somehow messing up. I've built this site myself, starting with no experience at all, and I've had many ups and downs along the way... I am terrified being this close to done and doing something to mess it up and not be able to recover it.

So I am hopeful that someone here can give me a clear answer where I don't have to make guesses and assumptions and perhaps mess myself up!

Is there a way to pull these fields from the user profile and print them separately in their own block?

A lightweight custom module to create a block for your business members and one for your regular members should do it. Creating a custom block isn't as daunting as it seems, it's one of the easier customizations you can do. The Block API should be very helpful here. Here's a quick example:

 /* Implements hook_block_info() */

function myblock_block_info() {
  $blocks['my block'] = array(
    'info' => t('Business User Block'),
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  return $blocks;
}

/* Implements hook_block_save() */

function myblock_block_save($delta = '', $edit = array()) {
  variable_set('block_text_prefix', $edit['block_text_prefix']);
  variable_set('block_text_suffix', $edit['block_text_suffix']);

}

/* Implements hook_block_view() */
function myblock_block_view($delta = '') {
  //get the information you want out of the profile here
  $block['content'] = //your information formatted here
}

Devel info:

If you double click on a row in the devel table, it will tell you how to reference it:


Does leaving the Views UI module enabled affect performance? I noticed that the "Disable Developer Modules" link in the Administration Menu module disabled the Views UI module. I'm under the impression that the purpose of disabling the developer modules is to reduce performance impacts. But I didn't think the Views UI module would have an affect on performance. Does leaving Views UI enabled in production have any performance impact? Is there any other reason to disable this module on a production site?

Every enabled module affect performance, just for the fact they are loaded, and parsed from PHP. views_ui.module, in the branch 6.x-3.x-dev of Views, is 10355 bytes.
There are then hooks that are invoked from Drupal, even if you are not using anything from the Views UI module, such as views_ui_help(), views_ui_menu(), views_ui_theme(), or views_ui_library_alter().

Another reason to disable unused modules is avoiding possible security issues.


How to select a particular node reference in a view programmatically I have two custom node types : catalog_item and category.

The catalog_item node has a cck node reference field that allow a user to select multiple category nodes. I want to be able to select a particular category from the node reference based on some php code. Is this possible with views?

Within the views API, you could use this field as an argument and then use PHP to supply the default argument.  This would then restrict the views to all catalog_items that have that specific category node referenced.

If you are doing this in code/a module/template/etc, you could do it also like this:

$nid=WHATEVERPHPCODEYOUWANT;
return views_embed_view(VIEWNAME,'default',$nid); // 'default' is the views display


Teaser trouble with Views block I have a content type of blog that I created a view for and added a display of that view. I created a view block and have it displaying on the front page in the main content block. I decided that I would rather display the blog posts as a teaser instead of the full text but I can't seem to get it to work.

I set up the content type as a teaser under manage display. Should I be able to select the blog teaser as a content type separate from the default blog display under filter criteria in views? Essentially how do I go about setting the content type blog, within my views block to display teasers instead of the full content?

Set views to output as Show: Content | Teaser

Then in your content type > manage display, click the teaser display mode tab, then set the body field to 'Summary or Trimmed'.

Hope that helps.


Store images in file or media entity? If you start now a Drupal project. Which way should you go for image files. Is it safe to use the module Media now. Can you upgrade to Drupal 8.3 with parts of Media in core?

I would go with Media suite simply because I believe files should be treated like full entities as nodes are. It grants you more options and flexibility in media management and reuse instead of the standard upload field.


Add role on custom register form I'm using the default register form on a custom page, which I want to use to set a specific role for the user who registers using that custom page.

Now I need to know how I add this specific role when the user registers.

Can I use like, the submit funcion for the custom form function, and then use user_multiple_role_edit()?

But how di I get the $uid?

What's best?

Here is my solution based on my favorite Rules module ;)

These 2 rules below automatically assign a predefined role to a user who registers to your website using a promotional link and code.

Important: Before importing these 2 rules:

backup your site :P
replace example.com with your domain name
replace 11 with your role id number
replace code=promo1 with your secret promotional code

You can import rules via this page on your website:
/admin/config/workflow/rules/reaction/import

Rule 1:

{ "rules_auto_assign_role_1" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "11" : "11" } } } },
      { "data_is" : {
          "data" : [ "site:current-page:url" ],
          "value" : "http:\/\/example.com\/user\/register?code=promo1"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "user?code=promo1" } } ]
  }
}

Rule 2:

{ "rules_auto_assign_role_2" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_view" ],
    "IF" : [
      { "AND" : [
          { "NOT user_has_role" : {
              "account" : [ "site:current-user" ],
              "roles" : { "value" : { "11" : "11" } }
            }
          },
          { "data_is" : {
              "data" : [ "site:current-page:url" ],
              "value" : "http:\/\/example.com\/user?code=promo1"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "11" : "11" } }
        }
      }
    ]
  }
}


How do I send webform submission data to a google sheet? I have implemented the webform module on my Drupal 8.4 site. I have some forms that I would like to submit the data to a google spreadsheet, instead of the drupal database.

Can someone help me get started with this?
Do I need to create a custom module to implement this functionality? What hooks do I need to use? Is there any documentation/tutorials out there on how to do this?

Right now the only available solution is to use Zapier.

Ivan Zugec did a great screencast showing How to Create Forms using Webform and Contact in Drupal 8 and includes a demo showing how to push webform submissions into a Google Sheet using Zapier.

Hopefully, someone will port the Webform to Google Docs module from D7 to D8.


How to make taxonomy term name field work with 'Full HTML' text format? As taxonomy term name field supports only plain text, all I want is to use non-breaking space (&nbsp;) for taxonomy name. Just to achive better html layout.

Try using the check_plain function in your template file. Similar to what is shown in this example (which is for menu items though).


Passing PHP objects and methods as strings to FormAPI When working with objects, how do you pass a method to the FormAPI's ['#after_build'] feature?

For example, how can I pass $myObject->_my_after_build_function to ['#after_build']?

Non-OOP exampe of what I would like to accomplish:

$form['#after_build'][] = '_my_after_build_function';

I think your best bet is to call a function that will call

$myObject->_my_after_build_function();

One way that won't work most likely.

$method_name = _my_after_build_function;
"$myObject->{$method_name}"

Another shot in the dark that might work if using PHP 5.2.3+ http://php.net/manual/en/function.call-user-func.php.

"myObjectClassName::_my_after_build_function"

You can try the above 2 methods but with a & in front of it. http://www.php.net/manual/en/language.references.pass.php


Broken modules are not rolled back I try to develop a D8 module with entities. A lot of them ^^. But there is an issue with the way D8 handles the creation of tables during the installation process. If the definition of the entities is not correct D8 can't create the table. But the module is enabled anyway.

Now D8 is not able to uninstall the module. I have tried drush pm-uninstall, drush cr, drush dre on the module. The uninstall process fails every time because D8 cant find the table and is obviously not aware of the failed installation of the module.

The only way I figured out was to create the tables with the primary key and then to uninstall the module. That works, but is very time consuming. How can I force uninstall my module even if the corresponding tables doesn't exist? And why is D8 ignoring the fact that the module was not installed correctly in the first place?

This is a known bug: https://www.drupal.org/node/2563515

As a workaround, remove the entity type definition (e.g. by removing the @ so it doesn't parse it as an annotation), clear cache, then uninstall.


How to define a menu with and without url arguments in hook_menu? $items['jobs/%'] = array(
    'page callback' => 'custom_changes_jobs_interface_create_update',
    'access callback' => TRUE,
    'page arguments' => array(1),
  );

I need to use jobs for POST request and jobs/% for put and delete request where the argument would be string but if its not passed I want to make sure it works.

You have two options:

1) Define both paths, jobs and jobs/%.

2) Define only the first path

$menu['jobs'] = array(
  'page callback' => 'my_page_callback',
  ...

Then make the argument optional:

function my_page_callback($job_id = FALSE) {
  ...

This callback will be called for both paths.


Should I use contextual filters to limit the view results for each type of administrators? I'm trying to display the View according to the current director, example:

I have a content type called faculty news,and I have two faculties: Medicine and Sciences, the content type faculty news is all news of medicine and Sciences.
I have two administrators: admin-medicine and admin-sciences, each one has permissions to publish, read and write only in his faculty.
I have the View: Administrator faculty news
with the path http://example.com/administrator-faculty-news

This view display nodes from content type faculty news.

Now I want to enhance this view like so: when the admin-sciences administrator uses the path http://example.com/administrator-faculty-news, then only the news of the Sciences faculty should be shown in the Views results, and the same for admin-medicine (only show the news of the Medicine faculty).

With contextual filter? How can I do that?

Note: Medicine and Sciences is implemented using taxonomy.

Contextual filters

I suggest you review the (free) video about Contextual filters with paths. It covers topics such as:

Using contextual filters for filtering Views result.
Using input from the view path to set contextual filter values.
Using contextual filter values for changing the view title.

If you like its content, you may also want to watch about 5 subsequent videos, also related to contextual filters (sometimes called "arguments" also).

Content Access

Even though your question is specific to Views, it seems like you should give it a thought to also get the Content Access module involved in your setup. Here is a quote from its project page:

  This module allows you to manage permissions for content types by role and author. It allows you to specify custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Just use this module to give appropriate access to each of the groups of users for each of the content types you have. After you do, the view you currently already have will probably not need any (or just a few) refinements. Because Content Access (if configured correctly) will make sure that the view results only include the news from each faculty.

Bonus: you'll find other use-cases for this module soon!

Organic Groups

Organic Groups is possibly an alternative also, which provides 'Groups' for Drupal users, and management of Access Control based on these groups.

In your case, each faculty would probably correspond to 1 such "group". And similar to using Content Access, the view you currently already have will probably not need any (or just a few) refinements.

Bonus: you'll find other use-cases for this module soon!


Arbitrary rating field I need a field that will allow content editors to enter a rating while editing a node, with the options 'yes', 'no', 'maybe' and 'unknown'. I then want to be able to display those ratings in a view, as images (tick, cross, fence, ?). I need to be able to have more than one on each node.

I can't do this with the rate module, because it doesn't do fields (there is a rate field issue, but it's not moving very fast). Fivestar only does five-star ratings, so that's out.

Optionally, I would also like to be able to give each result a numerical value, so that I can do calculations across fields (e.g. median).

Are there any options out there that can do this kind of rating?

I need a field that will allow content editors to enter a rating while editing a node...

You could use Drupal's built in Field API to do this. Given that a node will already be in edit mode while being rated, you wont need any additional add-on modules.

If you use the integer type, calculations should be simple.  You can override the text like this:

To add the images next to each item, you could use CSS.  Each element should have the necessary classes to theme them as required.


Multiple currency  displayed in ubercart product page I have a website where I need to display the product in 2 different currencies. Once the user selects one price, adds the product to cart, and tries to checkout, the currency can be posted to the payment gateway in USD. For example, if the user selects the price in Indian Rupees as 450 INR and tries to checkout, the value is converted into USD if the user pays through Paypal, but if the user selects the Indian Payment gateway, the same will be posted as 450 INR. How can we do this?

Take a look at Ubercart Currency Conversion. From the project page:

  This module converts prices of ubercart products from one currency to
  another currency. The target currency will be selected as follows

  Administrators can select the currency and force all prices to be
  automatically converted
  If the above is not set, then the currency is determined based on
  user's address
  If the above is not possible, then the site's default currency is
  used.

  The module depends on Currency module.


Has anyone implemented a tablesort with ajax? I would like to sort on a column with a round trip but no page reload. The table is very large and has to be paged in, which I am doing manually with an ajax select element. I know TableSort is available to extend the query but I've only seen examples that reload the page.


Views arguments from URL how to get the arguments from the URL and store it for further processing in views drupal 7.I am passing a token from a webform to a view through custom redirect URL.Later i need that value for some calculations.I need some help on how to do this.

I've done this for Drupal 6.

In Views 2, I've had to define where in the URL the parameter(s) would be located positionally (e.g. blah/view_name/%/%) where the % represent parameters 1 and 2 respectively; then, in my next view (which was either another display or attached view within the same view file) I defined the arguments in the argument section and then they could be referenced as %1, or %2 respectively.


How to apply specfic coupon in ubercart while creating an order from backend means admin pages I am using ubercart. I am facing two issues while creating an order from backend.

1.) How to add coupon codes on add order admin page ?
i need to add orders manually from backend but not able to apply coupon codes for discounts, there is only a feature to "add a line item" but not for coupon.
I think there should be a textbox to fill coupon code and apply button to apply it.

2.) If coupon is applied to manually created order then tax calculation should be done after coupon price deducted from subtotal.

1.) How to add coupon codes on add order admin page ? i need to add orders manually from backend but not able to apply coupon codes for
  discounts, there is only a feature to "add a line item" but not for
  coupon. I think there should be a textbox to fill coupon code and
  apply button to apply it.

If you want to apply a coupon code from the admin page. Use the uc_discounts_alt module that provides you three submodules(uc_discounts,codeless_discounts_field,product_price_alterer_field).
Enable the uc_discounts module it will provide you the textarea at the admin configuration page to apply the discount code.
1)Go to admin >> store >> orders >> create
2)Enter the customer information
3)It will open the create order screen as shown in the screenshot below

  2.) If coupon is applied to manually created order then tax calculation should be done after coupon price deducted from subtotal.

Yes.


Structuring a user rating/rebuttal system I am looking to create a really basic rating system (user reference and fivestar content type). But I would like to be able to have users rebut ratings if need be. I am just trying to figure out, structurally, how to do it. Would I have to create another content type called rebuttal and reference the rating? What about adding a field to the rating content type with the ability for the referenced user to fill in a text field? Limit comment access to just the rating author and the referenced user?

This may be the wrong forum to ask this, since its an open ended and subjective question. But I guess my question would be "How would you allow users to make selective edits to a node or limit comments to only the node author or referenced user?"

Use the Flag module to create a Rebut flag, but do NOT make it a 'global' flag though. The flag is to be created (configured) by an admin, but each user (authorized to use the flag) will then be able to "rebut rating" using such flag. If it would make sense, you may want to have multiple flags configured for this (eg: Rebut-low , Rebut-medium, Rebut-high, whatever that would "mean" in your case).

Then create a view (with the views module) for each flag, whereas you create a "views relationship" with such flag(s).

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

You might also want to look at some of the Flag related modules, such as (partial list):

Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.

Refer to Flag's Community documentation for (way) more details.

Note: Via Rules it should be possibly to add logic to verify the "usage" of such flag.


Is it possible to have multiple instances of the same field in one content type? I understand that it is best reuse fields where possible and to avoid unnecessary duplication.

So is it possible to duplicate or reuse a field (or field instance) on the same content type?

For Example: A news article with both a cover image and an image gallery. Is it possible for both to use field_image or must there be two distinct fields, such as field_cover_image and field_gallery_image ???

No, field instance is unique within a content type. See field_create_instance. Relevant code for checking uniqueness in that function:

// Ensure the field instance is unique within the bundle.
// We only check for instances of active fields, since adding an instance of
// a disabled field is not supported.
$prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
if (!empty($prior_instance)) {
  $message = t('Attempt to create an instance of field @field_name on bundle @bundle that already has an instance of that field.', array('@field_name' => $instance['field_name'], '@bundle' => $instance['bundle']));
  throw new FieldException($message);
}


How to create a views export in XLS format? I have a view that extracts user informations. Now I need to export these results in XLS format. I have tried "views data export", but it is not supported in last Excel versions.

Is there some way that permits me to export data in XLS for the new Excel versions ? Or a good library to use via a custom module ? I'm a senior developer so I have no problem to use PHP and other features.

The Views Data Export PHPExcel should suffice:

  This module extends Views Data Export module to allow XLSX files export.

That format is supported by Office 2007 and up.

Or go with what Brady said in comments and use CSV, it should be just as good.


What does the 'master' option in the attachment view settings stand for? I am using some attachment views to display the latest one of different content types in one view.

I was using the first (block) view as the parent view and was attaching the others to this view. This, in many cases ok. But now I ran into some styling issues, caused by the overly complicated markup.

So I decided to delete the block view, convert all the views to attachments and  of the view attachments, and attach all of them to 'master'. I was hoping this would give me a homogeneous markup.

But now the block disappeared completely. It is not even visible in the blocks admin page.

So my question is, what does the 'master' in the attachment options stand for?

The master display is the default one created automatically for every view. It's not a block, so it won't show up in the list. For views, only their block displays show up in that list.

A quick trick to get access to the Master display: edit the view then without selecting any of the displays append "/default' to the URL and hit return.


Is access control necessary upon form submission if I've controlled access to the page containing the form? Let's say a malicious user has no access to some path (e.g. path/element/1) based on 'access callback' as set in hook_menu() or altered in hook_menu_alter(). What happens if he has access to path/element/2?

Could he simply not change the values that are POSTed in the form submission to the server? I thought they can (even though there are form tokens). If I do several access checks to determine who can view a page, and that page contains a form that can be submitted by anyone who has access to that page, do I need to do those same access checks in the #submit or #validate handler or anything like that? Or can I rely on Drupal's form API security to keep me from having to tediously duplicate all that access code twice for pretty much every custom form!

I know Drupal has some form tokens and whatnot, but doesn't this depend on the developer who output that form (assume a contrib or custom module) setting things up right? I remember a while back I created a custom form and tried changing the POSTed values of one of the elements, and the altered value is what got picked up by Drupal! There was no rejection of the form based on altered values! So clearly I did something wrong there (what might it have been?) - and if I did, then a developer of a contrib module could do the same. So what's the best practice here?

It is not necessary to control if the user has access to a form in its submission handler.

Drupal protects its forms from form forgery, and verifies the values contained in the submitted form. The first control is done in drupal_validate_form(), where the form token (which is automatically assigned to every form built through the form API) is verified; if the value of $form_state['values']['form_token'] is different from the value of drupal_hmac_base64($form['#token'], session_id() . drupal_get_private_key() . drupal_get_hash_salt()), the form is rejected.
The submitted values are also validated in _form_validate(), where the length of the entered value is checked against the maximum length reported for the form field, and the value entered for a "checkboxes," or a "tableselect" form field is checked against its acceptable values. In both the cases, the value used to verify the submitted values is not taken from the submitted values.

To be more sure, you should not pass sensible data, such as the ID of the node being edited as hidden field; it is preferable to set it inside the $form variable, using an array index that starts with "#" and that is unique for that form (such as "#nid"), or use a "value" form field; in that way, the value will not be passed to the HTML form rendered in the browser, and a forged form would not be able to alter that value to effectuate an operation on an entity for which the user doesn't have access. For example, this is the code used for a confirmation form that allows to delete a node:

function node_delete_confirm($form, &$form_state, $node) {
  $form['#node'] = $node;
  // Always provide entity id in the same form key as in the entity edit form.
  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  return confirm_form($form,
    t('Are you sure you want to delete %title?', array('%title' => $node->title)),
    'node/' . $node->nid,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

Both $form['#node'] and $form['nid'] are not contained in the form passed to the browser.

The submission handler for that form builder is the following one:

function node_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    $node = node_load($form_state['values']['nid']);
    node_delete($form_state['values']['nid']);
    watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
    drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));
  }

  $form_state['redirect'] = '<front>';
}

The value of $form passed to the form handlers is not passed to the browser, but it is retrieved in the Drupal cache from drupal_build_form(), which calls form_get_cache() when the form has been submitted. The documentation of drupal_build_form() contains the following sentence:

  The form may also be retrieved from the cache if the form was built in a previous page-load. The form is then passed on for processing, validation and submission if there is proper input.

If you look at Drupal code, you will notice that none of the core modules check if the user has the permission of accessing the form in the form submission; the only code you will find is the code that checks if an error message must be output, in the case that error message should be visible to a group of users that is smaller than the group of users that has access to the form.

As side note, Drupal.org has a security team that investigates on security issues reported for Drupal core code, and any third-party modules hosted on Drupal.org; for third-party modules, they don't investigate on reports for non official releases of the modules (e.g. alpha, beta, and development snapshots). If you find a security issue in Drupal, you should report it in the project queue for Drupal core.


How do I access field variables directly in Drupal 7 without having to drill down into a node array? I have a view reference field and have some php code in the view where it grabs the taxonomy ID of the page its currently on. Currently I am grabbing the TID via

menu_get_object()->field_device_type_vocabulary[und][0][tid];

I know you can access the fields directly without having to do that, but forgot how that was done.

There are two main methods:

Procedural, using field_get_items(), e.g.

$node = menu_get_object();
if ($items = field_get_items('node', $node, 'field_device_type_vocabulary')) {
  $tid = $items[0]['tid'];
}

Objected oriented, using an EntityMetadataWrapper, e.g.

$node = menu_get_object();
$wrapper = entity_metadata_wrapper('node', $node);
$tid = $wrapper->field_device_type_vocabulary[0]->tid->value();


where to find default view code in user relationships module in drupal 7? I have installed user relationship module. Which gives me default views to display the list of friends, received requests and sent requests. I want to show a message to the user about the number of requests he/she has received as we see in facebook. But I am not getting the view's machine name, display name to take a count of requests received as I am not getting which is the view for requests received. Where Can I find it?

Under User Relationship module there will be a folder called user_relationship_views inside that you can find the default view user_relationship_views.views-default.inc file


space character in url is coming up as '%20' one of my clients website (built on D7) has the '%20' sign coming up in url as a result of a space. My only way around till now has been to use'-' instead of a space between the product names. But i cannot have a '-' between every products name. Please advise

A 'non html/non - technical / not sure what plugins we have already installed' person

:|

%20 is a standard replacement for the space character in URLs.

If you're using pathauto for clean urls ( presumably ), it should remove those from the URL, and replace with hyphens.

/admin/config/search/path/settings

  SEPARATOR

  Character used to separate words in titles. This will replace any
  spaces and punctuation characters. Using a space or + character can
  cause unexpected results.

Check that a hyphen "-" character is being used there.

The regular product title can have spaces, but pathauto should replace those with the separator character in the URL.


How to dynamically group content in a views listing I've hit a massive wall in trying to group a list of nodes displayed through a view on my Drupal 7 site. Currently I have a view that lists a group of nodes that are under a specific vocab term. I then use a weight field to make sure they are in the order that I would like. This works just fine.

Here is an example on my site. In this example I have 11 videos bundled together under one taxonomy term.

What I would like to do is now create "chapters" to better organize these. Using the example above I would like to be able to have the following output:

HEADING 1  <-- I want to add headers like this. And then group videos in each header.
 1. Video
 2. Video
 3. Video
HEADING 2
 4. Video
 5. Video
HEADING 3
 6. Video
 7. Video
 8. Video
 9. Video
 10. Video
 11. Video

The big caveat is that I want to be able to assign these "chapter headings" at different spots for each video series that I have. I don't want to have Chapter 1,2,3 in the same position every time.

Here is an example of how I would like to be able to group my individual videos. Take a look at the video list on the left.

One route that I tried was to create a new Vocabulary called "Video Headers" and then create terms for each header that I wanted. I then created a new term reference field in my video content type where I would choose the corresponding "header" term that I wanted. But I am having trouble grouping this in my view. It's just not grouping correctly.

I've looked into the Book Module, but that doesn't seem like the right fit. My gut tells me that it has to come down to using taxonomy terms to group these videos.

UPDATE: Thanks to Jason below I was able to almost get it working. The problem is that all of my videos show up in the view rather then just the videos that are under a term. In order for my lists to work I have to have a contextual filter:

UPDATE #2: Figured it out! With help from Jason below, I also added a contextual filter of "Has Taxonomy: Term ID". That showed only the nodes associated with a term.

So as soon as I add that contextual filter, it ruins my grouping and groups all of the videos that I have together with one header. Somehow that is breaking it.

Try this out.

Add the taxonomy term (or entity) reference field to your output, exclude it from rendering, and configure the format settings to group on this field.

Add a relationship to you view based on the term (or entity) reference field you are using to reference the taxonomy terms. With this relationship, you can now add a sort field using the taxonomy term's weight. When you click to add a sort field, filter the options to taxonomy term using the drop-down select to the right of the search field in the add sort dialog. Once filtered, you will now see the taxonomy term weight.

Adding this to your sort, will allow you to sort the view results based on the node's referenced taxonomy term's weight within the taxonomy vocabulary. You could also sort on the term itself, if your term names will include numbers like, "1. Chapter 1" and "2. Chapter 2", etc.

Jason.


Customizing Output of Views Block I'm trying to figure out how to alter the output of a Views Block. The first image shows the situation that I'm stuck in, which obviously looks horrible, and the bottom two images are of what I would like to see, as well as the likely div plan. This is my first time working on this type of issue, so if someone has an idea of where to go, or if there is a module available for me to work with. I'm just looking for the cleanest way of getting to the output goal. Thanks!

In Style settings you can add a class to your fields.

To achieve your look, move the picture above the title.
Then add css class to your picture field.
Then add the following css code to your theme's .css file .pictureclass { float: left; }

BONUS INFO
In Format Settings, you can add classes to your rows

In css class, you can add a class to your entire view


Multilingual homepage I am currently in the proses of making my first multilingual Drupal site. Using the i18n module I have been able to get separate menus and their respective pages.

My problem is that the content on the home page, with the theme that I'm using is created/edited via a page.tpl.php file. Do I need to duplicate this file and have one for each language? If so how to I go about this?

This is the site: http://www.lac-de-montbel.com/

Thanks in advance.

No, you don't need to duplicate file, just go to /admin/config/regional/translate/translate and search for what you want to translate.

To be able to translate strings or variables from custom page.tpl.php file, all of them in the file need to be translatable, ie. to be in t() function, so if you can't find words that are from some custom .tpl.php file, make sure that particular string or variable in the file is translatable (in form like I mention).

For more information about using function t() look this.


How do I show a product attribute in a cart? I don't know why the item name shows "price" in the shopping cart.

My product variation type have 2 fields: Certificate choice (attribute) and Course period.

How can I customize my formatter in the cart?

The last image is my views "Cart form"

The price must be showing because that is all that is configured to be rendered for the referenced entity in whatever view mode it's defaulting to. If you want something like you've pictured, you're going to need to use the individual fields, which likely means adding another reference to get the attribute / value data, adding all three of the fields you want to render (course name, attribute value, and period), and then configuring the View to ensure all three of those fields are rendered into the single column.


Generate PDF from custom fields, and link from Views page I have a list of records that are presented to end-users in a View. That works fine. What I want to do is generate a printable PDF from custom fields so that users can print out a nicely formatted profile page and hand the printout to someone else. Does anyone know if this is possible?

I know there is a module called Views PDF. I did have it working on a test CiviCRM 4.2 site, but formatting the PDF was somewhat tedious and I have never used it on a live site.


Custom field permissions based on workflow or rule/action Is there a way to trigger permissions to specific fields in a content type based on a workflow or rule/action?

For example, for a content type called 'article':

field 1 is writable, field2 is hidden
workflow state has changed
field 1 is now read-only and visible
field 2 is now visible and writable

I came across this module called Workflow Fields that sounds perfect, but it is only available for Drupal 6.

You can probably do this with Conditional Fields.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.


Is it possible to have all content types as dropdown field in one content type in drupal 7? I have one requirement, where I need to create one content type having field 'Type' and it should have Dropdown list of content type present in that Drupal project.
Is it possible to do it? Can anybody suggest me how can I achieve this?

I can suggest four different solutions:

Using Bundle Name Reference module , of course I haven't used this module and I'm not sure if it presents the same functionality as you desire.
Easy but not always working , Create a taxonomy vocabulary and add terms having same name as your content type does , then you can add a taxonomy reference to your content type targeting that vocab.
The problem in solution 2 is that when a new content type is added you manually must add a term for that in your vocab , to overcome that problem you can write a simple module then implement hook_node_type_insert and there you can add term to your targeting vocab programmatically so you wont need to manually add new terms any more.
The last and the most complicated solution , maybe you can write it as a module so others can use it in future. You will need to write a module to implement a new field type , you will need to implement hook_field_schema to add new table for your field type (there you can store bundle ID of selected content type) , a field widget which must be Select type and its options can be filled using this function : node_type_get_types.


Concatenating translatable strings is not allowed, use placeholders instead and only one string literal The following code:

$report .= '
' . t('%percentage of '.$node_type_get_types[$type]->name.' completed.', array('%percentage' => $percentage)) . ' ' . $count . '
';

is inside of iteration, because I need to make the same calculations and collect all the results and output all in one string.

Drupal.org's automated testing complains about the above part:

Concatenating translatable strings is not allowed, use placeholders instead and only one string literal

I don't have any idea how to make this correct.

It means you have to use a placeholder, in the same way you used the %percentage placeholder.

$report .= '
' . t('%percentage of @content-type completed. %count', array('%percentage' => $percentage, '@content-type' => $node_type_get_types[$type]->name, '%count' => $count)) . '
';

I used a @-placeholder for the content type, in the same way done from node_add().

For a list of the placeholder types used from Drupal, see format_string(). The documentation for t() explain in details why concatenating is not possible in translatable strings.


Field updated date in view I am using Drupal 7 and I have a view displaying the Updated date.
Unfortunately, the Updated date changes every time I save the node, even if no changes are made.

How can I configure the Updated date to be changed only if changes in fields are made??

P.S: I tried with "Rules", setting as action "Set a data value" and Data selector "node:changed", but it shows me this message: "The selected data property doesn't support writing."

The Updated date field is a core property (node.changed) of Drupal nodes, representing when it's database record changed. You'd probably have to do some core hacking to rework this property to change only when fields change.

As an alternative, you might want to consider a module like Track Field Changes which logs when specified fields are changed and provides Views integration.


Cache pages/variables in hook_preprocess() for anonymous user So I am having trouble understanding the caching of variables set in hook_preproccesses for anonymous users. It seems that the entire page is cached, and not rebuilt, even when set to no caching. With the following simplified example I am troubleshooting:

/**
* Implements hook_preprocess_node().
* @param $variables
*/
function hook_preprocess_node(&$variables) {

  $variables['testing_1'] = [
      '#markup' => date('m/d/Y h:i:s a', time()),
      '#cache' => ['max-age' => 0]
  ];

  $variables['testing_2'] = date('m/d/Y h:i:s a', time());
}

then in twig template:

{{ testing_1 }}

{{ testing_2 }}

Both seem to work fine for logged in users, but these variables never seem to update for anonymous users except upon:

Manually clearing cache
Saving content on the node, which then clears node cache.

Even when page caching is set to "no caching" on /admin/config/development/performance, but that does not seem to matter. Its as though the hook_preproccess does not run for anon users once first page hit from anon user happens.

It seems like from Anonymous user cache control and others, this is due to internal page cache module. Uninstalling this DOES solve the problem, but I am unsure that this is the best way to solve this issue, especially since it is enabled by default. Per the docs, internal page cache says "This module assumes pages are identical for all anonymous users". This is true, I simply want the pages to rebuild (rerun the preproccess hook) for ALL anon users when page cache (set on /admin/config/development/performance) clears.

After a day or so of troubleshooting, I am considering simply creating a cron job to flush caches at this point, but there has to be a better way I am missing. What is the best way to ensure that pages rebuild for anonymous users after a set time?

You may have encountered a core bug where a page cache is not respecting the max-age, or in other words, max-age is not bubbling up to the page cache. There's a workaround on the issue summary but the workaround has a few problems of its own so make sure you consider the implications carefully. The bug issue is postponed until 3 of the linked issues are resolved. Hope this helps.


What are the main difference between panels and paragraphs? What are the main difference between the Panels and Paragraphs module in Drupal 8?

As far as I know both of the modules can be used for creating landing pages.

When to use paragraph and when to user panels?

They are not the same and you can't do the same thing with them.

Panels

  The Panels module allows a site administrator to create customized
  layouts for multiple uses.

Paragraphs

  Paragraphs module comes with a new "paragraphs" field type that works
  like Entity Reference's.

With Paragraphs you can create collections of items, like you can do with Field collection, as they are fields that you can attach to your content types, you can't do this with Panels.

In the other hand if you want to modify your layout in a simple and easy way you can use Panels, and if you have a collection of items maybe you have used Paragraphs in the content that you're showing.


File always save with underscore I have a custom form where admin users upload a CSV file. Everything is working fine, but the file is saved with an underscore. For example, I upload callLog4127_Lorem_20170701.csv but the file is saved as callLog4127_Lorem_20170701_1.csv.

I checked the database, but I don't find any reference to callLog4127_Lorem_20170701. I also deleted the temp folder, and ran cron, but I am still getting the same problem.

It happens just with this file; when I upload another file it's working correctly, which means the filename is not changed.

This is my form validation handler. Is there anything wrong with it that could cause the behavior I am seeing?

function upload_rtap_validate($form, &$form_state) {
  $file = file_save_upload('calllogrtap_file', array(
    'file_validate_extensions' => array('csv'), // Validate extensions.
    'public://mrtap/', FILE_EXISTS_REPLACE
  ));

  if ($file) {
    $file = file_move($file, 'public://mrtap/', FILE_EXISTS_REPLACE);
    $file->status = 1;
    file_save($file);
    $form_state['storage']['filename'] = $file->uri;
  }
}

If I print the content of $file with print_r($file), after file_save_upload(), I get the following.

stdClass Object(
  [uid] => 1
  [status] => 0
  [filename] => callLog4127_GentleDental_20170701.csv
  [uri] => temporary://callLog4127_GentleDental_20170701_4.csv
  [filemime] => text/csv
  [filesize] => 48429
  [source] => calllogrtap_file
  [destination] => temporary://callLog4127_GentleDental_20170701_4.csv
  [timestamp] => 1501309335
  [fid] => 235
 )

The main error is that you aren't passing the last two arguments of  file_save_upload() to that function, since you are putting them in the array you pass as second argument. The code you are using is the following one; see the comments I added.

  $file = file_save_upload('calllogrtap_file', array(
    // First line of the array
    'file_validate_extensions' => array('csv'),
    'public://mrtap/', FILE_EXISTS_REPLACE
    // Last line of the array
  ));

As you aren't passing the last two arguments to file_save_upload(), the function is using the default values for those parameters, which are:

$destination = FALSE
$replace = FILE_EXISTS_RENAME

The first values is making Drupal save the uploaded file in temporary://; the second value is telling Drupal to rename the file if there is already a file with that name.

The function call should be the following one.

  $file = file_save_upload('calllogrtap_file', array('file_validate_extensions' => array('csv')), 'public://mrtap/', FILE_EXISTS_REPLACE);

If you change the code in this way, then the following code line is not necessary, since the uploaded file is already moved in public://mrtap/ from the call to file_save_upload().

$file = file_move($file, 'public://mrtap/', FILE_EXISTS_REPLACE);

If filename is the ID of the form element for uploading the file, the following code probably needs to be changed.

$form_state['storage']['filename'] = $file->uri;

Probably, the correct line is the following one.

$form_state['values']['filename'] = $file;

I would also keep the code to validate the user input in upload_rtap_validate(), and the code saving the file as managed file in upload_rtap_submit().
For example, see the code used from the form handlers for system_theme_settings(), system_theme_settings_validate() and system_theme_settings_submit(). (I replaced the comments with mine.)

  // system_theme_settings_validate()
  $file = file_save_upload('logo_upload', $validators);
  if (isset($file)) {
    // The user upload the logo file.
    if ($file) {
      // The uploaded file passed the validation in $validators.
      $form_state['values']['logo_upload'] = $file;
    }
    else {
      // The file upload failed.
      form_set_error('logo_upload', t('The logo could not be uploaded.'));
    }
  }

  // system_theme_settings_submit()
  // If the user uploaded a new logo, save it to a permanent location.
  if (!empty($values['logo_upload'])) {
    $file = $values['logo_upload'];
    unset($values['logo_upload']);
    $filename = file_unmanaged_copy($file->uri);
    $values['default_logo'] = 0;
    $values['logo_path'] = $filename;
    $values['toggle_logo'] = 1;
  }

In your case, you could use file_copy() instead of file_unmanaged_copy(), or file_save() as your code is doing.


Trying to get a localhost copy working I've transferred all of the files for a Drupal build to my localhost, imported the database into my local WAMP server, however when I try to access the drupal build on my localhost, it keeps giving me an error, saying it cannot connect (connection reset). Other sites on localhost work fine.

What would cause this?

The connection details are the following ones:

array('database' => 'default_drupal',
  'username' => 'default_drupal',
  'password' => '1r3s3tM3',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
);

I created an account using the account default_drupal on the default_drupal database, so it should work.

Are you using any Drupal performance optimizations on the site that's the source of your imported database? This article suggests turning them off and gives a query to accomplish that.

Once you've got your local site up and running, I also suggest trying the Backup and Migrate module to manage your data migration. You can create a backup profile that omits your live server's cache data, which makes for a smaller backup file and may mitigate the problem you're having now.


How to set a menu item active ? I have a site that has a lot of menus. One of them is the main menu that has few items. These items link to main areas of the site, and each of these main areas has one specific menu. When I'm on a landing page of one of these main areas, the item of it on the main menu is active, but when I'm on an internal page of one of these areas, the item on the main menu is not active.

Is there any way to make it active automatically?

I tried using menu_position but it seems not be working.

Their is a lot of ways. I list here only things compatible with D7 and eventually on D6.

Use a modules

https://drupal.org/project/menu_position (need rules, watch http://vimeo.com/27074705)
https://drupal.org/project/menu_trail_by_path
https://drupal.org/project/context

Code your stuff

Their is now a native API menu_tree_set_path to set the path you want to use to calculate the menu active trail.

You can also work in theme_links but but I recommend to use menu_tree_set_path so other module know what is your active link. The advantage is you can use this function in your theme without creating a module.

Keep in mind, menu_position has an API to create your custom rules.

So what should I use???

It's depend of your need. if you have simple rules like: for this node type/views/taxonomy i want this active menu, context is good.

If you have a good url structure (autopath) than follow your menu structure, menu_trail_by_path will just works without any effort.

I never used menu_position... so I can very tell.

If you need some special logic, coding your things is certainly faster than creating 40 context or rules...


How do I display the date but not the author? I want articles to show Submitted on without showing Submitted by. The checkbox on Display settings toggles both, not only one of them.
Control/modify display settings (author and date) on posts explains how to do it in Drupal 7.

How should I achieve it in Drupal 8, for example with the Bartik theme?

It's enough to edit the node.html.twig template used from the theme. For example, the Bartik theme uses a node.html.twig template containing the following code. (I omitted the documentation comment at the beginning of the file.)

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'clearfix',
  ]
%}
{{ attach_library('bartik/classy.node') }}

    {{ title_prefix }}
      {% if label and not page %}

        {{ label }}

    {% endif %}
    {{ title_suffix }}
    {% if display_submitted %}

        {{ author_picture }}

          {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

        {{ metadata }}

    {% endif %}

    {{ content }}

The line printing the name of the user who created the node and when it was posted is the following one.

{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

It's enough to change it and remove the part printing the username. In the case of the Bartik theme, the node.html.twig content will become the following one.

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'clearfix',
  ]
%}
{{ attach_library('bartik/classy.node') }}

    {{ title_prefix }}
      {% if label and not page %}

        {{ label }}

    {% endif %}
    {{ title_suffix }}
    {% if display_submitted %}

        {{ author_picture }}

          {% trans %}Submitted on {{ date }}{% endtrans %}

        {{ metadata }}

    {% endif %}

    {{ content }}

For a different theme, it's enough searching the line of the node.html.twig template containing {{ author_name }} and remove it. Clearly, also the sentence containing {{ author_name }} needs to be changed to make it grammatical. (Submitted by on {{ date }} would not be grammatically correct.)

As general suggestion, never change a template file used from a Drupal core theme or a third-party theme. Rather, create a sub-theme using that theme as parent theme, and add the template files you need to change.


Altering User Registration Message I need to take control over and change the flash notification a user gets when they register, but administrator approval is required.

I want to alter this...
"Thank you for applying for an account. Your account is currently pending approval by the site administrator. In the meantime, a welcome message with further instructions has been sent to your email address"

https://api.drupal.org/api/drupal/core%21modules%21user%21src%21RegisterForm.php/function/RegisterForm%3A%3Asave/8.2.x

It states...
'Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.'

I'm trying to figure out what the Drupal 8 way of doing this is.
Should I be trying to "alter" the message with a hook?
Should I be overriding a service? (though from my understanding this
is not service).
Should I be extending this?
Or is there some other best practice way of overriding this?

I'm learning Drupal 8. So I'm not entirely sure the "right" way to handle this particular case.

Brandon's answer is good for altering the email messages.

If you are looking to alter the status message that pops up afterwards, I found this answer helpful: https://stackoverflow.com/a/38797543/963866


Is there a Drupal tool to aggregate and compress CSS files I know that Drupal 7 has settings for Aggregate and compress CSS files and Aggregate Jacascript files (under Administration/Configuration/Development/Performance).

Is there a tool that let me extract the result of this process?

I am using Sass and Compass, so I guess that to produce an aggregate and compressed .css, I could set output_style = :compressed in Compass and the just concatenate together all the separate .css files, but that won't resolve conflicts or combine overlapping CSS selectors.

I wonder if there are some better way to do this, for instance making use of the Drupal built-in tool that apperently is designed specifically for the job.

This is for a Zen sub-theme.  The Zen STARTERKIT produces a lot of CSS-files, and before making this sub-theme generally available, I would like to "clean up" the distribution by consolidating CSS and Javascript into two aggregate and compact files.

(Outside the Drupal universe, YUI compressor seems to be the most popular tool for this.)

I'm not 100% sure I'm right in thinking this, but if you're looking for something to reverse the CSS aggregation/compression, but if you are then it doesn't look like there is anything that exists that will give you exactly what was initially compressed. However, the cache Drupal creates is an array that is keyed by the original filename of the cached CSS, so you should be able to find out WHICH CSS files are being cached relatively easily (I think the variable_get('drupal_css_cache_files'); will get the array for you.

If you are looking to mimic what Drupal does when it aggregates and caches your CSS, then take a look at the drupal_build_css_cache() function (which, as an FYI, is called by drupal_aggregate_css()).

As a point of interest, there is also a drupal_build_js_cache as you'd expect.


Drupal features recreate issue with CCK fields I have created a form using CCK with conditional fields. If I use the features module to recreate and export the new settings to my staging machine the form comes out flat.

So for example my form is set up to expand other options based on a selection (second option on a drop down box will show different form fields).

After re-creating and sending the files over to staging, same deployment, version and all that for some reason the CCK form appears flat. All the fields that are supposed to be hidden behind certain field selections now appear flat.

So the files that I might have transferred for example after downloading the feature:

support_tickets_v2.features.conditional_fields.inc
support_tickets_v2.features.content.inc
support_tickets_v2.features.fieldgroup.inc
support_tickets_v2.info
support_tickets_v2.strongarm.inc
support_tickets_v2.views_default.inc

I faced the same issue today. After a lot of searching, I found the following patch.
https://www.drupal.org/node/2210241

I was able to solve this using the patch provided.
Can export the conditional field settings (along with content-type & fields) in a feature.
In my case the dependent is a Date field & dependee is a boolean field.

Conditional field 7.x-3.0-alpha1
features 7.x-2.2


Display all Nodes associated to a Taxonomy term? I currently have a list of Taxonomy terms: Fruit, Meat, Vegetables..etc. And I would like to add a drop down to a content type that will display all nodes and only the nodes that are associated to a Taxonomy Term. I am currently using the Node Reference- Select List, but the list is growing and will eventually become unmanageable.

To Summarize:
In example, I select a Taxonomy term and then a "select list" displays only nodes that have been previously associated to that same Taxonomy term. I select Fruit and it displays oranges, apples, and lemon nodes only. Not... lemons, oranges, carrots, ribeyes...etc, in which, is my ever growing Node reference list now.

Thank you for any help you may lend.

You could accomplish this by writing code (in a custom module) to ajaxify the relevant select fields. Check out the Examples module (ajax examples -> dependent dropdown) for implementation help. Here's what needs to be done roughly:

Use hook_form_alter or hook_form_FORM_ID_alter to add necessary #ajax options (callback and wrapper at minimum) to the taxonomy select field. The node reference field needs a wrapper (via #prefix, #suffix) and #options changed when a term has been selected (value set in $form_state['values']).
A function for the ajax callback returning the node reference form field.
Custom functionality checking which nodes are associated with the selected term to set the right options for node reference. Easiest way might be by querying them directly from the taxonomy_index database table (if you need other data (like type) include the node table as well).


In Views, how can I show a blank end date if no value is entered? A date field in views allows you to show a start date and/or an end date. If the end date is optional, and not filled out by the user, views doesn't show a blank field if it is empty-it's show the start date for some reason.

This issue is similar to How can I rewrite a date field "End Date" to be "present" if no value is entered?

I have tried messing around with the code in the above issue to meet my needs but it's not working.

I have views php installed and I need to add php code to show the field label and date but leave the date portion as blank, if empty. e.g. End Date: 2017-09-20 or if empty End Date:

These are my available variables

$row->field_start_date: Content: Position start/end date (Set to display only start date)

$row->field_start_date_1: Content: Position start/end date (Set to display only end date)

To answer my own question:

I used the Views Conditional module and set it up as follows:


How to prevent multiple votes in polls of the rate module? I have installed the rate module, and set the emotion widget. I like this module but  after I vote successfully, I can click the vote button again. Instead I want to popup a window which says" you have voted. don't vote again", to prevent people from voting multiple times.

The rate module hasn't built support for this. If you wanted to do this, your best option would be to

Deny duplicate votes, it's up to you to decide how, but you could check the voting api table which stores the IP addresses of all who have voted then use rate_vote_alter hook. Doing it this way would make it impossible to change the vote.
The other option is to use rate_vote_alter to stop the rate module from saving votes and do it yourself with votingapi_set_votes. That would make it possible to set criterias for which (old) votes should be deleted.

This could have been done easier if the rate module was built more flexible. You could consider making an issue and a patch for the rate module, to add this feature for others to use.

Update:
The alter hook is not defined anywhere, but done with drupal_alter('rate_vote', $votes, $context). This means you should be able to do:

function my_module_rate_vote_alter(&$votes, $context) {
  ..
}