How to link a title from one view to a page of another view I created a content type x.

I added 4 contents.

My contents look like this.

I created a views page. (xxx.com/mypage),

I created a views block placed in sidebar. (displayed sidebar of xxx.com/mypage),

This is how the page looks like,

Each time I click a title in sidebar, I like the corresponding views page to be displayed. Currently, title takes me to orginal content. Thats not what I want.

Example: If I click Chapter1 Title1, I like to see chapter1 title1 body page, If I click Chapter2 Title1, I like to see chapter2 title1 body page.

I think I need to use contextual filter and I am not sure how I can do that to make it happen.

Please advise.

You are correct.  You can use contextual filters to achieve this.  There are two parts to the solution.

The first is the views page, which you labeled xxx.com/mypage.  You will need to add a contextual filter using Content:NID.  You would then change your views page's path to uft/%.  Then, for instance, navigating to xxx.com/uft/2 in your browser would result in accessing your views page with only the information for node 2 shown.

The other half of the solution is in the block.  You will first need to add one more field to your block's fields, NID. Make sure to check the 'Exclude from display' checkbox while adding it. Once you've added NID, you'll need to rearrange the fields so NID is above title. Now you are ready to change what the Titles in your block link to.  When you click Content:Title under the Fields section you will first want to uncheck 'Link this field to the original piece of content'. Next, you should see a collapsed fieldset titled 'Rewrite Results'.  Click that to expand it. In the text box, entering uft/[nid] should complete the process.

At this point, your views block should be generating xxx.com/uft/target_nid as the link targets for the titles in the block and when you click them you should arrive at your views page with the selected nid passed as a contextual filter argument.


Adding indexed field to Search API query in code I want to add an indexed field to a Search API query in code. My query currently looks like this:

$index = search_api_index_load("default_node_index");
$query=new SearchApiQuery($index);
$query->condition('type', 'answers_question', '=');
$filter = $query->createFilter('OR');
$filter->condition('title', $text, '=');
$filter->condition('body:value', $text, '=');
$query->sort('search_api_relevance', DESC);
$query->fields(array('title'));
$query->filter($filter);
$query->keys($text);
$data=$query->execute();

This returns the correct results, however the result set is composed of an array of arrays with an 'id' and a 'score'. I want the indexed node title to be returned as well. I cannot do a join to the node table as ->join is not available on SearchApiQuery.

The statement:

$query->fields(array('title'));

does not seem to do anything.

I have this same query set up in a view where it is working properly. When I inspect the query at hook_search_api_query_alter I cannot see where or how the title is added.

How do I add the indexed title as a field to be returned in the result set?

$query->fields(array('title'));

Doesn't do what you think it does/should, this tells Search API that this is one of your fulltext fields that you want querying against the string you passed to keys()

$query->keys($text);

What backend are you using for Search API, in my experience Solr returns all indexed non empty fields. Make sure the Title is indexed so that it is available to your Search API's backend.


How to use loadByProperties when one of the properties is an array? I have this configuration entity and I want to load an entity using the properties label and subregions

Lets say I want to load the entity if it has the label CU and the subregions CU-04. Note that subregions is an array. I tried with this code but is not working.
$region = $this->entityTypeManager->getStorage('region')->loadByProperties(['label' => $region, 'subregions' => $subregion]);

How can I call loadbyProperties with properties being arrays?

Configuration entities are not queried via SQL, you search within a multilevel array.
See the code docs:
core/lib/Drupal/Core/Config/Entity/Query/Query.php
  /**
   * Overrides \Drupal\Core\Entity\Query\QueryBase::condition().
   *
   * Additional to the syntax defined in the QueryInterface you can use
   * placeholders (*) to match all keys of an subarray. Let's take the follow
   * yaml file as example:
   * @code
   *  level1:
   *    level2a:
   *      level3: 1
   *    level2b:
   *      level3: 2
   * @endcode
   * Then you can filter out via $query->condition('level1.*.level3', 1).
   */
  public function condition($property, $value = NULL, $operator = NULL, $langcode = NULL) {
    return parent::condition($property, $value, $operator, $langcode);
  }

In your case the second level keys are the same as the values. So you have to ignore the second level with an * to query these values.


Render a menu block in current user's language I have a multi-language site.

How this is supposed to work is that on /fr pages, everything except main navigation block should be in French. However, main navigation menu block should be in whatever currently logged user's language.

I tried to change language code in custom module using block or menu hook, but none of them worked.

Thanks in advance.

You don't need a custom module for this.

Drupal can have seperate language detection for interface (menu item/interface elements) and content.  There was a bug that was fixed recently so make sure you are on the latest 8.6.x version.

Assuming you have enabled all 4 core language modules and you have enabled at least 1 extra language than configure the language detection methods to accomplish what you want as I its outlined below.

Go to Configuration > Regional and language > Languages > Detection and selection and

enable Account administration pages. This will allow each user to choose their preferred interface language (there will be a new option when they edit their profile page)

enable content language detection. This will make available the language switcher (content)) block.
enable 1 detection method.  In my case I choose url (i.e. /en /fr) but you can choose any other or more methods if you like.

ΝΟΤΕ: The detection methods take precedence as they appear from top to bottom provided they are also enabled.

Go to Structure > Block layout and enable language switcher (content) (not language switcher (interface text)

Now lets say a user has chosen English as their interface language they can press on the language switcher (content) and their interface (menu, admin menu etc) will always  stay English.


Can't migrate alias with Wordpress Migration I am using the Wordpress Module to migrate from Wordpress to Drupal 8. I am trying to have the alias be set to the link value (<link>https://myurl.com/wordpress-path</link>). I added the following to the source:

    -
      name: link
      label: 'The link value'
      selector: 'link'

and the following to process:

  path/pathauto:
    plugin: default_value
    default_value: 0
  alias:
    -
      plugin: get
      source: link
    -
      plugin: str_replace
      source: link
      search: 'https://myurl.com/'
      replace: '/'

I have also tried path/alias and path instead of alias but no luck.  I verified that the str_replace plugin does return the correct value but somehow it does not save in the node.

Here is my full migrate_plus.migration.my_wordpress_wordpress_content_post.yml:

uuid: 5b3b3b84-8d41-4a80-b1ca-c9046c269297
langcode: en
status: true
dependencies: {  }
id: wp_wordpress_wordpress_content_page
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - WordPress
migration_group: wp_wordpress
label: 'Import content from WordPress XML'
source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  item_selector: '/rss/channel/item[wp:post_type="page"]'
  fields:
    -
      name: title
      label: 'Content title'
      selector: title
    -
      name: post_id
      label: 'Unique content ID'
      selector: 'wp:post_id'
    -
      name: content
      label: 'Body of the content'
      selector: 'content:encoded'
    -
      name: excerpt
      label: 'Excerpt of the content'
      selector: 'excerpt:encoded'
    -
      name: pubDate
      label: 'Publish date of the content'
      selector: pubDate
    -
      name: post_date
      label: 'Post date of the content'
      selector: 'wp:post_date'
    -
      name: status
      label: 'Published status of the content'
      selector: 'wp:status'
    -
      name: creator
      label: 'Username of the content creator'
      selector: 'dc:creator'
    -
      name: post_tag
      label: 'Tags assigned to the content item'
      selector: 'category[@domain="post_tag"]/@nicename'
    -
      name: category
      label: 'Categories assigned to the content item'
      selector: 'category[@domain="category"]/@nicename'
    -
      name: link
      label: 'The link value'
      selector: 'link'
  ids:
    post_id:
      type: integer
process:
  title:
    -
      plugin: get
      source: title
  body/value:
    -
      plugin: get
      source: content
  body/summary:
    -
      plugin: get
      source: excerpt
  created:
    -
      plugin: callback
      source: post_date
      callable: strtotime
  changed:
    -
      plugin: get
      source: '@created'
  status:
    -
      plugin: static_map
      source: status
      default_value: 0
      map:
        publish: 1
  uid:
    plugin: migration
    migration: wp_wordpress_wordpress_authors
    source: creator
  body/format:
    plugin: default_value
    default_value: basic_html
  type:
    plugin: default_value
    default_value: page
  path/pathauto:
    plugin: default_value
    default_value: 0
  alias:
    -
      plugin: get
      source: link
    -
      plugin: str_replace
      source: link
      search: 'https://myurl.com/'
      replace: '/'
destination:
  plugin: 'entity:node'
migration_dependencies:
  required:
    - wp_wordpress_wordpress_authors

Turns out path/alias worked. I must have been doing something wrong or my page was cached that it wasn't redirecting to the alias.

path/alias:
  -
    plugin: get
    source: link
  -
    plugin: str_replace
    source: link
    search: 'https://myurl.com/'
    replace: '/'


Various "Undefined" notices on content admin screen I get these sporadically on the content admin screens.  These seem to be referencing fields that I do have in my templates, that are working just fine for those actual screens.  I just don't get why this content admin screen would be looking for those values.

Here are the error messages:

•   Notice: Undefined property: stdClass::$field_pcast_fname in include() (line 64 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/node.tpl.php).
•   Notice: Undefined variable: messages in include() (line 13 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/comment-wrapper.tpl.php).
•   Notice: Undefined index: field_twithandle in include() (line 14 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).
•   Notice: Undefined variable: field_headshot in include() (line 24 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).
•   Notice: Undefined offset: 1 in include() (line 94 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).
•   Notice: Trying to get property of non-object in include() (line 94 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).

And for example, the field_twithandle code that's in my user-profile.tpl.php:

<?php if($user_profile['field_twithandle']) { ?>

        <a href="http://twitter.com/<?php print $field_twithandle[0]['value']; ?>" class="twitter-follow-button" data-show-count="false" data-show-screen-name="false">Follow @<?php print $field_twithandle[0]['value']; ?>

<?php  } ?>

Try this, check to make sure it's set first:

<?php if (isset($field_twithandle[0]['value'])): ?>
<a href="http://twitter.com/<?php print $field_twithandle[0]['value']; ?>" class="twitter-follow-button" data-show-count="false" data-show-screen-name="false">Follow @<?php print $field_twithandle[0]['value']; ?>
<?php endif; ?>

The problem is that those values aren't set on some pages, which is why you're getting the error. So that's a fix for an undefined index error. You also have things like undefined variable, for which a fix could be like:

<?php if (isset($messages)): ?>
  /* Do stuff here with $messages */
<?php endif; ?>


How does "cache dates" work? Having a hard time finding documentation explaining in any depth how date caching works in Drupal 7. Adding a date field to a content type allows a checkbox option that says "Cache dates: Date objects can be created and cached as date fields are loaded, rather than when they are displayed, to improve performance." In what scenarios is it a good idea to select this option? How does it improve performance?

Found this 5 year old comment in the issue thread that gives some more context. Not sure why the enhanced help text didn't make it into the 7.x module, but it helped me make the decision. https://www.drupal.org/project/date/issues/1358790#comment-6327490

  In order to display a date, a date object is created. Creating and caching date objects at the time date field data is entered may improve performance. For single-value, non-repeating, date fields caching will be neutral or have a performance benefit. For multiple-value or repeating dates with a large number of values, caching may negatively impact performance as some date objects that are cached may never actually be required.


Same menu display only a couple of levels down when used normally but when used within the "Site map" module it would display all the levels? In order to display all the links using the "Site map" module I am adding everything we want in our site map to the primary links menu, going in as many levels deep as I need. Then I don't actually display all the levels in our menu but the site map will display all the links within the primary links menu.
Is there a way to have the same menu display only say a couple of levels down when used normally but when used within the "Site map" module it would display all the levels?

You can install the Menu Block module to help with that.

You can define a define a block for a specific menu, and in the block configuration you can choose the maximum depth (see the active select list in the image below). Then you can add that block to your header/whatever region in place of the menu that's there now.

This won't affect the underlying menu itself though, just the display of it for that particular block. So in the sitemap, all levels of links will show.

Obviously you may need to make a few CSS tweaks to your menu as the wrapping classes will probably have changed, but I think this is by far the quickest method to get what you're looking for.


Why user_save overrides user picture? I have a user profile form. If a user selects a picture, it's uploaded and shows on user profile but If user just updates other details and leaves the picture the same the user_save overrides the user picture and then there is no user picture.
My code is like this.

if(!empty($_FILES['files']['name']['profile_image']) && isset($_FILES['files']['name']['profile_image']) && ($_FILES['files']['size']['profile_image'] != 0)) {

        $filepath = 'public://pictures/';
        $file = file_save_upload('profile_image', $validators, $filepath);
        $file->status = 1;
        file_save($file);
        if(isset($file) && !empty($file) && !is_null($file)) {
            $loaded_user->picture = $file;
        }

    }
user_save

I assume you are not setting you default_value for the file field and that you are using a managed_file field.

The default value should be the fid of the file that has been uploaded before.

Something like this:

$form['profile_image'] = array(
  '#title' => t('Profile picture'),
  '#type' => 'managed_file',
  '#description' => t('Upload a photo for your profile.'),
  '#default_value' => $previously_uploaded_file->fid,
);

In your case I'm not exactly sure where the $previously_uploaded_file->fid will come from, but I assume it will be in your form or form state or else you will have to get it from the database or something.

If you are using a regular file field instead of a managed_file file field I don't believe you can set a default value.

In that case you have to make sure that when you do the user save that you are not overwriting the file with an empty value.


How do i specify a style for a single exposed filter? I have a View where i show some exposed filters; i would like to apply a particular CSS class only to a specific exposed filter.
I have seen that if i copy the views-exposed-form.tpl.php inside my theme directory and call it views-exposed-form--MYFORMNAME.tpl.php i can control the html code; i don't think it s a good thing to put code with

 if($widget->id==MYID) {}

inside the template ... which is the correct way to assign a style to an exposed filter?

Not sure if you need the template for other reasons, but you can style it directly with CSS, using the ID.  See screenshot.  I happen to be using Better Exposed Filters module, which provides some nice extras controls.


Maintain in-house repository of custom modules? Whenever a contributed module has a new version, Drupal's update manager will show a notification and allow automatic downloading of the updates. After that, the user is guided through "update.php". Is it possible to get the same automatic treatment for custom modules?

If I develop a few custom modules for a specific site, it would be interesting to get Drupal to look for updates of said custom modules, on a server specified by me, where I'm hosting the modules myself, and treat them like any contributed module. But maybe this goes against good practices?

maybe this goes against good practices?

Wouldn't have thought so, providing a central repo for your modules can only be a good thing in my opinion. It's the best way to keep multiple sites up-to-date with changes to custom modules.

What you need is a combination of the Feature Server module:

  This module allows you to share features and custom modules on your own website. It lets you create projects and releases, and it produces an update XML feed compatible with the update module in core. In a way it's a highly simplified version of the project module.

And the project status url module .info file setting, for your custom modules:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.


How to remove the default cache tags on a block? Here's what I'm noticing:

I set the cache array to what I want it to be in my block
It propagates up to BlockViewBuilder.php and gets put into the $build's content array
There is still a #cache array on the $build itself, which by default has three contexts:
array('languages:language_interface', 'theme', 'user.permissions')

I want to get rid of the languages and user.permissions contexts for my block, because they shouldn't affect its content and I don't want the two contexts to have inconsistent data, but setting my block's contexts won't affect the ones set by the top level $build object.  Is there a way for me to do that?

It looks like CacheableMetadata::createFromRenderArray() will try to merge the two #cache arrays, but from the way it's doing it, it seems it will grab unique values from the two arrays.  Is there a place where I can remove the bad contexts?

Nope, you can't really opt out of those.

They are defined as required cache contexts in services.yml. So even if you'd manage to remove them, they are added in Renderer.php.

You could change that globally, but you have to be aware of the risks as it is likely that not every contrib/custom code is adding the user.permissions cache context when required, so we decided to make that a default so that at least that kind of cache/acess separation is enforced.


How to add a static image to theme? I'm very amateur in theming. Using Basic theme for Drupal 6, I try to add an image to the very top of the page. (Something like repeating flags here)
However, when I add

<img src="images/flags.png"/>

to the upper side of page.tpl.php, the image has proper permissions but does not show up. No surprise though since the image is hyperlinked as

http:// 127.0.0.1/drupal6/content/images/flags.png

I have also tried defining a  div class="flags" at the top of page.tpl.php and then introduce the image as the div's background-image url('images/flags.png'). No success either.

Direct insertion of static images used to work on my other theme. So got really perplexed and appreciate your help.

Put all your theme images in a directory in your theme; let's call it img.

Then you can load them like so:

<img src="<?php echo drupal_get_path('theme', 'THEME_NAME'); ?>/img/flags.png">

Hope this helps.

(More info at drupal_get_path();)


Render multiple values of a field in Drupal 7 I created a custom content type with a field with multiple values which I want to render as follows in my node--custom_content.tpl.php;

<div class="CLASS" style="background: url('<?php print file_create_url($node->field_creation_images['und'][0]['uri']);; ?>')">

However, this renders only the first value of the field. Is there a foreach solution to my problem?

For multivalue field it makes the field value array like :

// $node->field_creation_images['und'][0]['uri'];
// $node->field_creation_images['und'][1]['uri'];

So to print all values you need to use foreach :

<?php foreach ($node->field_creation_images['und'] as $uri) { ?>
  <div class="CLASS" style="background: url('<?php print file_create_url($uri['uri']); ?>')">

<?php } ?>


Reply form not showing for ajax_comment module installed for Open social distribution recently I've installed Open Social Distribution and installed the ajax_comment module to enable ajax comments and reply but unfortunately the reply link never appear at the home page that shows all posts
here is a screenshot of a post showing in home page:

Make Sure that connected user has Post comments Permission Or anonymous has it.


Add Additional Logic To Node Save/Submit Process Where can I hook into drupal to modify the value of a specific field just before it is inserted into the database?

For example, lets say I wanted to trigger an email or run an arbitrary piece of code just before the node is inserted into the database?

I've been looking at hook_node_presave and it looks like it will do what I want, but I need it to only apply to one content type.

You can probably use either hook_entity_presave(), hook_node_presave() hook_field_attach_presave(). These hooks are all pretty similar right now. Actually not sure why there are 3 of them :)

Simply add a check for the content type and/or the existense of the field you want to alter.


Drupal 7 - Autoslave Master/Slave Failover Issue I am using Autoslave (https://drupal.org/project/autoslave) project for implementing mysql high performance and failover. I have successfully setup the mysql master/slave replication at the server and it is working perfectly. With the following settings taken from Autoslave documentation (https://drupal.org/node/1952990) for Master/Slave, I am trying to implement the following use cases:

If Master is up and slave is down, master should entertain all the traffic (working fine)
If Master is down and slave is up, slave should entertain all traffic in readonly mode (NOT WORKING).

With 2, what happens is as soon as the master db is down, the requests to slave also stops. The following are the contents of autoslave-invalidation-default.inc file after i take master db down:

<?php
$databases["default"]["slave"][0]["status"] = FALSE;
$databases["default"]["master"][0]["status"] = FALSE;

Its showing that both servers are down, where as slave is up and running. I tried with manually changing this file and changing slave status to TRUE, and the traffic is then successfully routed to slave.

Following are the relative contents of my settings.php file:

$databases['default']['master'] = array (
  'database' => 'dbname',
  'username' => 'username',
  'password' => 'password',
  'host' => 'master.ip',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
);

$databases['default']['slave'][] = array (
  'database' => 'database',
  'username' => 'username',
  'password' => 'password',
  'host' => 'slave.ip',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
  'readonly' => TRUE
);

$databases['default']['default'] = array (
  'driver' => 'autoslave',
  'master' => array('master', 'slave'),
  'slave' => array('slave', 'master'),
  'invalidation path' => 'sites/default/files',
  'flag all tables' => TRUE
);

Following is the error shown:

Error
The website encountered an unexpected error. Please try again later.

Error message

The system is currently in read-only mode. Any changes you make will not be saved!
Warning: mt_rand(): max(0) is smaller than min(1) in DatabaseConnection_autoslave->rand_weighted() (line 1233 of /includes/database/autoslave/database.inc).
Warning: mt_rand(): max(0) is smaller than min(1) in DatabaseConnection_autoslave->rand_weighted() (line 1233 of /includes/database/autoslave/database.inc).
Exception: No master connection has been chosen in DatabaseConnection_autoslave->determineMasterTarget() (line 703 of /includes/database/autoslave/database.inc).

Kindly guide me of the any solutions/suggestions and/or possible reasons why is point 2 not working, where it's suppose to.

Thanks.

For read-only mode to work properly you must apply the patch from https://drupal.org/node/1889328 (currently committed to 8.x but not backported yet).

The patch https://drupal.org/files/1889328-1-query-options_1.patch will work for 7.x, though it has not yet been cleaned up according to review comments.

I'm not sure I've mentioned this in the documentation, but you must ensure that you use a read-only user for the slave connection when utilising the read-only functionality. Otherwise you may end up writing to the slave-db which could cause inconsistencies and consequently the replication to fail.

The mt_rand() is possibly due to the result of no connections being available (both servers have status = FALSE in the invalidation file). Servers are only re-validated during cron. If you take down the slave to test that scenario, and then spin up the slave again and take down the master without running cron in between, you may end up with the kind of invalidation file you posted.


How do I define a computed field equal to the concatenation of two fields of my custom entity? I have a custom entity (Person) with these fields: ID, nom, prenom, telephoneportable, estactive, userID, created, changed. I created it with baseFieldDefinitions.

I want to have a computed field nomprenom = nom ." ".prenom
Here is the corresponding code:

$fields['nomprenom'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Nom et Prénom'))
  ->setComputed(TRUE)
  ->setClass('\Drupal\association\NomPrenom');

The code of class 'NomPrenom' is here:

/**
 * @file
 * Contains \Drupal\association\NomPrenom.
 */

namespace Drupal\association;

use Drupal\Component\Utility\String;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\Core\TypedData\TypedData;

/**
 * A computed property for defining 'Nom Prénom'.
 */
class NomPrenom extends TypedData {

  /**
   * Cached processed value.
   *
   * @var string|null
   */
  protected $processed = NULL;

  /**
   * Implements \Drupal\Core\TypedData\TypedDataInterface::getValue().
   */
  public function getValue($langcode = NULL) {
    if ($this->processed !== NULL) {
      return $this->processed;
    }

    $this->processed = $this->get('nom')->value ." ". $this->get('prenom')->value;
    return $this->processed;
  }

  /**
   * Implements \Drupal\Core\TypedData\TypedDataInterface::setValue().
   */
  public function setValue($value, $notify = TRUE) {
    $this->processed = $value;

    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

}

When I try to add a new Person, I get a PHP Fatal error:

  Call to undefined method Drupal\association\NomPrenom::setLangcode()

Why?

I found this in ContentEntityBase.php 499 (but you could show us the whole error log):

I think the case is the following: your field is translatable (you didn't set it's not, and I tihnk the default is TRUE).

else {
  $field_langcode = $langcode;
}
**$field->setLangcode($field_langcode);**
$this->fields[$name][$langcode] = $field;

What I don't understand here: how basefield definition allows you to add a class which doesn't inherit / implements the right class / interface. I think it's a core bug?

You should either:
- add set language method, with a languagecode property
- set your computed field untranslatable


How to get the content of a node with Devel Path? I am quite new to Drupal an would like to get the Data of a Node. With the Devel module I read out the Path to the information I like get with PHP.

$var->location['postal_code']

How can I access this path? I would like to get this info an pass to Javascript. So I think I have to access this path with PHP and then use drupal_add_js to pass it to JS. But I don`t even know where to put the PHP code.

Any suggestion?

If your main goal is to expose a piece of data to JavaScript, you can use drupal_add_js() to add a "setting". Here is the example from api.drupal.org:

drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

(https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x)

That then becomes available in the frontend in the Javascript variable: Drupal.settings.myModule.key.

Now, the question is WHERE do you put that call to drupal_add_js? That depends on exactly what data you want to expose, and when you want to expose it, but in general you would create a custom module and implement a Drupal hook that runs drupal_add_js at a specific point in the Drupal pageload life cycle.

If, as it sounds from your question, you want to add node information to a node's "view" page (ie: on the /node/1 path), one option is to implement hook_node_view() in a module called mymodule like so:

/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {

  // If the node contains the field we want, add it to a JS setting.
  if (!empty($node->location['postal_code'])) {
    drupal_add_js(array('mymodule' => array('postal_code' => $node->location['postal_code'])), 'setting');
  }
}

Here is the documentation for that hook: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7.x

That's just one way to do it. There are lots of other hooks where this could be done, again: depending on when and where you want it to.


Tracking the fields in view How to track the content fields changes in view, just like history review.

When we click on that particular field of content, my aim is some how to track the field of content type have gone through field track changes module. But its of no luck.

Using the track_field_changes module, I was able to get the side by side values in a view. Note , I also have revisions turned on for this node type.


Textfield default value to user email NOT WEBFORM I am using the Drupal 6 Form API to build a custom form. I am not using the Webform module or CCK. How do I assign the user's email as a default value for a form element?

I know about #default_value => but I do not know what to assign to this.

In your form function, you can add global $user; at the top. Then in your #default_value you can use $user->mail.


Prevent access to or redirect /user page I'm looking to redirect or prevent access for authenticated users to the /user page. The reason being that it serves no purpose being there so would like to either remove or redirect it.

The best I've managed so far is to redirect the user on login so they don't get dropped on the /user page straight after logging in which works great but I'd like to prevent all access to it. The code I've used for the redirect is below:

function mymodule_user_login($account) {
  // Redirect users on login
  $link = Link::createFromRoute(
    "Admin",
    "admin.home"
  )->getUrl()->toString();

  $homeResponse = new RedirectResponse("{$link}");
  $homeResponse->send();

  return;
}

Just a note for anyone potentially using the above code - it only works in a .module file, not a .theme file which took me a while to work out.

You can probably use access_filter to prevent access to a specific URL.

It can setup filters that will allow you to deny access to specific URL based on IP (or all IPs) and specify where to redirect anyone who is trying to access that URL.


Edit the default front page One of my colleagues setup a Drupal front page for a website. He has left now. I was given access but I am not able to edit the front page. I can edit every other page, but not the front page.

I don't want to replace the front page with another page. I know how to do that by promoting the page.
I want to edit the content of the front page I already have. It has some RSS feeds coming in, a presentation like thing and some pictures. I would like to edit those.

I googled but I cannot find anything substantial. Can anyone please help? I am a noob when it comes to Drupal, so apologies in advance!

Even if it is the front page is located at the default mysite.com/node, there are dozen's of way of populating it in Drupal with stuff that aren't nodes.

Have you looked if blocks are used to populate the front page?  To check, navigate to Home » Administration » Structure » Blocks, and examine the configuration of the blocks that are enabled.  The RSS feed, for instance, is probably a block.  You can edit the content of blocks, or moving them to region - None - to disable.

One problem here is that we don't know whether you predecessor has done this the right way or his own way.  For all we know, he may have hacked the core or theme template directly.  Things also depends on version and theme.  You haven't told us what version of Drupal you're running or what theme the site uses.  To answer this question with more accuracy than this general answer, all this must be known by the person writing the answer.

Three things to try:

If you're using Drupal 6, navigate to Home › Administer › Site configuration › Site information.  See if there is any contents on that page that account for material on the front page.  If so, you may now edit it.
Change the site's theme.  In particular, get rid of any sub-themes and revert to the default theme for the Drupal version you're running (depends on version).  If you're already running the default, install the admin theme as default (depends on version).  If the content on the front page disappear, it's in the theme templates.  Update your question with this information, and ask how to fix it.  I (and others) will then update our answers.
Back up your configuration (Important!) Upgrade Drupal to the newest major version of the branch you're at (depends on version).  If it is already the latest major version, upgrade anyway.  If the content on the front page disappear, your predecessor has hacked the core.  Restore from backup, and hire a consultant.


Attaching files in Drupal Commerce Selling files online with the following pieces:

Commerce 7.x-1.8
Commerce File 7.x-1.0
Mime Email 7.x-1.0-beta3

I would like to provide people with a document attached to an email. The commerce-checkout-rules almost gets there. What is the token replacement that 'provides a list of files; one per line'? Or otherwise, how do we attach the files being checked out?

Resolved it.

The trick was to create a new variable in the rule.

Store > Configuration > Checkout Settings > Checkout Rules.
Edit the rule : Send an order notification email.
Create a loop over each commerce-order:commerce-line-items.
Add a variable to the loop.

This was the trick.

The data selector is: list-item:commerce-file-line-item-files:0:file

Don't worry about the the 0 - the loop is sending 1 email per document. The result could be cumbersome, but means that if people order 20 documents and they are large, they should still get through.

I called the variable: added_commerce_file_licence_items.

6) Create a Send HTML e-mail rule. Put it in the loop.

The attachments field contains:

[added-commerce-file-licence-items:path]

7) Make sure that the permission "Send arbitrary files" is set.

I could also send by hook_mail_alter(&$message), which allowed me to try a few different things such as permutations of the URL and get a working version without too much experimentation.

function commerceemaildoc_mail_alter(&$message) {
  if (array_key_exists('attachments', $message['params'])) {
    foreach ($message['params']['attachments'] as $attachment) {
        $file_content = file_get_contents($attachment['filepath']);
        $mime_type = file_get_mimetype($attachment['filepath']);
        $attachment = array(
            'filecontent' => $file_content,
            'filename' => basename($attachment['filepath']),
            'filemime' => $mime_type,
        );
        $message['params']['attachments'][] = $attachment;
    }
  }
}


Hook for removing a role from a user Specifically, when an admin goes to the 'People' admin screen, selects some users, then goes to 'Remove a role from the selected users', I want to capture this and apply some other actions.

To give a little bit of insight into what I'm doing: I have another set of tables in the same database belonging to a CRM, and when the user is removed from xyz group, it should toggle the account status in the CRM as well. The action of toggling the status is no problem, I just need to know the best way of going about capturing the role removal. Is there a quick way of doing this, or am I going to need to create a new cancellation method via hook_user_cancel_methods_alter()?

You can use Rules module for it. There is an event "After updating an existing user account", add conditions "User has roles" (both for account-unchanged and account parameters to check roles before and after an update), and as a action you can use "Run custom PHP code" to do whatever you want.


How to add Flag Link field to view based on Search Index? So, I am building a faceted search view on my product display, but I cannot add the field for the Flag link. I can get fields that reference the User's who used a flag, but no relationship that I can add, allows me to access my flag link as a field.

There are references to this problem Add Flag link to Search Index and Flag Module Integration, but no obvious solution. Thoughts? Recipies?

This doesn't work out of the box, but there's a patch for this
https://www.drupal.org/node/1362298


Unable to add Acquia Cloud site using Acquia Dev Desktop behind a proxy (Win 7) I'm trying to use Acquia Dev Desktop 2 Beta behind a proxy at work (Win 7), but there doesn't seem to be any proxy configuration settings for the program.

When I try to log in to Acquia cloud, it times out and says:

  Login failed.
  Network error: Couldn't connect to server

Has anyone figured out how to make this work through your proxy?

Short answer is:
"Proxy configuration is currently not supported in the most recent version of Acquia Dev Desktop"

There are some workarounds, that work with varying levels of success, but nothing solid that I've found.


Compress images before generating PDF file I am working with Views PDF Module, and I used it to export any node of content type "Appointment" as PDF file and then send it by email...

In my case the content type "Appointment" should have a field of type "Image", so that mean I will have many images included on the PDF file.

Let's imagine that the client upload 10 images with 1MB for each one , so that will make my website so slow in generating the PDF file and maybe will not continue all the process .

I need a tool which can compress images before saving the node and that will make it easier for generating the PDF file.

Is there any solutions guys!

The "standard" way to go would probably be to create a "reduced" image style (in admin/config/media/image-styles) and use it for the image field in your "Appointment" content type. Like that, you would let Drupal itself do the compressing of the images.


Database API join fields i've got a database query with a join like this:

$query = db_select('node', 'n');
$query->condition('n.nid', 0, '<>')
  ->fields('n')
  ->range(0, 50);

$query->leftJoin('field_data_field_prospekt_owner','prospekt','prospekt.revision_id = n.nid');

Let's say I want to get the fields from my 'field_data_field_prospekt_owner' table in the result. How do I go about that?

i tried extending the fields function like query->fields('n,prospekt') but this throws an error.

query->fields('n')->fields('prospekt') isn't working, unfortunately. I'm getting a error:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'prospekt': SELECT n., prospekt. FROM {node} n {} LEFT OUTER JOIN {field_data_field_prospekt_owner} prospekt_2 ON prospekt.revision_id = n.nid WHERE (n.nid <> :db_condition_placeholder_0) LIMIT 50 OFFSET 0; Array ( [:db_condition_placeholder_0] => 0 ) in main() (Zeile 42 von /var/www/asvg/prospekt_iframe.php)

You should do

$query->fields('n')->fields('prospekt');

See the documentation for more info.

Note that querying field tables this way is not recommended as the tables are created dynamically. You should only fetch field data via APIs.


new submit button to node form not displayed? When i try to add a new node of type article for example i want to add a new submit button with new submit function so i did like this in hook_form_alter :
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
        case "article_node_form" :
            $form['submit_delegate'] = array(
                '#type' => 'submit', // I tried also '#type' => 'button'
                '#value' => t('Delegate'),
                '#submit' => array('MYMODULE_form_submit_article_delegate'),
            );
            dpm($form);
            break;
  }
}

this is the dpm result of the new form element :

submit_delegate (Array, 3 elements)
type (String, 6 characters ) button
value (String, 8 characters ) Delegate
submit (Array, 1 element)

Thanks in advance.

It will be displayed somewhere between the node form elements. May be you didn't notice that. Try appending this form element under actions like this. Then You can see the button along with save and preview button.

$form['actions']['submit_delegate'] = array(
  '#type' => 'submit', // I tried also '#type' => 'button'
  '#value' => t('Delegate'),
  '#submit' => array('MYMODULE_form_submit_article_delegate'),
);


Configuration management and site specific configuration I have different site environments for my site; dev, test and live site. On dev (local develop) my solr settings are different then on my live environment.

How do I configure site-specific solr configuration, so I am still able to export my configuration from my dev environment (drush cex) and import the configuration into my live environment using drush cim?

I know there is the config split module. Is this suitable for this, or is there a better solution? I want to controle and export all configuration only form my dev environment. I don't want to use drush cex on my live environment. Only import configuration (drush cim). The drush command drush cim is also implemented in the deploy script.

There are multiple ways to override the configuration on a per-environment base.

The config split module is a great tool for splitting complex configurations between the environments. E.g. having some development modules enabled/configured in development, but not installed/no database stored configuration for them in production.

Besides splitting entire module configurations, it also allows you to split single configuration items like parts of your solr settings. You can have them stored in separate configuration folders. These folders can be used as argument when running drush cim <folder> to get them re-imported to a site.

However, this kind of configuration management most often is overly complex, when your configuration differs slightly only between your environments (e.g. some URLs, IDs or flags, while other settings keep unchanged).

The better approach for minor differences might be overriding the configuration within your settings.php, or even better a settings.local.php file, which can be enabled by uncommenting the according inclusion lines at the end of your settings.php (given it's based on default.settings.php):

/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

You can then override your environment specific configuration using the $config array in your settings.local.php:

$config['search_api_solr.settings']['site_hash'] = '...';

This will not alter the database stored configuration or the managed configuration imported using drush cim. Instead, it will override the database stored configuration during page load. Therefore, it might be wise to having production values stored in your database/configuration management and config overrides for your local and/or staging environments. Once you remove your overrides from your settings file, the database stored configuration (re-)applies.


specific htaccess in some sites on multisite i have several drupal sites running as multisite (same core + modules code), just moving to shared hosting

Some sites should be kept password protected. (AuthType Basic)

Is there a way to tell in .htaccess in drupal root that for certain HOSTNAME's
the password section should apply or at least a new .htaccess (in site subfolder) shall override
 .

Apache does not support this.  You can use REWRITECOND to conditionally match rewrite rules, but there is no way to conditionally hide AuthType directives, except to separate the Drupal sites into different Drupal root folders.  Putting an .htaccess file in the sites/mysite folder won't work, because settings.php is read via php, not served up by the webserver.

Use Drupal features to protect your content.  If you turn off the "Access Content" permission for anonymous users, then a Drupal login will be required to view any page; all others will get "Access Denied".


Limit a View with a relationship to show only the first (by sort) relationship of each of the original entities (note - I've tried aggregation and Distinct, see final paragraph. This is different to questions like this one about Views duplicates because I want to remove the "duplicate" relationship-derived items with the first "original" determined by sort criteria, not ID)

To give a simple use-case, imagine a shop with products (italics) and a taxonomy vocabulary 'colour' (bold) something like this. Using products here simply for an easy-to-understand use case.

Each product has a field relating to sales:

Red - Weight: -5

Fire truck. Sales: 12
Telephone. Sales: 128

Blue - Weight: 0

Whale. Sales: 0
Bottle. Sales: 914

Yellow - Weight: 5

Banana. Sales: 1,941
Submarine. Sales: 1

more...

I want something like a view which, for each term (sorted by weight, limited to the top three), shows the term name with the image of the top-selling item, as an example of that category. For example:

Red. picture of a red telephone
Blue. picture of a blue bottle
Yellow. picture of a yellow banana

I could do this using Views Field View module, with each item in a Taxonomy Term view contains a nested view of products restricted to one item, receiving a contextual filter that is the taxonomy term ID, then sorts by sales to show only the top seller. This is my "last resort" option, since Views Field View can create very complex queries. I'd prefer to avoid views within views for somethig that seems so simple.

What I've tried to make work is, making a view of terms, with a relationship to products, then sort it first by product sales then by term weight. This works, but it gives me every product with the term, and I can't find a way to restrict it. With results limited to three the above example would show:

Red. picture of a red telephone
Red. picture of a red firetruck
Blue. picture of a blue bottle

Based on an old similar question on SO, turning on Use aggregation under Advanced view settings and ticking Distinct under Query settings under Advanced view settings, I've managed to get something that removes the "duplicates" from the original list. However, because of the timing of when they're removed, the sort isn't able to apply, and it seems to simply get the first by ID, not by my sort criteria:

Red. picture of a red fire truck
Blue. picture of a blue whale
Yellow. picture of a yellow banana

I believe your issue is a good example of needing additional meta information on your Product (Node) to do (simple) views searches. The approach you've take, by embedding the information into a Field of the node is typically difficult to use. I recommend 2 possible solutions:

This may not have a solution for you but I suggest looking at https://www.drupal.org/project/views_aggregator for complicated aggregated views.
Another option is that instead of using the field with nested values. To use something like the Relation module to store your heuristics (sales data). Relations be linked together to get information like you requested from your products.


How to use an IF statement in node.twig In node.twig (output for articles) I want to use the value of boolean content type field like this, but do not know how to realize this in drupal 8.

if boolean content type is true {

   {{ content.body }}

else {

   {{ content.img }}

}

According the Twig If documentation, you would do it like this:

{% if content.field_boolean == true %}

   {{ content.body }}

{% else %}

   {{ content.field_image }}

{% endif %}

You need to use content.[machine name] you can find the machine name of you fields in Manage Display of your content type.

From my example. change content.field_boolean to the machine name of your boolean field. If your boolean field is called "cool" then replace it with content.field_cool

Remember to clear/flush the cache to see changes.


Programmatically logout user without redirect I have the following code in my module:

<?php

function MODULENAME_init() {
        if (!user_is_logged_in()) {
                global $user;
                $user = user_load(31);
                user_login_finalize();
        }
}

Purpose of this code is to log in all anonymous user as user with id 31. But with this code i can't even logout correctly:

if (user_is_logged_in() && request_uri() == '/user') {
    user_logout();
}

After i am visiting http://ggames.kz/user i am getting redirected back to the main page and so i am logged again as user 31. I want to log out any user when he's requesting http://ggames.kz/user and show a login form in order to log in as user with id 1.

You need to change your hook code.

function MODULENAME_init() {
  if (!user_is_logged_in() && request_uri() != '/user') {
    // Log in the user as user #31.
  }
  elseif (user_is_logged_in() && request_uri() == '/user') {
    module_load_include('pages.inc', 'user');
    user_logout();
  }
}

Since user_logout() is defined in modules/user/user.pages.inc, you need to first load that file, and then call that function, or you will get an error about a not defined function. You don't need to first check the file has been already included, since it will not be included twice.

Keep in mind that http://ggames.kz/user could be directly accessed from users to see their user page, and that Drupal redirect logged-in users who try to access http://ggames.kz/user/login to http://ggames.kz/user.


How to hide field from entity display view programmatically? I am adding field inside module.install file to specified entity. I want to hide this field from display. How can I do that?

Anyway found solution, example of field instance:

field_create_instance(array(
    'field_name' => FIELD_GALLERY_VIEW_FIELD_NAME,
    'entity_type' => 'node',
    'bundle' => 'article',
    'label' => t('Choose gallery View'),
    'description' => t('Gallery view type for display gallery field collection'),
    'widget' => array(
        'type' => 'OPTIONS_SELECT',
        'weight' => 0,
        'settings' => array('size' => 50),
    ),
    'display' => array(
        'default' => array(
            'label' => 'hidden',
            'settings' => array(),
            'weight' => 1,
            'type' => 'hidden'
        ),
        'teaser' => array(
            'label' => 'hidden',
            'settings' => array(),
            'type' => 'hidden',
        ),
    ),
    'required' => TRUE,
));


Printing fields in a View template file (Devel / Krumo) My "Article" node type has a field image. I can print this field in a node template with

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

I have a simple View which lists Articles here. The default Views template /modules/views/theme/views-view.tpl.php prints the content with <?php print $rows; ?> (line 58 here).

I want to use my own Views template which will specify the various elements of the node ie print title, print image, print body etc instead of <?php print $rows; ?>

I don't think...

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

...will work in a Views template so what syntax do I need?

In case it helps I have the devel / krumo output on the page.

I am aiming to use the Views template to control the layout of the Articles in the View, for example I might want the View to look like this:

So I think the default Views template's <?php print $rows; ?> is no good for this and I need to isolate the various elements of the View's output (image field etc)

Thanks...

You not using the correct Views template, views-view.tpl.php is the base template. You need to use views-view-field.tpl.php but you need to use template overrides in your theme.

Firstly, copy views-view-field.tpl.php from the Views module into your theme, make a copy of views-view-field.tpl.php calling it views-view-field--field_image.tpl.php and make your adjustments, remember to clear your template cache so Drupal picks up these files.


variable_get() using "default value" with no reason in Pressflow 6 I'm currently having a problem with variable_get() that sometimes with no reason, returns the default value instead of the one from the database.
I'm using memcached here (and the Drupal memcached module, of course).

Did anybody else also have this problem?
How to fix it?

If you look at the code for variable_init() used by Pressflow, you will notice the following:

If the MAINTENANCE_MODE constant is defined, it tries to acquire the "variable_cache_regenerate" lock; this means the code will not be executed until lock_acquire() doesn't return TRUE.
In the case lock_acquire() doesn't return TRUE, the function will call lock_wait('variable_cache_regenerate'), and then recursively call itself.
After 49 recursive calls, the function set the $variables variable to an empty array; doing so, all Drupal variables are set to their default values.
The comment in the function says:

  Try a limited number of times to avoid
    // infinite recursion if the database connection is invalid for
    // some reason, e.g., mysqld restart, loss of network, etc.

This behavior is not present in the function used by Drupal 6, where variable_init() doesn't use any lock.

Similar code is used from Drupal 7, even though there is a slight difference: Drupal 7 reads the values of the Drupal variables from the database, while Pressflow doesn't do that. Compare the following snippets; the first one is used in Drupal 7, while the second one is used in Pressflow 6.

// Cache miss. Avoid a stampede.
$name = 'variable_init';
if (!lock_acquire($name, 1)) {
  // Another request is building the variable cache.
  // Wait, then re-run this function.
  lock_wait($name);
  return variable_initialize($conf);
}
else {
  // Proceed with variable rebuild.
  $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  cache_set('variables', $variables, 'cache_bootstrap');
  lock_release($name);

  // Wait for another request that is already doing this work.
  lock_wait('variable_cache_regenerate');

  // Run the function again. Try a limited number of times to avoid
  // infinite recursion if the database connection is invalid for
  // some reason, e.g., mysqld restart, loss of network, etc.
  $recursion_depth++;
  if ($recursion_depth < 50) {
    return variable_init($conf, $regenerate, $recursion_depth);
  }

  $variables = array();


Problem with ssl, broken site I want to install Drupal in https, but I failed.The page is trying to open resources (css, etc) in http. How to solve this ?

In Drupal 7 you could set the $base_url='https://example.com'; in /sites/default/settings.php.

For Drupal 8 it looks like $base_url has been removed in favor of trusted domain patterns which are protocol agnostic. Using .htaccess rules seems to be the recommended approach.

In .htaccess below RewriteEngine on

  # Redirect to HTTPS
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

That's from this page: https://www.drupal.org/https-information


Randomly display questions in Webform - to use as an exam Is it possible to randomly select a fixed number of questions to display in a Webform? I have a request to set up over 500 questions in a webform but for each user who visits the webform, only a random selection of 100 questions will be displayed. The rest will not be displayed. The purpose of this is to use the Webform as an exam/quiz.

Note: the hidden questions cannot be visible in the code, so CSS or other Javascript hiding techniques are not suitable.

Any ideas how I might achieve it.

Thanks a mil

F

You can use form alter to access $form array and display/hide specific elements, more details: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-programmatically-hide-and-show-webform-elements.

function CUSTOM_MODULE_form_webform_submission_WEBFORM_NAME_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $elements = &Drupal\webform\Utility\WebformFormHelper::flattenElements($form['elements']);

  $elements['question_one']['#access'] = FALSE;
  $elements['question_two']['#access'] = FALSE;
}


Password Gets Reset when executing user_save I have a function that sets a user to confirmed after they login to my site for the first time. However, whenever I run this function and I log out and try to log back in the password doesn't work anymore and I have to do a manual reset in the database. I can't seem to find what would cause a change in the password. Any advice?

Note that I am using mongodb.

function update_profile($uid,$attribute_name,$attribute_value,$arrayaction=NULL)
{
    // update some user property
    $existing = user_load($uid);
    $edit = (array) $existing;

    //Update profile iformation
    if(!empty($arrayaction))
    {
        if(strtolower($arrayaction) == 'push')
        {
            array_push($edit[$attribute_name]['und'][0],$attribute_value);
        }
        else if (strtolower($arrayaction) == 'unset')
        {
            if(($key = array_search($attribute_value, $edit[$attribute_name]['und'][0])) !== false) {
               unset($edit[$attribute_name]['und'][0][$key]);
            }
        }
    }
    else
    {
        $edit[$attribute_name]['und'][0] = $attribute_value;
    }

    //Make the changes to the user
    user_save($existing, $edit);
}

function module_user_login(&$edit,$account) {
    if ($account->access == 0) {
        update_profile($account->uid,'field_confirmed',array('value'=>1),NULL);
    }
}

Be sure to

unset($edit['pass']);

if you don't want to edit password. Generally creating $edit from $existing shouldn't be needed. You do not need to re-save all fields, you only put into $edit what you know you want to change. You should, usually, be able to start with empty array, without seeding it first.


How to create a view displaying nodes posted in the logged-in user groups? I can't figure out how to create a view listing all nodes from the logged-in user groups. This was easy with Drupal 6 version of Organic groups, but with the entity based version, it is not obvious (or maybe not doable without some views data hooks).

Thanks for your help.

In Views you can use  User: Current under "Filter Criteria" to filter the view results.


Dynamic block on the side suggestion Googling didn't help a lot in this issue. I was wondering if there is a drupal module that inserts sort of a dynamic content in the side of the page the can be expanded and shrinked while pressing a button/arrow?

This is more like a Javascript question, no i don't think you will find that kind of module.

You can always write your own Javascript/jQuery slideToggle() behavior (my suggestion) in a .js file in your theme, control any DOM element (like a block title) and assign this behavior to it.


Language comparison in template file My site has 3 languages. In my node--service.tpl.php, I've put the following:

<?php if ($language = 'es'): ?>

<a href="<?php print $base_url . $node_url ?>">Leer más

<?php elseif ($language = 'en'): ?>

<a href="<?php print $base_url . $node_url ?>">Read more

<?php else: ?>

<a href="<?php print $base_url . $node_url ?>">Leere más

<?php endif; ?>

However, it only shows me the language es even a page en, i.e. it only shows me the first div. Any idea?

node--TYPE.tpl.php doesn't include the global $language variable as you can see in this document but you can still use it by bringing the variable into scope, using global.

I've updated your code below to show you how to get this working.

<?php global $language; ?>
<?php if ($language->language == 'es'): ?>

<a href="<?php print $base_url . $node_url ?>">Leer más

<?php elseif ($language->language == 'en'): ?>

<a href="<?php print $base_url . $node_url ?>">Read more

<?php else: ?>

<a href="<?php print $base_url . $node_url ?>">Leere más

<?php endif; ?>


CKEditor Link a content with rule as a hypelink with title and url to a custom field I would like to add a hyperlink entry in a blog which points to a internal content URL with different content type which needs to be display for authenticated users.

1.) The hyperlink should show the title of the content

2.) The hyperlink URL should be mapped to a custom field

3.) The hyperlink should not be visible to a chosen user and should be customizable

Is this possible in drupal ckeditor? or should we write PHP for it using PHP filter?

You don't want to use PHP Filter. That's for embedding PHP code into a Drupal content field and is not what you want (unless you're willing to give your content creators access to PHP code that could potentially break the site).

You want to implement 2 things to provide your custom functionality in a Drupal module:

Provide a custom plugin to CKEditor: You'll need to build your own CKEditor plugin which will do the work of building your custom markup (e.g. internal URL, title, mapped field, uid, etc.) to embed into CKEditor, You'll need a custom module to define it via hook_ckeditor_plugin() in D7 (or a CKEditor plugin in D8), then enable it in the Drupal CKEditor module settings.
Provide a custom input filter: After your CKEditor button provides the markup for your custom link, you'll need a custom input filter so you can process the CKEditor markup for display that depends on your requirements. This can be defined in D7 with hook_filter_info() (or a filter plugin in D8). Once this input filter is enabled for your text format, it should be able to post process the information (e.g. internal URL, title, mapped field, uid, etc.) that CKEditor plugin embedded in its markup so you can render it accordingly.


settings.php displays in browser For all the Drupal sites I run except one, requesting /sites/default/settings.php in the browser results in a blank page, which seems right and proper.

But for one of my sites (on a different host), requesting /sites/default/settings.php actually results in the file's contents being served to the browser.

I have no idea where the trouble might be: is this a Drupal problem? Apache problem? Doesn't seem to be related to file permissions. How can I ensure that a request to settings.php doesn't serve the file?

As a stopgap measure I've added a line in .htaccess that generates a 410 error when settings.php is requested, but I'd really like to know how this is supposed to work...

According to this Stackoverflow question you might need to add this to your server configuration:

AddType application/x-httpd-php .php

Another possibility is an encoding problem, according to this other Stackoverflow question.


ContentEntityForm buildForm method parent out of memory I have the following issue with my form class that extends the ContentEntityForm class.

When calling the parent buildForm which is needed my system runs out of memory.

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    // Here is already runs of memory. $form is never initiated.

    /* @var $entity \Drupal\sg_configuration_rule\Entity\ConfigurationRule */
    $entity = $this->entity;

    $form_state->set('old_cron_value', $entity->get('cron_settings')->first()->value);

    $type = FALSE;

    if (!$entity->isNew()) {
      $type = $entity->getPluginInstance()->getPluginId();
    }

    if ($entity->isNew()) {
      $type = \Drupal::request()->query->get('type');
      if (!$type) {
        return new RedirectResponse(Url::fromRoute('configuration_rule.add_form_step1')->toString());
      }
    }

    if ($type) {
      try {
        /** @var \Drupal\sg_base_api\Plugin\BaseApiPluginInterface $enabled_api */
        $enabled_api = $this->baseApiPluginManager->createInstance($type);
      }
      catch (PluginException $exception) {
        LoggerService::error($exception->getMessage());
        return new RedirectResponse(Url::fromRoute('configuration_rule.add_form_step1')->toString());
      }

      $enabled_api->configRuleForm($form, $entity);

      $form['plugin_type']['widget'][0]['value']['#value'] = $type;
      $form['plugin_type']['widget'][0]['value']['#access'] = FALSE;
      $form['plugin_type']['widget'][0]['value']['#disabled'] = TRUE;
      $form['server_node']['widget']['#options'] = $this->getServerNodesByType($enabled_api->entityType());
    }

    $form['user_id']['#access'] = FALSE;

    return $form;
  }

When i check the parent function i noticed that the line:

$form = $this->form($form, $form_state); is causing this in the class EntityForm(Core method).

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // During the initial form build, add this form object to the form state and
    // allow for initial preparation before form building and processing.
    if (!$form_state->has('entity_form_initialized')) {
      $this->init($form_state);
    }

    // Ensure that edit forms have the correct cacheability metadata so they can
    // be cached.
    if (!$this->entity->isNew()) {
      \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
    }

    // Retrieve the form array using the possibly updated entity in form state.
    // This is causing my memory timeout.
    $form = $this->form($form, $form_state);

    // Retrieve and add the form actions array.
    $actions = $this->actionsElement($form, $form_state);
    if (!empty($actions)) {
      $form['actions'] = $actions;
    }

    return $form;
  }

If i comment that line out it is working fine but this is needed to save my values in config. Also this is core and should work.

Anyone else have this problem and knows the solutions to this?

Thanks.

Are you sure this is a coding error? Are you loading any large quantities of content in the form by any chance? Loading a lot of nodes in a select field, for instance, can generate memory overflows.


Can I make interaction between views relations and views arguments? I'm running into the problem where I have to join a node and a registration. The nodes are of type 'event' and the registration is available for some, but not all of them.

So basically I have a list of event nodes, and I left join the registrations on them, giving me some extra information where available.

The problem is I want to list only my registrations. So a contextual filter has to be added somewhere. The problem; The default filter applies after the join, filtering also all nodes for which I have not yet registered. But I want to show those.

Therefor I am looking for a custom handler that allows me to add an 'extra' statement to the views join clause. I've looked for it, but started t doubt where such  a thing is actually possible. Had anyone ever tried such a thing?

I suppose I need to make a custom hander, it's not a problem. But can handers 'communicate', or is there something like a hybrid handler of some sort?

Wrong query

SELECT ...
FROM
{node} node
LEFT JOIN {node_registration} node_registration_node ON node.nid = node_registration_node.nid
WHERE (( (node_registration_node.uid = '1' )

Working query, but non contextual

SELECT ...
FROM
{node} node
LEFT JOIN {node_registration} node_registration_node ON node.nid = node_registration_node.nid AND node_registration_node.uid = '1'

Thanks for the suggestions Andrew, I ended up creating a custom argument-handler. It adds one (or more) extra conditions to the join. LEFT JOIN ... AND ....

function query($group_by = FALSE) {
  $this->ensure_my_table();

    $this->query->table_queue[$this->table_alias]['join']->extra = array(
      array('table' => $this->table_alias, 'field' => $this->real_field, 'value' => $this->argument),
    );
  }
}


Set a page to show only to registered users I have a website with two pages. The "home page" and a "notice page". The notice page should only be viewable to people who are logged in or people who have the role called "Basic User". I have created the role, but I cannot find how to set this notice page (basic page) to require log in.

Here is a similar question, but I think it is regarding drupal 6 and I know that a lot has changed when drupal 7 was released.

Set a page to be only viewed by users who are logged in

There's a usable dev version of Node Privacy by Role for D7.

Alternatively, you could edit the templates for those pages to check a user's role before displaying the content. I can't really think of why you'd want to, but you could.


How to use drush with proxy I am using Acquia Dev Desktop 2 for my Drupal 8 project, I tried to download module with Drush. But I can only access the internet via a proxy. How can I configure drush to use the correct http proxy settings for downloading?

Drush by default is using wget to download project (if available), otherwise curl. This can be change by --package-handler. You can check which package handler is in place by running your command with debug parameter (-d).

So you configure proxy the same way as you would configure this for wget or curl.

For wget, you can configure these lines in ~/.wgetrc:

use_proxy = on
https_proxy = http://proxy-host:8080
http_proxy = http://proxy-host:8080

Note: Please check /usr/local/etc/wgetrc for some examples.

For curl this line should in your ~/.curlrc:

proxy=http://username:password@proxy-host:port

For both I think you can try to export http_proxy/https_proxy as a system variable.


How to change field cardinality per form either programatically or by rule? I've a multipage form (where each page is determined by field group) where on the first page user type number of people in text field and on the second one I would like to show X number of field collection instances based on the given number. So if user selects 5 people, I expect to see 5 field collection placeholders to fill for the user and no more Add another item buttons (especially when field cardinality is set to Unlimited).

Is there any solution which can achieve setting up cardinality per form state by a rule or from the code?

There are the following hooks which allow to alter the widget form such as hook_field_widget_form_alter and hook_field_widget_WIDGET_TYPE_form_alter, but they only apply to widget form element.

As for workaround, it's possible to set the field to Unlimited and use hook_form_alter to remove add_more element manually like:

$form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
$form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;

or overriding/removing #theme:

unset($form['field_foo'][LANGUAGE_NONE][0]['#theme']);

for certain conditions.

Using Rules, it's possible to use Rules Forms Support module which can deal with form elements, so you can change the items_count. Here is sample rule dealing with a multi value field in Entityform:

/**
 * Implements hook_action_info().
 */
function mymodule_entityform_rules_rules_action_info() {
  return array(
    'foo_entityform_rules_set_cardinality_value' => array(
      'label' => t('Change items count of a multi value field'),
      'group' => t('Rules Forms'),
      'parameter' => array(
        'form' => array('type' => 'form', 'label' => t('Form')),
        'form_state' => array('type' => 'form_state', 'label' => t('Form State')),
        'element' => array('type' => 'form_element', 'label' => t('Target Element')),
        'value' => array('type' => 'form_element', 'label' => t('Value from Element')),
      ),
      'base' => 'foo_entityform_rules_set_cardinality_value',
      'callbacks' => array(
        'access' => 'rules_forms_integration_access',
        'form_alter' => 'rules_forms_element_form_alter',
      ),
    ),
  );
}

/**
 * Implementation of rule callback.
 */
function mymodule_entityform_rules_set_cardinality_value($form, $form_state, $element, $value) {
  module_load_include("module", "rules_forms", 'rules_forms');
  $val_elem = &_rules_forms_get_element($form, $value);
  if (!isset($form_state['field'])) {
    return;
  }

  $element = substr($element, strpos($element, ':') + 1);
  $path = explode(':', $element);
  if (count($path) == 1) {
    $path[] = LANGUAGE_NONE;
  }

  $field_state = &drupal_array_get_nested_value($form_state['field'], $path);
  if (!$field_state) {
    return;
  }

  $limit = !empty($val_elem['#value']) ? $val_elem['#value'] : (!empty($val_elem['#default_value']) ? $val_elem['#default_value'] : NULL);
  $field_state['items_count'] = $limit;
  $field_state['field']['cardinality'] = $limit; // Won't work for field_multiple_value_form().
}

This works when field is set to Unlimited, however Add another and Remove buttons still needs to be removed from form_alter as shown below:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

    // Check cardinality.
    // If items_count for a field has reach its cardinality limit,
    // then remove Add more and Remove buttons.
    foreach ($form as $key => $item) {
      if (is_array($item) && !empty($item['#type']) && !empty($item['#language']) && $item['#type'] == 'container') {
        $field = &$form[$key];
        $langcode = $field['#language'] ?: LANGUAGE_NONE;
        $field_state = field_form_get_state($field[$langcode]['#field_parents'], $field[$langcode]['#field_name'], $langcode, $form_state);
        if ($field_state['items_count'] == $field_state['field']['cardinality']) {
          $field[$langcode]['add_more']['#access'] = FALSE;
          foreach (array_column($field[$langcode], 'remove_button') as $key2 => $rm_item) {
            $field[$langcode][$key2]['remove_button']['#access'] = FALSE;
          }
        }
      }
    } // end: foreach
  }
}

It's also worth to try some patches from Allow cardinality to be restricted (overridden and reduced) in the field instance settings or  Add hook alter to override field_multiple_value_form().

There is also Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

Some other proposed workaround from here by @donquixote (without actually hacking Drupal core) could include:

a new widget type with FIELD_BEHAVIOR_CUSTOM with widget settings to change a cardinality limit, the name of another ("decorated") field widget type and other settings for the decorated field widget type,
add a number field in the instance settings form and use hook_field_widget_properties_alter to replace $instance['widget']['module'] (keep original in $instance['widget']['_module']) and replace override $instance['widget']['type'] with own FIELD_BEHAVIOR_CUSTOM and save the original in $instance['widget']['_type'], so you can do the same decorator trick in hook_field_widget_form as above.

Modules

Related modules:

Multivalue Extras

  Enhances settings for multiple value fields.


server side path to filesystem How do I get the server side directory of the filesystem path?

For example, my files are in http://mydomain.local/myfiles; this is the root of my drupal filesystem. I am searching for a function that will give me d:\xampp\htdocs\drupal\myfiles.

$_SERVER['DOCUMENT_ROOT'] will get you the d:\xampp\htdocs and $base_path or base_path() will give you the Drupal part.


Admin edit of older order forces to add values to newly added required fields In our drupal-commerce e-shop orders were already working for more than a year. Later we wanted to add some required fields (phone number and "I agree with ...." checkbox), phone field few months back and the checkbox just recently (as part of GDPR-ready effor).

Today we realized that admin editing of order to move it in workflow (change state) forces the admin to fill-in the phone number field and to check the checkbox. That is not good.

Also it looks that in order list is the name of admin now ... for those edited orders.

Does anyone know how to fix this behaviour? Any existing issue? We just want to be able to change the order state and not to change anything else.

Versions: Drupal 7.59, Commerce 7x-1.14

How you resolve this depends on your Drupal version, so please be sure to specify Drupal 7 vs. Drupal 8 in future questions. On Drupal 8, you can likely resolve this by editing the form display mode and not including those fields on the normal admin form. However, in Drupal 7 you'll have no such option. You'll need to use hook_form_alter() to prevent those fields from showing up on the order edit form instead.

Re: the administrator name, there's no way for us to help you without knowing how you've constructed that View. If it's just showing the name of the last person to edit the order (i.e. create a revision of it), it makes sense that it'd be the administrator. It should normally be pulling the name from the order's billing information profile.


How do I get a hold of the session object in my form handler? I have build a form in D8 and on submit I want to save the form values into a session, so that I can access them 3, 4,.... page requests later.
In D7 I just used

$_SESSION['key'] = $value

I have a feeling, in D8 and symfony, this is (very) bad practice. How should I solve this?
At the moment I'm using the following chunk of code, but I don't know if this is the correct way:

$session = new Session();
$session->set('name', 'value');

$name = $session->get('name');

The conversion to the Symfony session component is not yet complete, therefore you still have to access the session using the superglobal.

Follow https://www.drupal.org/node/1858196 and its sub-issues, if you like to stay up to date regarding this issue.


Services module and hook_node_view When I view a node via Services in json or xml format a field I am adding via hook_node_view is unavailable. How could I add the field so it is available also when the node is viewed via Services?
I only seem to be able to access the node via hook_node_load

hook_node_view() is only invoked when a node is prepared for display (normally either through node_view() or node_view_multiple()).

Since the node isn't prepared for display when you request it via a services call, your hook won't be called. If you think about it this makes perfect sense; you're requesting a json/xml representation of the node so there's absolutely no reason why the node should be prepared for display.

The only way round this would be to move your logic into hook_node_load(), which is called for all node loads. The same data that you attach in hook_node_load() is available to you on the node object in hook_node_view(), so you'll be able to move your logic without any problem at all.

I suppose the other, more complicated method, would be to write your own Services resource that loads the node view as well as the node, so the extra data you're adding would get picked up.

But semantically speaking, unless the actions you're taking relate specifically to the HTML that will be output for the node, hook_node_view() is not the right place to add your extra data.


Panels - custom or use System? Maybe I'm not getting this but for Page manager (Panels) there is two options to create a page either Custom Page or use the System (Node Template).

I need to create a Panel for the news page (/news). I could either create a Custom one and set the path to "/news" OR use the System node_view page and create a Variant where if the Selection rule = This panel will be selected if Current path is "news".

Which way is better? Should I overload the System with many variants where one of them checks if the Current path is "news" or create my own Custom Page for the news page?

A page provides a certain context.

For node_view, it happens to be a node.

There's no benefit to creating a custom page just to provide the same context.

You'd want to add a new page however, if you, for example, wanted both a node and a taxonomy term as context.


Order nodes in multiple views I have a site where there are multiple staff profiles, each of which are in a specific department; some times more than one. Parts of these profiles are then displayed in a grid view for each department.

What I need to do is have a method of setting their ordering in the grid view. My original plan was to just have a text field where they can enter the profiles position number & have the view order by that. The problem is they can be part of multiple departments so the numbers entered could conflict between departments.

Does anyone have any ideas on a way around this?

The other idea that has been suggested is to add a weighting to each profile and that would dictate its position, still kind of has the same problem as the text field though. If I was to use the weighting system what is the best way to add it? I assuming just creating a select field with the options -50 through to +50 isn't the best way?

With the module Draggable Views, you can set up an administrative view to set the order (with the standard drag and drop interface), and then you can create other views that display the contents following that order.
There is a comparison of node/entity ordering modules here
Draggable Views:

DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
Have you ever rearranged Blocks?, sorted Taxonomy terms? or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
With DraggableViews you can apply this tabledrag.js to any Views-generated table.
Features:

Order any type of entity.
Set different order for different set of arguments.
Create one view that sets the order, and create as many views as you like that shows that order.
Use core tabledrag.js or jQuery UI draggable javascripts to set the order.


Site wide information data I'm using many information data on my site. I have some blocks with the main informations like address and phone numbers, but also I have some blocks with Quick Response code, geolocations (latitude, longitude) etc. There is about 15 this kind of details.

I wrote a simple module which allows me to define them in one place and save all of them as a one variable (array), so if I need any contact detail in any block template file, I just call e.g: $contact_details['qr_code'] to get it.

It's working and it is very useful, but I'm just wondering what do you think about that? Maybe I spent couple hours unnecessarily, because this kind of module already exists, or maybe I did not need any module at all, because for example: I should create a page with as many fields as I need, and then create my blocks with views?

I think many people would be intersted where to store all their contact informations and use them to build any content they need, for example blocks.

there is a small cutting of my module output:

AFAIK, there is no module that does this for you.

I think this is a sensible approach.  I am doing the same thing myself, storing the array with site-wide persistant data using the built-in function variable_set() to save, and then I use function variable_get() to retrieve the data.

I don't think saving site wide information in fields is a good idea.


Webform show custom composite result at their own line in submissions download I have a webform with a custom composite field
THE custom composite has one text field that can be repeated an unlimited amount of times

here is an image of the form:

What I want is to show each student name in a separate line when I download the results.
Is it possible to do it using a module?
if not I will be glad to hear if there are hooks that can manipulate the downloaded data

I solved the above issue by creating a new Webform Exporter plugin, extending the default "Delimited text" in a custom module. I assume you download them in either CSV or MS Excel file format. I've only tried the below for the CSV export, but I see no reason for it not working for MS Excel ones as well.

The idea in a short summary is:

Create a custom WebformExporter plugin extending the default "Delimited text" exporter (class DelimitedWebformExporter)
Override the writeSubmission method which adds the data to the CSV string and make it run once for every sub-element of your composite element

How to create a custom WebformExporter plugin

In a custom module, create the file

<custom_module_root>/src/Plugin/WebformExporter/CustomDelimitedWebformExporter.php

And in it create a class CustomDelimitedWebformExporter with the necessary annotations in order to define the WebformExporter plugin. Also since we want to extend the default exporter for delimited text, our class should extend the "Delimited text" class DelimitedWebformExporter.

<?php

namespace Drupal\custom_module\Plugin\WebformExporter;

use Drupal\webform\Plugin\WebformExporter\DelimitedWebformExporter;

/**
 * Defines a delimited text exporter.
 *
 * @WebformExporter(
 *   id = "custom_delimited",
 *   label = @Translation("Custom Delimited text"),
 *   description = @Translation("Exports results as delimited text file, splitting the composite element's multiple values to different rows."),
 * )
 */
class CustomDelimitedWebformExporter extends DelimitedWebformExporter {

}

If you did this correctly you should see (after clearing cache) a new option in the "Export format" dropdown in the Results Download page of the webform.

How to override the submission writing to loop for each subelement

Now override the writeSubmission method. That method in the parent class builds a new row of results for each submission and then puts the data in the CSV handler. Since we want the results in different rows, we therefore need to call the parent method just as many times and print each subelement.

use Drupal\webform\WebformSubmissionInterface;

const COMPOSITE_ELEMENT_KEY = 'composite_element_key';

/**
 * {@inheritdoc}
 */
public function writeSubmission(WebformSubmissionInterface $webform_submission) {
  $element = $webform_submission->getElementData(self::COMPOSITE_ELEMENT_KEY);
  if ($element) {
    for ($i = 0; $i < sizeof($element); $i++) {
      $webform_submission->setElementData(self::COMPOSITE_ELEMENT_KEY, [0 => $element[$i]]);
      parent::writeSubmission($webform_submission);
    }
  } else {
    parent::writeSubmission($webform_submission);
  }
}

A couple of notes:

The above works for one specific composite element in your webform. You can adjust the behaviour if you need it for more that one or for an arbitrary one (i.e. by checking if the element type is composite)
As the above does not change anything for the rest of the webform's elements, the rest of the columns in the results will have their data copied in every extra row created.

End result

<?php

namespace Drupal\custom_module\Plugin\WebformExporter;

use Drupal\webform\Plugin\WebformExporter\DelimitedWebformExporter;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Defines a delimited text exporter.
 *
 * @WebformExporter(
 *   id = "custom_delimited",
 *   label = @Translation("Custom Delimited text"),
 *   description = @Translation("Exports results as delimited text file, splitting the composite element's multiple values to different rows."),
 * )
 */
class CustomDelimitedWebformExporter extends DelimitedWebformExporter {

  const COMPOSITE_ELEMENT_KEY = 'composite_element_key';

  /**
   * {@inheritdoc}
   */
  public function writeSubmission(WebformSubmissionInterface $webform_submission) {
    $element = $webform_submission->getElementData(self::COMPOSITE_ELEMENT_KEY);
    if ($element) {
      for ($i = 0; $i < sizeof($element); $i++) {
        $webform_submission->setElementData(self::COMPOSITE_ELEMENT_KEY, [0 => $element[$i]]);
        parent::writeSubmission($webform_submission);
      }
    } else {
      parent::writeSubmission($webform_submission);
    }
  }

}


Checkboxes, Radios, 'select or other' wont render inside table select element I want to render elements of type checkboxes or radios inside tableselect, but what I get are empty html tags. Textfield and select type elements render fine.

Basically this renders fine.

$tableSelectTesting = array(
  '#type' => 'select',
  '#options' => array(
    "1000" => "$1000",
    "other" => t("Other"),
  ),
);

This does not.

$tableSelectTesting = array(
  '#type' => 'radios',
  '#options' => array(
      "1000" => "$1000",
      "other" => t("Other"),
    ),
);

I add the form element to table select using the 'data' array key.

$options[$index] = array(
    'column1' => $column1Data,
    'column2' => array(
      'data' => $tableSelectTesting,
    )
  );

This is the output I get for the radios element.

What should I be doing differently?

I believe you are missing some details in the way you structure your data. Check this example, specifically the data array tree.

Also, check the structure of the array that defines the tableselect. For radios it should look like this:

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);

(the #multiple property is the one that defines whether these are checkboxes or radios)

Your data in the array $options should look something like this:

$options = array(
  '1000' => array(
      'field_price' => '$1000',
  ),
  'other' => array(
      'field_price' => 'Other',
  ),
);

Notice the nested structure, and the field name (this could be anything, but it needs to exist, one for every column of the table, starting with the second column.


Would redirecting users in hook_menu's access callback have any undesirable effects? This answer led to a discussion about the best way to redirect a user to a specific page if they shouldn't have access to the page they are trying to access.

One option is to set the access callback to true and then redirect users in the page callback. Whilst this seems valid I think it is mixing access functionality with page building functionality in the page callback.

E.g.

function hook_menu() {
    $items['player/my_page'] = array(
        'title' => t('My Page'), // note this is a required parameter
        'access callback' => TRUE,
        'page callback' => 'some_function',
    );
    return $items;
}

function some_function() {
    global $user;
    if(!$user->uid) { // here checking if the user is logged in but could be checking for a specific permission or field value
        $dest = drupal_get_destination();
        drupal_goto('user/login', $dest); // this remembers where the user is coming from
    }
    // carry on building rest of page
}

Another option is to set the access callback function to call a function that checks if the user has access, but then instead of returning false it would redirect the user to another page. This is good as it is separating access logic and page building logic. However the purpose of an access callback is to return a boolean value, so this is breaking that logic by redirecting the user.

E.g.

function hook_menu() {
    $items['player/my_page'] = array(
        'title' => t('My Page'), // note this is a required parameter
        'access callback' => 'check_access',
        'page callback' => 'some_function',
    );
    return $items;
}

function check_access() {
    global $user;
    // here checking if the user is logged in but could be checking for a specific permission or field value
    if(!$user->uid) {
        $dest = drupal_get_destination();
        drupal_goto('user/login', $dest);
    }
    return TRUE;
}

Are there any undesirable effects from redirecting users in the access callback that I'm not aware of?

What do you think is best practice here?

I think you could do this by altering the delivery callback function. If the access callback returns FALSE that's what's passed to the delivery callback. If you wanted this redirect behaviour just on specific pages you could modify the delivery callback just for those pages via hook_menu() or hook_menu_alter(). If you want the behaviour to be global, you can use a hook_page_delivery_callback_alter() to change it.

Here's an example delivery callback.

function custom_deliver_html_page($page_callback_result) {
  if ($page_callback_result === MENU_ACCESS_DENIED) {
    drupal_goto('<front>');
  }
  drupal_deliver_html_page($page_callback_result);
 }

Btw this is untested, and I've never actually altered the delivery callback myself previously.


Get all nodes with empty taxonomies I'm trying to fetch all nodes who's term reference field has no value or NULL.

$query = \Drupal::entityQuery('node')
    ->condition('type', 'mycontenttype', '=')
    ->condition('field_grade_level.entity.name', '');

    $nids = $query->execute();
    return $nids;

But it doesn't seem to work, giving empty results. Can anyone help what's wrong with the query?

You query is looking for nodes that are tagged with a term that has an empty label. Obviously that's not what you want. What you're looking for is notExists():

$query = \Drupal::entityQuery('node')
  ->condition('type', 'mycontenttype', '=')
  ->notExists('field_grade_level');

$nids = $query->execute();
return $nids;


how to set up a user field that the only the administrator can access? I would like to have a STATUS field for certified and uncertified for all users under a certain role preferably, but it could be for all users

how would i go about implementing this?  thanks!

You can use the Field Permissions module:

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

Once installed you'll be able to set CRUD permissions on each field's settings form.


Controlling access to documents for specific users I need customers to be able to access certain documents (PDFs mainly) specifically for them (they contain sensitive information).  The document information is setup in nodes.  I have looked at a lot of access control modules, but they all seem to focus on user roles.  I don't want a role for every customer.  What would be the best way to structure this?

A possible (but somewhat convoluted) solution could be to use Node access user reference module with private files setup. Basically adding a user reference to a node will allow them to see its content (including files) and having files' folder protected will prevent direct access to the file urls.


form field not rendering i have a problem theming my user-profile-edit.php
the user name field (name) is rendering nothing, while other fields like 'mail' are working good.

//contents of user-profile-edit.php
<?php
print render($form['form_id']);
print render($form['form_build_id']);
print render($form['form_token']);
print render($form['account']['name']);
print render($form['account']['mail']);
?>

//contents of template.php
...
function MY_THEME_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
    'user_login' => array(
      'render element' => 'form',
      'template' => 'templates/user-login',
    ),
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'templates/user-profile-edit',
    ),
    'user_pass' => array(
      'render element' => 'form',
      'template' => 'templates/user-pass',
    ),
    'user_pass_reset' => array(
      'render element' => 'form',
      'template' => 'templates/user-pass-reset',
    ),
  );
}

in the end when I open the page mysite.com/user/1/edit I can only see the mail field.

any idea of what am I doing wrong?? or how can I render that name field so I can customize the visualization?

Encountered a similar problem when trying to render the Forgot Password form in a block.

Since the form builder for the form is in user.pages.inc, the solution is to load the include file at the same time you do the drupal_get_form() to retrieve the form. e.g.

module_load_include('inc', 'user', 'user.pages');

If you are calling the form via a hook_menu implementation, you will need to use the 'file' and 'file path properties'.