How can you group multiple answer fields? Firstly, apologies if I don't use correct Drupal or database terminology - I'm still learning!

I am using Drupal 6 with the latest stable versions of CCK, Views and Date.

I have a content type that requires two 'sections' of fields - the first would be for standard fields, the second would be multiple entry fields where all the fields are related.

It's probably best explained with an example, so here goes:

Let's say the content type is for episodes of a TV show.

Firstly, we want to know the title of the episode, so there'll be a title field.

Secondly, we want a reference number for the episode, so there'll be an ID field.

Now for the grouped fields:

We want to know when the episode was broadcast, and on what channel.  However, it may be that the episode is repeated - and that repeat could be on another channel.  For example:

Top Gear was on BBC2 this evening (26/06/11) at 8pm.  It will be repeated on BBC2 on 28/06/11 at 11.20pm.  It will be repeated again on 29/06/11 at 7pm, this time on BBC3.

So I want to have an unlimited value datetime field.  However, this needs to be bound to an unlimited value text field for the channel (and likewise for any other field with unlimited value data).

How do I achieve this?

Thanks in advance for any assistance!  Please bear in mind that I'm not much more than a novice - I can install a module but I won't know how to do any advanced stuff without guidance!

The drupal 6 version of cck comes with a sub-module called multigroup. This will allow you to group multiple fields together and allow for unlimited inputs per group.


How do I include a jQuery in the body of a content type? I try to include a jQuery in the body of a content type, as shown in the image below:

The purpose of this jQuery is to hide a div with id="test", so that the text aaaaaaaaaaaaaaaaaaaa in it is not shown. The jQuery was added to the content (saved in it), but yet I still can see the aaaaaaaaaaaaaaaaaaaa and my js did not run.

I added scripts[] = js/test.js to my .info file. I then put test.js inside the mytheme/js folder. I cleared all caches and still nothing happens. I also installed jQuery, changed to version 1.10, and still no luck.

Seems like Drupal JQuery.js file is not loaded, so how can I get it loaded? Do I also need to add jquery.min.js in the .info file and the js/ folder?

UPDATE:

(function($) {

$('#wrap').hide();

})(jQuery);

When I put the above code in a block, it works. If I put in the test.js file, it doesn't work.

If I put an id or a div that is not part of my page.tpl, it doesn't work even on a block.

This is so weird.

Update #2 (re-edited)

Turns out the actual reason it didn't work when using the .info and .js file is that the .js file needs a document ready function

(function($) {
$(document).ready(function(){
$('#test').hide();
});
})(jQuery);

Thanks to all that tried to help.

As @Gulok and @Drupalist said it is not good that add your js in content,the simple way to add js with one of below solutions (it is seems you are newbie to drupal I suggest if you want use learn and use drupal  use is correct,I can suggest a solution that you can add js in body(content) but I prefer guide you in correct way ;) )

  The PHP function drupal_add_js() lets you add a JavaScript file,
  setting or inline code to the page and it takes 5 parameters (see the
  api reference).

  The first parameter is always going to be a path to a js file, an
  array, or a piece of JavaScript code. If the second parameter is
  'module' (the default), 'theme', or 'core', then the first parameter
  must be a path and the only difference between these three is the
  order in which the script tag will be placed relative to other
  scripts, i.e. core scripts first, then module scripts and finally
  theme scripts.

  If the second parameter is 'setting', then the first parameter must be
  an array of settings. This is very handy for telling JavaScript about
  the configuration settings for your module, for example, and is
  explained in more detail in the next section.

  The final possibility for the second parameter is "inline" and this
  means you are passing in straight JavaScript code as your first
  parameter, which you want written directly to your page between script
  tags, rather than a call to a file.

  These two are the most important parameters for this function - indeed
  you may never even use the second one if all you ever want to do is
  add a js file for your module - but you can learn about the other
  parameters by reading this function's documentation at api.drupal.org.
  Adding JavaScript from within a module

  So, let's say you have written some jQuery code that targets some of
  the elements that are output by your module or theme. You simply need
  to save your jQuery code as a JavaScript file (i.e. with the .js
  extension) and place it in your module or theme's directory. If it's
  for a module, you then need to make the call to drupal_add_js() as
  above, from wherever the module is about to output content (e.g. in
  hook_block or hook_nodeapi), or if the JS is not acting on content
  output by your own module you can call it from hook_menu or hook_init.
  Note, that putting this file into hook_init means it will run on every
  page request, whether needed or not. Here is how you would ensure the
  file gets added:

  The jquery.js file is included automatically so you don't need to
  worry about adding it.

  To add JS (or CSS) file from form builder function the recommended way
  is to use Form API #attached property as below,

  See Form API reference for more details. Adding JavaScript from within
  a theme

  Adding JavaScript to a Drupal 8 theme With drupal_add_js (Drupal 6 &
  7)

  (drupal_add_js is deprecated in Drupal 8; use '#attached' instead.) If
  you are adding your .js file from within a theme, then you simply need
  to make the call from within template.php, you need to add the second
  parameter this time as 'theme' so that Drupal knows this script should
  be loaded after all core and module scripts are loaded:

  <?php drupal_add_js(drupal_get_path('theme', 'mytheme')   .'/mytheme.js'); ?>

  Using the theme's .info file (Drupal 6 & 7)

  You can add your script path in the .info file of your theme and
  Drupal will include them automatically. name = My theme description =
  Theme developed by me. core = 7.x engine = phptemplate

     scripts[] = mytheme.js Using a preprocess_page function

  To conditionally add js to the theme, you can use a process_page
  function:

 <?php function mytheme_preprocess_page(&$vars, $hook) {   if (true) {
     drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
     $vars['scripts'] = drupal_get_js(); // necessary in D7?   } } ?>

and according you comment your js will be something like

I try to include a jQuery in the body of a content type, as shown in the image below:

enter image description here

The purpose of this jQuery is to hide a div with id="test", so that the text aaaaaaaaaaaaaaaaaaaa in it is not shown.

The jQuery was added to the content (saved in it), but yet I still can see the aaaaaaaaaaaaaaaaaaaa and my js did not run.

Seems like Drupal JQuery.js file is not loaded, so how can I get it loaded?

(function($) {
$(document).ready(function(){
$('#wrap').hide();
});
})(jQuery);


Drupal 7 Syntax Highlighter not applied when logged in as user or admin I have a Drupal 7 website.
I installed the syntax highlighter module and downloaded the library.
I was very careful following instructions when configuring the module. I also configured it to get the "insert syntax highlighter button" when using the ckeditor library through the wysiwyg module. Yet, the highlighting is only applied when I preview an article. If I do save that article, the highlighting is gone. Then if I logout, it is applied as an anonymout user. So my question is... Is this normal? I've been trying to fix this for hours but no luck.

Well, since nobody seems to want to answer my question, I will provide my solution to the problem. As I have discovered. Drupal do not load all javascripts, go figure why.

So, what I did is go to the admin panel. In configuration/performance you can aggregate all javascript files into one big file which apparently helps minimize server requests. When I did that, it worked. The syntax highlighting is now applied all the time, with a nasty side effect.

I got my code-hightlighting effect working but now, the wysiwyg shows up in comment's textarea field with a background that matches my websites... How unfortunate!


Language detection by domain breaks ajax requests over https What do I have:

Drupal 8.6.2
Domain Access
Language modules
Cloudflare with https

Problem:

If in URL language detection option (/admin/config/regional/language/detection/url) I have "Path prefix" - everything works fine.

Party starts, when I change it to "Domain" - every ajax request on any subdomain is trying to get through http instead of https and I can see "mixed content error" in console, so these requests are being blocked and website is malfunctioning. I cant use views propeerly, upload files through Plupload, use autocomplete forms, change some settings etc.

If I change it back to prefix - ajax works great again.

For prefix I have site.com for default language and site.com/en - for english. For domain setting: site.com - default and en.site.com is english version.

In Domain Access settings I've tried to set all possible URL schemas (http, https and variable) - no change. In Cloudflare settings I have speacial rules, redirecting every request from http to https (I set up CF's https for dozen of websites, I know how to do it).

If I set back to prefix and go to en.site.com (it still works as an alias for the main domain) ajax works fine, so this is not something about server or background settings - it's just Drupal messing around.

I could run it with prefix, but for SEO purposes it is better to use subdomain, because website is going to be big and it is better to separate languages technically on different websites, search engines will rank these subdomains more correct.

Please help! This is my first experience with multilingual website and I don't have a clue what to do.

The problem is the CDN, which connects to Drupal via HTTP and to the client via HTTPS. Then all absolute URLs generated by Drupal have the wrong protocol. Not only this one for ajax, which is absolute because you've switched language detection to domain based. Prefix based it uses relative paths and then the protocol doesn't matter.

Normally CDN's add a header X_FORWARDED_PROTO to the request, which Drupal can use to determine the correct protocol. For this to work you have to configure the CDN as reverse proxy in settings.php.


Drupal 7: How to insert site's Main Menu and also use my custom style on it? I've a menu like this-

About Us

Artists

Works

Dolore ipsu

Consecte

Dolore ipsu

Consecte

Elit Conseq

Elit Conseq

Blog

Contacts

There's a whole section of CSS style information for that plain HTML section.
I've tried to add the site's Main Menu to page.tpl but it isn't showing up When I add the following PHP code-

<?php
    $menu = menu_navigation_links('menu-main-page');
    print theme('links__menu_main_page', array('links' => $menu));
?>

What am I doing wrong here?

Also when it DOES show up, I'd like to which elements are printed exactly when trying to include the menu and how to assign the generated ul / li to some classes, as required for the CSS to apply style to those elements?

In Bartik, menu is added like that:

    <?php if ($main_menu): ?>
      <div id="main-menu" class="navigation">
        <?php print theme('links__system_main_menu', array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu-links',
            'class' => array('links', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#main-menu -->
    <?php endif; ?>

Except the fact that $main_menu was not provided in page.tpl.php nor in template.php, apparently created by menu module, it looks like your code, just more elaborate. This indicates that either in menu_navigation_links or in theme you passed an argument that happens not to work. Except that it should be all right. Use dpr() or var_dump() to see which one fails.

If you need better control over your menus, I suggest using Menu block module to put them. This module allows you to treat menus or their parts as a blocks, so in your template all you need to do is to output proper region.

To get classes on menu items, you can simply use Menu attributes module:

  The module currently allows you to set the following attributes for each menu item:

  Id
  Name
  Target
  Rel
  Class
  Style
  Accesskey


commerce_cart_order_load not working for anonymous user in drupal commerce I have created an order programmatically, the order is created and shown in backoffice order listing, but most of the time in the cart it shows empty.When I checked I found that commerce_cart_order_load for anonymous user return false.

Please help me to find the solution.

Here is the code on submit function i have written :

global $user;
$product_id = $form_state['input']['product_id'];
$quantity = $form_state['input']['quantity'];
$audience = $form_state['input']['audience_id'];
$material = $form_state['input']['material_id'];
if ($product = commerce_product_load($product_id)) {
  $threshold = $product->field_threshold_quantity['und'][0]['value'];
  if(is_numeric($threshold) && $threshold != ''){
    if($quantity >= $threshold){
      $box_code = $product->field_box_code['und'][0]['value'];
      $product->sku = $box_code ;
      $quantity = 1;
    }

  }
  if (!commerce_cart_order_session_exists())
   {
                $order = commerce_cart_order_new();
               $order->log = t("Created by checkout page.");
               commerce_cart_order_session_save($order->order_id);
     }
  // Attempt to load existing order for user from session
   $order = commerce_cart_order_load();
    if(!$order){
      $order = commerce_cart_order_new($user->uid);
    }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;
  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  //uid of the logged in user
  $uid = $user->uid;
  $line_item = commerce_product_line_item_new($product, $quantity);
  $line_item->field_line_item_audience['und'][]['tid'] = $audience;
  $line_item->field_line_item_item_type['und'][]['tid'] = $material;
  $line_item_added = commerce_cart_product_add($uid, $line_item, FALSE);
  //$order_wrapper->commerce_line_items[] = $line_item;
  commerce_line_item_save($line_item);
  if($uid  == 0 ){
      commerce_cart_order_session_save($order_id);
  }
 //
  // Save new line item to get line item id

 // Add line item to order wrapper
//

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

Every thing is ok,I had the same problem after spend a half night I found that sometimes drupal dont start session for anonymous users then you should start it manually if begin of your function

   drupal_session_start();


settings.php after migration I transferred my files via FTP and database to a hosting service. I edited two files, settings.php and sites/default/settings.php whose content was originally the following.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'db',
      'username' => 'loginname',
      'password' => 'passwd',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

I changed the database name, username, password and host (to yes.domainname.com) in both files.

There is probably something wrong because I get this warning.

  Warning: Cannot modify header information - headers already sent by (output started at /web/www/yes.domainname.com/sites/default/settings.php:1) in drupal_send_headers() (line 1044 of /web/www/yes.domainname.com/includes/bootstrap.inc).

Do you know what is wrong?

Verify that there are not extra characters at the beginning of the file, right before the <?php part; this would cause the error you have seen.
Sometimes the editors add the BOM (Byte Order Mark) when saving an Unicode file; verify Unicode is not the text encoding used to save the file, or that the editor is not set to add the BOM to the files it saves as Unicode.
The BOM characters are not normally visible in a text editor; if the editor has the option to show characters that have a specific code, or "invisible characters," that can help to notice them.

Alternatively, the file got corrupted when transferred.


How should I include an image field from a taxonomy term in a node view? I'm creating a site with just one content type sorted in three categories and posted by three different organizations (no matter in which of the categories). The front page has to be three columns displaying the content of each category.

The nodes has to be distinguished by the logo of the organization. I'm trying to solve it by managing the organization as a taxonomy and creating an image field for each organization/term; when I deal with the view, I find that I just can use as field the name of the taxonomy and not the image (creating a view of node type of course).

How can I achieve it?

If you're using Drupal 7 then you will have to add a "Content: Taxonomy terms on node" relationship before attempting to add the term image field. When you add the relationship then in the Fields section you will be able to choose term fields (like the image field of your terms) to display them in your content view.


Unable to index field in Search API settings in a commerce site In my product display content type, I created a new image field and am aiming to show that in a view among other things. I after long research found out that I have to enable indexing of a field before I can use it in a view. However, this new field is nowhere to be found on Search API settings. Where else can I look?

Best,
mto

If you go to admin/config/search/search_api, then I guess you could see a server of type "Index".
Click on the Edit link against that and go to the "fields" tab(admin/config/search/search_api/index/product_display/fields).
Enable the checkbox against your new field and save.
You will have to index the whole content, which you can do by click the view tab and clicking the "Index Now" button.
I guess this would do.


WebForm images not displayed after node creation with submission handler I'm at a loss.

I'm using WebForm 8.x-5.2 on Drupal 8.7.3. I have a custom webform handler that takes the submission and creates an unpublished node for review. The webform includes an image field that saves one or more images submitted through the form in the Private Files area as suggested.

Everything in my submission handler works as expected except for the images. Upon viewing the page created by the handler, the images are not displayed. The images are there. If you simply edit the node in the UI and save it, the images show up. I've tried a bunch of things, without success...

Saving files to the public files directory
Adding code to the handler to save the node a second time
Adding code to the handler to make a change to the Title field after saving and then saving again.

Inspecting the node with Devel before and after the manual edit/save shows no difference that I can see. Here's the relevant code snippets...

$values = $webform_submission->getData();
if (!$webform_submission->isDraft()) {
  $node = Node::create([
  ...
  'field_image' => $values['image'],
  ...
 ]);
 ...
$node->save();

My submission handler is setting taxonomy terms, multiple fields, URLs, and everything is working except for the images. What am I missing?

I would agree with cchen - you need to use the URI of the image to print it - and I'm not sure 'field_image' => $values['image'] would work in this case.


Include dynamic tagging in drupal7 I just like the way the tags work out in stack exchange communities.  The way it gets description for each tag in a dropdown and key based tagging.

How come it works?? Do we need to use jQuery???

I just want to know whether these kind of tags can be developed in Drupal 7

Is there any module in Drupal 7 to make our tags appear like the one shown in the above image.

Drupal out of the box supports taxonomy and tagging using autocomplete. You need to create a vocabulary and add terms to the vocabulary.

Create a term reference field and choose widget as autocomplete.

Regarding making it look alike above you can consider this post.


How to add multiple havingCondition with OR operator? I want to add havingCondition with OR operator

In normal sql query my having conditions are like:

group by n.nid
having comment_count!=0 OR viewed_count!=0 OR likes_count!=0;

With adding multiple havingConditions like:

$query->havingCondition('likes_count', 0, '!=');
$query->havingCondition('viewed_count', 0, '!=');
$query->havingCondition('comment_count', 0, '!=');

but It gives having condition with AND operator

Can any one please help me in.

Create OR conditions separately, in a variable, and then just use them:

$or = db_or()->condition('a', 0, '=')->condition('b', 0, '=')->condition('c', 0, '=');
$query->havingCondition($or);

For more details, read db_or documentation on Drupal API page. This should always be your first place to go, before you ask API-related questions.


How to make content of a (cck) field visible when pressing a button? I am working on a Drupal 7 website and I would like to create a node where a specific (cck) text field is only shown to the users after they press a button.

The effect I would like to achieve is exactly the same you can find in the Careers 2.0 website where, at the end of each job post, there is a button titled "Find out how to apply". When you click on this button the "how to apply instructions are shown". To see how it works you can check http://careers.stackoverflow.com/jobs/10860/foursquare-software-engineer-scala-lift-foursquare?campaign=Featured.

Can somebody please help?

Thank you so much!

The best way to do this is in the theme. Simply add the CSS and JS needed for this effect. Should be pretty simple as all fields has unique ids.


Multiple choice question creation change checkbox to radio Using quiz module, I am creating Multiple Choice question. In that there is a check box to select the correct answer. Check box enables users to select multiple answers for a single question, but I want the users to select only one answer for a question. Is there any configuration to change that or can I change the check box to radio button. If so how can I change it to radio button? Should I change it in code base or is there any module available?

If I'm not mistaken, as long as you don't check the "Multiple Answers" option in the answer settings tab, your answers for that question will render with radio buttons on the front-end. This doesn't change the checkboxes to radio buttons when you are editing a question, but that's because you are supposed to be able to mark multiple correct answers for each question, if need be.


How to use tokens in a filtered text field In Drupal, when you create a field, there is the option "Text Processing". You can select either "plain text" or  "Filtered text".

When I create a field with "Filtered text", I am unable to use it as a token.

For example, on my content type "content_page", I have a long_text field called "intro_text". The "Text Processing" is set to "Filtered text".

If I use this field as a token, it just won't work. This happens in a variety of modules including Meta Tag and Path Auto.

Even if I set the text format in the token, it still does not render. (e.g. [node:field-intro-text:plain_text]).

If I change the "Text Processing" to "Plain text", it works, so the problem lies with "Text Processing".

How can I get the token to work when it set to "Filtered text"?

I am using this module Token Insert Text

Perhaps you need this to get it to work. (I know my version is outdated, I did this a long time ago)

Then go to admin/config/content/ckeditor/edit/Advanced and under EDITOR APPEARANCE

Scroll alway the way down and click save.


How can I set up Protected Pages so users only have to log in once? I'm using the Protected Pages module to make an area of the website - which is about 13 pages - password protected. The problem is that users have to enter the password to view every page rather than being able to enter the password once and then being able to see the entire section of the website (the members portal).

I had only one thing in the list of password protected pages which was /members which is part of the url. Every page that is supposed to be password protected has a url of website.com/members/pageName but that didn't work because anyone could just put the url straight into the browser and the page would should up without having to enter the password.

So, i added all 13 pages to the list of password protected pages but now users have to enter the password on every page.

We have two menus on the site. The public menu and members menu. When a user logs in to the members portal the menu changes and when you select a page from the menu, you have to enter the password every time, but we want it so users only have to enter the password once and they can see all the pages in the members portal.

How do I set that up?

Protected pages is really intended for one off password protection of webpages on a site. In order to have users login once to access a section of content, you should setup a user role assigned to a specific content type.

In the case where your existing content requiring authentication is the same content type as the non authenticated content, you can use the TAC Lite (taxonomy access control lite) module. To restructure the existing site to use this:

Create a new taxonomy to distinguish the password protected nodes from the others
Assign your custom term to the nodes to distinguish that they need authentication to view.
Install TAC Lite module.
Setup a new user role to associate with viewing permissions for the nodes with the assigned term.
Configure TAC Lite for the node type with term and user role.
Remove protected pages passwords for the given pages.
Clear caches
Test accessing (without login, you should see permission denied messaging)
Optionally, install r4032login module to automatically direct nonauthenticated users trying to access this section to the login page, and subsequently redirect back to requested url.

For future site builds or enhancements, I would recommend just setting up a distinct authenticated only content type and installing r4032login.


Perform action on logout, I would like to add javascript on logout. I tried using hook_user_logout but the javascript doesn't get added.

Even adding something as simple as drupal_set_message doesn't result in a message  being displayed.

I know the hook is firing because I can add a watchdog message in the hook and see it in the logs. The watchdog message is about the only thing I tried that DID work.
Curious about other options that may or may not have results, I tried looking at Actions and Triggers and Rules. I basically decided to try to do something simple on logout, like add a message. But even those modules don't work! I was actually really suprised when Rules didn't work.

I can add messages and do actions elsewhere. Has anyone else had problems with hook_user_logout? And does anyone know if it is possible to add javascript with that hook?

Is this some sort of problem involving drupal_goto? Hmmm.
I am on the verge of just adding JQuery to every page to check every link to see if it is a logout link and then adding a click event. It will work for my purposes, but it is such a hack. I would prefer not to.

Even adding something as simple as drupal_set_message doesn't result in a message being displayed.

That's the  expected behaviour - in the logout hook, you're still inside the authenticated user's session. Once they're logged out, you're not any more. So messages intended for that user are no longer there, because that session has been destroyed.

You should implement a logout/token expiry resource in your API, and invoke that in the logout hook. Then you don't need to remove the token held in local storage, as it will not be valid any more.


in views row-template, how to obtain rendered output of each item in multi-valued field? I have a custom row template, and I know I can obtain the rendered field output with:
$field_output = $view->render_field($fieldname, $view->row_index);

For a certain multi-valued field, I would now like to create an array of the rendered output of each item in the field.
$field_output[3] = rendered field output for 3rd item in my multi-valued field

Anyone know how I can do this?
UPDATE:
There are two approaches I am aware of, but neither is a good, robust solution.
Approach #1:  get_values()
One approach is to call get_values, and then grab the safe_value:
$vals = $view->field[$fieldname]->get_value($row);
$field_values = array();
foreach ($vals as $i=>$v){
  $field_values[$i] = $v['safe_value'];
}

The problem with this approach, as described here, is that (a) it breaks localization and (b) some fields do not have a safe_value.
Approach #2: render_field()
The second approach (see below) uses render_field() and then explodes the result:
$field_values = array();
$field_output_str = $view->render_field($fieldname, $view->row_index);
if (!empty($field_output_str)){
  $separator = ',';
  $field_values = explode($separator, $field_output_str);
}

The problem with this approach is that, in addition to exploding multi-valued fields, it also explodes individual fields that contain commas, such as text fields.
Does anyone have a better, more robust solution?

If the field is multi-valued, then $view->render_field($fieldname, $view->row_index) returns a comma-separated string of the individual rendered items:

rendered_item0,rendered_item1,rendered_item2,...

To generate the array $field_output_array where $field_output_array[2] = rendered_item2, explode the string:

$field_output_string = $view->render_field($fieldname, $view->row_index);
$separator = ',';
$field_output_array = explode($separator, $field_output_string);


Programmatic filefield value/Default Filefield value I have a module that takes a file uploaded to an entity, changes it and then saves the new version on my server in a folder based on the user id and entity title.

$where = 'private://' . $user->uid . '/';

This is all working fine.

I would like to have a field on the entity that displays this new file (it's an audio file).

I have tried writing the process of attaching the file into the module itself several times but have had no luck.

My next idea was to have Rules do this for me but unfortunately when it comes to setting the data value for a filefield Rules will not let you use PHP or Tokens so all I can do is set it to the value of an existing filefield.

My third idea was to have the entity's field have a default value and use tokens that reflect the location of the file e.g [uid]/[title] but filefield does not allow default values.

I have also tried writing a module that updates the entity field values but I can't seem to get this to work either.

Does anyone have any ideas on where you go from here? Does anyone know how this can be done?

The new version of the file should be saved as a managed file. This will provide a file object that has a fid which in turn can be used by the file field.

Here are the docs for the function used to save a managed file.

https://api.drupal.org/api/drupal/includes%21file.inc/function/file_save_data/7

The value for a file field contains the following

fid - The fid property of the file object returned by file_save_data.

description - The description may be used as the label of the link to the file.

display - Determines whether a file should be displayed when outputting field content.


How to create a content-type with "sub-pages" that are default and/or custom per node I'm in the process of planning a Drupal 7 site-build that will make use of what we're calling 'sub-pages' or 'minisites.' Essentially, as you can see in the wireframe below, we'll have a page for each Doctor, and each doctor page will have a sub-nav.

Here are some requirements;

This sub-nav will link to pages with the url structure 'doctors/[doctor-name]/[sub-page-title]'.
Sub-pages like 'Biography' are populated via fields on the node.
Sub-pages like 'News' and 'Case Studies' are populated via contextual Views (based on references from these content types).
Sub-pages like 'Community' are completely custom and unique to each doctor. Another doctor may have a 'Family' sub-page instead.
The header above the sub-page should stay the same on every sub-page.
Content managers should be able to easily add additional custom sub-pages.
The site is being built utilizing the Panels suite (Panels Everywhere included).

What's the best way to accomplish this? I've fielded suggestions like 'use the Book module', but I wanted to get some feedback from the larger community before I start down a path that leads to a "90% solution."

Update (Includes my solution)

I've decided to pursue the Organic Groups route, as OG and its suite of modules have value in other areas of the site's architecture. In order to meet my requirements I've had to introduce a few additional modules (benefits included);

OG Menu

Configured to automatically create a menu for each 'Doctor' (an organic group).

OG Menu: Default Links (Submodule)

Configured to provide default menu links to views standard for any Doctor. When a Doctor is created, they'll automatically have menu links like 'News' and 'Case Studies'.

Rules

When my content managers create a new Doctor Page (organic group content to the Doctor Group), I made a custom rule that adds a menu link entry to the referred group menu (provided by OG Menu).

Sub-pathauto

We want URLS that are aliased to match the pattern 'doctors/[doctor-name]/[doctor-page-title]'. This modules lets me do that easily (doctor/[node:og_group_ref]/[node:title]).

OG Role Override

I need all content managers to edit and assign content to all Doctor groups. This module lets me do that easily.

Panels

General layout, but also overriding layout for Doctor Pages and default links that direct to views.

All-in-all, I have exactly what I need and didn't write a line of code.

Update Nov 16

This feature was sent out to pasture. Sad Panda. :`(

Everything you've described is done by OG (Organic Groups).

OG is originally designed for GROUPS to have 'private' sections of a website, or to manage how groups manage different parts of a website, but the side effect of that allows you to build highly contextual "sub sections" of a website just like you're describing.

All of the 'contextual' stuff you mention.   Site side branding, sub section branding,  site wide menus, section based menus.  Are covered by OG.

Good luck!


Database log messages (auto cleaning) with keeping exceptions I can see that the Drupal has a settings about logs to keep, but when some amount is configured, so after X logs, the oldest are deleted.
Is there any option to make some logs not to be deleted?

Under Database log messages to keep, there is an All option to keep all logs.  However, there is no option to selectively delete logs automatically in core.
There are two things you could try instead:
First, the Recent log messages screen is a view.  So, if you have the Views UI module enabled, you can edit the log messages view to create a new view mode (for example, a separate page) and then customize the configuration on that page to only list the types of log messages you want to automatically delete.  You can then trigger this manually at whatever interval you want.
Another option would be to use the Logging and Alerts module to store the logs you want to keep forever by copying them to email, SMS, or some other server.


How can I preserve nids during a migration? I'm writing a migration using migrate/migrate_d2d to import nodes from one Drupal 7 installation to another.

Currently there are a lot of links on the web that point to articles using the example.com/node/[nid] url. Since the site I'm importing to will eventually replace the current one, I need to make sure those links still point to the correct articles.

How can I preserve nids during the migration, so that the old links that use /node/[nid] still point to the correct articles?

Alternatively, how can I easily make 500,000+ URLs to old nids redirect to their newly migrated counterpart?

This is actually easy to do. In the prepare() function of the node migration class, just set the nid and is_new to true:

public function prepare($node, $row) {
  // Preserve old nid so that old links to nodes using /node/nid still work
  $node->is_new = TRUE;
  $node->nid = $row->nid;
}


Disable field on hook_form_alter I have a form that I want to render with a disabled field.

I've already tried:

$form_element['#node']->field_assoc_cnpj[0]['#attributes'] = array('disabled' => 'disabled');

And also to use it directly into the form array:

$form['#node']->field_assoc_cnpj[0]['#attributes'] = array('disabled' => 'disabled');

Nothing seems to work.

How can I do that?

In simple terms, CCK is yet another module that alters the forms. When your form_alter function is used, even if you disable the field, it will not work. That's because the CCK forms are built after those form alter functions.
Note that this limitation is only for Drupal 6. In Drupal 7, it should work with regular form_alter functions.

I had to do this on a client site. This page from Drupal docs helped me a lot.

See Clive's answer. It's how we do it on regular forms.
But don't forget that you always can use field permissions which is much more robust than form alters.

Also, note that setting the field's disabled attribute means this field will not be submitted by browser. If you want to get the value back to your site, use read only attribute with some fancy css to make it look like disabled (browser will take care to not allow editing). Chuck Norris can hack the page using Firebug or something to change the content though.


Drush needs a higher bootstrap level to run Do you have any idea on what might be causing this error when I execute:

drush si geoslate --db-url='mysql://root:root@localhost/geoslate' --site-name=Geoslate

  Command site-install needs a higher bootstrap level to run - you will need to invoke  from a more functional Drupal environment to run this command.
  The drush command 'si vimn_geoslate' could not be executed.
  A Drupal installation directory could not be found

?

This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.


Dynamic Taxonomy Filter dropdown with childs in Drupal 7 For a while I'm trying to sort this but no luck

I need exact same filter like here http://www.pets4homes.co.uk/

I have pet types as taxonomy terms and breeds as child`s. I want to accomplish same thing like on that website, when I select dogs I want just dogs breed to be on second dropdown. Location is not needed but if you know the way to add it even better, but now I'm focusing on dropdowns.

Already I tried with Simple Hierarchical Select module and Hierarchical Select but I just can't set it up to work like I want, or I don't know how to set up it properly.

With SHS module  I have one dropdown with pet type and when I select it than other dropdown shows up, but I need it to be all the time there, and that is not possible with this module as I read it in issues of that module.

You need to use Ajax and the drupal form api to build this type of search form.

I recommend looking at the Taxonomy Edge module to make "finding the children terms of some parent" really easy, because the SQL can be annoying. Then you can just focus on the Ajax needed. Drupal has great support for Ajax!

I recommend looking here on drupal.stackexchange to find ajax examples of which there are plenty. I'm nearly positive there is an example of this type of ajax "update the form with some new options or div" in the Drupal 7 Developer Examples module.


Symlink inside profile I forked a repo from a third party development team that I am taking over for, and inside the "profiles" folder is a file just named foo.

When I open it, it as this ../../foo and nothing else.

Is this a symlink to the install profile?

There is an install profile, just not in the docroot folder, it sits outside of it with the grunt and build files.

If so, is there a difference on how Nginx and Apache handle symlinks?  They used a Nginx server to develop and I'm using Apache.

Thanks everyone.

It is fairly common practice to use symlink on web server. You might also see it on your private folder so that I can be hosted on a NAS or AWS EFS for example.

Symlink should work regardless of the web server you use as they are specific to the server operating system and not to the web server by itself.


How to use Simple hierarchical select on a view starting at second level taxonomy? I am using the Simple hierarchical select on a view for a an exposed taxonomy term, but I want the first level of the taxonomy to be preselected, so that the user can only choose the second and third levels.
I tried to do this by adding jquery to change the first element, but it doesn't load the second level taxonomy then.

Is there a parameter in this module so I can preselect the first level taxonomy term and not let the user change that?

I made a patch to allow you to choose the parent taxonomy at a level lower than the root. I will post a link to it soon .   If anyone wants to ask me about it in the meantime please write to me.


Display 0 if no results from view I have created a view to show users their uploaded content. It works well enough. Now if the user has not created any content then the view should output 0 or some custom message.

In earlier versions, there used to be a Empty Text field under Basic settings. I am using Drupal 7 with the latest Views.

So after some searc, I found it should occur under "No Results Behavior" in "Advanced Settings" but I do not seem to find an empty text there. I found "Global text" so there I write my message, but it does not display anything if the view is empty.

Do you have any suggestions?

Click on NO RESULTS BEHAVIOR on the right side.

Add a Global: Text area

Enjoy...


Is there a printed map / tree / graphic of a sample array(s) during each phase? This is a larger question to help me better visualize the Drupal array structure at each 'stage' of the life cycle. I'm looking for material to help me see what's happening behind the scene that center on the array structure exposed to the various hook calls.

Does anything exists in this fashion? I guess something could be pieced together by examining the APIs, but at it's core (version 7 at least), Drupal is about letting various components authored by different individuals to flexibly alter array(s) before their final HTML render.

Devel is a good place to start. That will make the function dpm() available to you. This will allow you to print out arrays in an extremely user friendly visible way. If you're doing any sort of development you should really look into this module. I know when I'm trying to figure out what's being called for a given area I often use the combination of dpm and debug_backtrace.

There's also a theme developer that relies on Devel that you can you to see a back trace of functions.


Add a Block ABOVE view I need to add short descriptions for some 20+ views and display them above the views. I know I have an option to add a header to a view, but that's not what I want. I have a sidebar on the left and the main content on the right which displays views on the views pages. I need to add different descriptions for my views ABOVE both sidebar and main content.

How do I achieve it?

Yes. The thing is, I need different content in this block depending on
  the current view. So I'd need to create 20+ different blocks for each
  of my views which seems redundant. I'm sure there must be more elegant
  solution.

Create a block and use template_preprocess_block to alter the content based on the path. In your theme's template.php add:

mytheme_preprocess_block(&$vars) {
  if ($vars['block']->bid === 'target_block_id') {
    $path = current_path(); // gets the current page path.

    switch($path) {
      case path1:
         $vars['content'] = "Hello World";
         break;
      case path2:
         $vars['content'] = "Hello Kitty";
         break;
       // ... and so on and so forth.
    }

  }
}

Note: replace mytheme with your actual theme name, same for 'target_block_id'.

Another possible option, would be to add a header to your views, and then just use CSS with absolute position to move it, this would mean you'll need to add some padding-top: or padding-bottom on some other div to create a space for it.


Left and Right region is not showing on ZEN sub theme I've been working right now on a custom sub theme via ZEN for a certain Drupal site. I had it first developed in my localhost. Right after I had the half of the basic design implemented, I uploaded it immediately to the site and had it enabled. Now, something is wrong. The two regions are not showing up when I tried to view them on the block administration page. Even if I put a block on each of them, still they don't display on the page... what could it be?

In my localhost, it's working fine. I'm not sure why it's not working well on the live site. Has anyone of you experienced the same issue? Any help or suggestion is very much appreciated.

thanks in advance.

I finally found the solution for this problem. That is the put 'zen' folder under the same location of the sub-theme folder. Actually, the site I've been working on is a multi site setup and there is also an entity there that is also using zen as it's theme. I thought putting just my sub-theme is enough since the site still recognized the main theme, which is Zen.

The reason why the two region of the theme I uploaded is not being recognized, is because it's info file is not being read properly. The info file that is being read by the site is found, on the other zen sub-theme I mentioned above.


Custom block with a field value that can be used in other twig template I am creating a custom block with fields:

field_items_to_show (items to show)
field_logos (images, multiple)

The site editor must have the option to set the amount of items to show in a field.
in the twig field template field_logos I need the value from field_items_to_show

            {% for item in items %}
            {% if loop.index == 9 %} // this value must be set from field_items_to_show

            {% endif %}

{{ item.content }}

            {% endfor %}

In a field template you find the parent entity in the variable element['#object'], from where you can get field values of other fields:
{% set field_foo_value = element['#object'].field_foo.value %}


Hide or disable node fields I am using drupal 6 and i have created my own content type and few CCK fields. When user is creating a node, i don't want to show him fields like menu settings, revison information, and many others, is it possible in Drupal 6.

The access to menu settings/revision information, etc. is controlled by permissions. For example the user will require 'administer menu' permission in order to choose what menus their content will go in.

You just need to find the permissions the relate to whatever task you're trying to deny access to, and make sure the users in question don't have that permission (at http://mysite.com/admin/user/permissions).

Failing that, you should use a hook_form_alter() function in a custom module, and set the field/fieldset #access to FALSE:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['the_field']['#access'] = FALSE;
  }
}

In case you need to control access to certain CCK fields that you've created, the Field Permissions module is available for Drupal 6 and Drupal 7 and will do just that.

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


Create field collection item in drupal 7 I am trying to dynamically create a field collection for a node.

Field collection item (field_markers) is used to create a point or a polygon for a map content type.

During debugging I found that my code create an entry for all the member elements of field collection but it does not create or update a record for field collection itself.

I have referred to https://stackoverflow.com/questions/6242018/dynamically-add-a-field-collection-in-drupal-7-by-script but was not able to resolve my problem.

Following is my code so far.

//Create field collection
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_markers'));

//Create fields related to field collection
$field_collection_item->field_title['und'][0]['value'] = "Brian 22";
$field_collection_item->field_summary['und'][0]['value'] = "Test entity creation.";
$field_collection_item->field_summary['und'][0]['format'] = "filtered_html";

$lat = -35.3241665257384;
$lon = 139.8046875;

$field_collection_item->field_coordinates['und'][0]['wkt'] = 'POINT ('.$lon.' '.$lat.')';
$field_collection_item->field_coordinates['und'][0]['geo_type'] = 'point';
$field_collection_item->field_coordinates['und'][0]['lat'] = $lat;
$field_collection_item->field_coordinates['und'][0]['lon'] = $lon;
$field_collection_item->field_coordinates['und'][0]['left'] = $lon;
$field_collection_item->field_coordinates['und'][0]['top'] = $lat;

$field_collection_item->field_coordinates['und'][0]['right'] = $lon;
$field_collection_item->field_coordinates['und'][0]['bottom'] = $lat;

//attach field collection to map content type
$field_collection_item->setHostEntity('map', $node);
// Save the entity.
$field_collection_item->save(TRUE);

I found the problem, it was related to the workflow of content publishing (specific to my site ). Field collection item is created after a user with required permissions approve the content.

The code in question works and could be helpful for anyone else trying to create a field collection item containing a geofield.


How and where would I be able to enable/disable gzip compression? In Drupal 7 where would I be able to enable/disable gzip compression? Is there a module for this functionality?

Personally, I do not like the way Drupal handles output compression; I take care of this outside of Drupal.

On the Drupal site, I add

$conf['page_compression'] = FALSE;
$conf['css_gzip_compression'] = FALSE;
$conf['js_gzip_compression'] = FALSE;

to settings.php, and this to a custom module to show that this is disabled:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}

This is to also prevent accidental double output compression, which can be very hard to diagnose if you don't know about the symptoms.

Then, in my Apache config, I do

<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>

</IfModule>

This lets Apache do the output compression by MIME type, and also make sure all text based output gets compressed.  This is adapted from an older version of the HTML5 Boilerplate project's .htaccess file, which now lives in a separate project.  I also add in their directives for cache control, and a few other things.  I keep all of this in an individual file, that I then Include in my virtual hosts.

The downside of this is that the server compresses each request, but it works well for my sites and my clients.


Prevent name collisions on form value flattening? The element's name property is declared in the $form array, at the
  very end of the array tree. For example, if an element in the form
  tree was structured like this:
  $form['account_settings']['username'] ?>

  ...then that element's name property is 'username'--this is the key it
  will be available under in $form_state['values'], in your validation
  and submission functions, as the form code flattens the array in this
  fashion before it passes the key/value pairs. NOTE: if you wish to
  have the full tree structure passed to $form_state['values'], this is
  possible, and will be discussed later.

-Source

So, for example, if you have this:

$form['details']['admin'] = array(
    '#type' => 'checkbox',
    '#title' => t('Only admin can view'),
    '#default_value' => variable_get('admin', 0),
  );

You see that you'd be using variable_get('admin', 0);

So what's to prevent naming collisions? Say you have another setting:

$form['more_details']['admin'] = array(
        '#type' => 'checkbox',
        '#title' => t('Only admin can view'),
        '#default_value' => variable_get('admin', 0),
      );

If anyone has a clear explanation as to how this "flattening" works, that'd be great.

While it's good practice to use unique field names in your form, you can use the #tree property to preserve the group nesting of parent -> same child name there.

$form['#tree'] = TRUE;

That will preserve the nesting of group -> field values in the form $form_state['values'] so instead of being flattened it will be

$form_state['values']['details']['admin'] = 'foo';

and

$form_state['values']['more_details']['admin'] = 'bar';


Workflow, Multistep, and "Save" vs. "Done" I have a Multistep node submission form with a couple of behaviors:

The user can save it, leave, come back, and edit it further. Paging between the steps as well as clicking "save" produces this behavior. (This is already implemented)
The user can also submit it by clicking "Done" on the last page. Currently all this does is save it the same way as the "Save" button, but it redirects to a display of the node that was just saved.
The desired behavior for the "Done" page is to "freeze" the node and prevent further editing by the user.

I'd like to use Workflow states or at the very least a permissions-altering Rule to remove the ability to edit the node upon clicking the "Done" button, but not upon clicking the "Save," "Next," or "Previous" buttons. Currently they all do the same thing (save the node) so as far as Triggers, Rules, etc. can tell, it's the same event.

How can I differentiate which button was pressed and use that to trigger a rule or workflow state?

You could use the Button Field module and rules.


Is theme_pager() vulnerable to HTTP Parameter Pollution? I'm currently running vulnerability scans against my application, which is based on Drupal. One "High" vulnerability is HTTP Parameter Pollution (HPP), and it has to do with pages that make use of drupal's theme_pager().

I know that it could indeed be (and probably is) a false-positive, but I need to be able to understand why it isn't a vulnerability so that I can remediate the scanning report. I'm hoping that someone with more security experience than I can help.

The found vulnerability is as follows (I'll use drupal.org in this example):

Visit a url that has a pager on it:

https://drupal.org/search/site/cat

Append a useless query parameter+value to the url such as %26foo%3dbar (or &foo=bar , I'm not sure if it actually matters)

https://drupal.org/search/site/cat%26foo%3dbar

The "vulnerability", as I understand it, is that the pager link URLs (1,2,3,4,etc) all contain the &foo=bar param.

The actual scan output was as follows:

  Vulnerability description This script is possibly vulnerable to HTTP Parameter Pollution > attacks.

  HPP attacks consist of injecting encoded query string delimiters into other existing parameters. If the web application does not properly sanitize the user input, a malicious user can compromise the logic of the application to perform either clientside or server-side attacks.

  This vulnerability affects /.
  Discovered by: Scripting (HTTP_Parameter_Pollution.script).

  Attack details

  Path Fragment input / was set to qui&n950086=v982658
  Parameter precedence: last occurrence
  Affected link: /search/node/qui?page=1&n950086=v982658
  Affected parameter: page=1

  Request GET /search/node/qui%26n950086%3dv982658

So my question is two-fold: Should this be considered a false-positive? How is Drupal protecting itself from HPP?

Thanks!

Simple answer: no, theme_pager() isn't vulnerable to this kind of attack.

The pager functions only use the page parameter and don't make use of any other. As far as Drupal core goes, that argument is used only in the context of a PDO-prepared database query, and so any effort at malicious manipulation of that page parameter will simply fail.

As with anything, careless use of theme_pager() outside of the proper API - e.g. using the associated preparatory functions manually without properly prepared database queries - can result in unwanted side-effects. But the function and its associates aren't inherently insecure, and from a core perspective are used safely.


How to create a list of similar nodes in Drupal 7/Views 3 I face a rather common problem of displaying a list of nodes similar to current one. Similar node is defined as one having at least one taxonomy term that current node has. There are few solutions available as modules, however most modules I've found are in beta stage for Drupal 7.

I've also found a couple of solutions based on Views and contextual filters (such as http://scito.ch/content/show-related-nodes-block-based-taxonomy-terms-views-3-and-drupal-7) or relations. I quite like this way as it saves me installing extra modules and with Views being actively developed and supported I'd prefer to use them rather than any custom solution. The problem I can't get around is how to sort "similar nodes" by the number of terms they share. For example, if I have "IPhone 4S" Node with Terms "Gadget", "Apple", and "Phone", I want similar nodes in the following order:

IPhone 3 (Apple, Gadget, Phone)
IPad (Apple, Gadget, Tablet)
Mac (Apple, Computer)
Bramley (Apple, Fruit, Tree)

How can I sort nodes in this view by the number of terms they share?

For those upvoting and favoriting, I've got the answer here: https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3

It boils down to:

Create a block view
Add Contextual filter -> Content: Nid -> Provide default value -> Content ID from URL
Add Relationship -> Content: Taxonomy terms on node -> specify the appropriate vocabulary
Add Relationship -> Taxonomy term: Content using vocabulary as specified
above -> Check off Require this relationship
Turn on Views aggregation
Assuming you are listing title only, edit the title field to use the Relationship you set up in #4 above.
Add new sort criteria of Content: Nid. In aggregation settings, select Count. Use relationship from #4 and sort descending
Add Contextual filter -> Content: Nid -> Use relationship from #4 -> Provide default value - Content ID from URL -> Scroll down and expand "More" then check "Exclude" to remove current node from the view.


How to add "#main-content" to the link of pager element? I would like to add #main-content to the link of pager element. So, I would get an url like this: http://domain.com/my-views-list?page=2#main-content

Any idea, are there any preprocesses or something like that?

You can use template_preprocess_pager to alter the pager links. You should be able to do something like the following for whatever links within the pager you want to change:

function MYTHEME_preprocess_pager(&$variables) {
  if (some check to make sure its the pager you want){
    $cur = $variables['items']['next']['href'];
    $variables['items']['next']['href'] =  $cur . '#main-content';
  }
}


Problem with specific permissions I would like to set a role permission for displaying a field depending on the value of an other field. But I can't find how to do it.

For example, I have a content type Person. If I add a content Person that is a "policeman" (field Job = "Policeman") then his phone number (field Phone) is display only to user that have the role "Officer". But if the person is a "Secretary" then his phone number is display only to user that have the role "Direction".

Does anyone know how to do it ? Is there a module for that ?

Thanks !

There are 2 modules out there that can do one part of what you're wanting, but not both.

Field Permissions lets you display fields based on role.
Field Formatter Conditions lets you display fields based on the content value of another field.

If your content design is flexible these might help.

However, if you're looking for field display based on both a role and another field's value you might be better off adding a template_preprocess_node() function to template.php to check for rendering logic. For example:

function MYTHEME_preprocess_node(&$variables) {
  global $user;

  $job = isset($variables['node']->field_job[LANGUAGE_NONE][0]['value']) ? $variables['node']->field_job[LANGUAGE_NONE][0]['value'] : '';
  if($job == 'policeman' && !in_array('Officer', $user->roles)) {
    hide($variables['content']['field_phone']);
  }
  //@TODO: Add other role/value checks
}


Assign previous migration destination id in prepareRow Working on migration of 6 to 7 where 2 websites are being merged into one. This is being done using migrate module.

There are duplicate users in 2 source sites and intended result is that the user that exists from the 1st migration should be linked as destination id on the second without being updated.

We already have migrations set up for 2 sites and site #1 is imported.  When importing users from site #2 we want to essentially keep the same user from site #1 and link all content from site #2 to be owned by user from #1.

Can this be done in prepareRow and how ?

In your site 2 content (Node) migration you probably want to use the prepare() function.

  function prepare($entity, stdClass $row)

  The Migration class prepare()
  method is called by the destination class prepare() method, after it
  has called all field-level prepare() methods and immediately before
  the destination object is saved. The $entity argument is the
  destination object as populated by the initial field mappings and
  manipulated by the field-level methods; the $row argument is an object
  containing the data after prepareRow() and any callbacks have been
  applied. The prepare() method is the last chance to manipulate the
  destination object before it is saved to the Drupal database. It is
  important to remember that, since it is called after the field
  handlers, fields will be in their fully-expanded forms (i.e., in
  Drupal 7 a text field value will be at
  $entity->field_textual_data['und'][0]['value'] rather than simply
  $entity->field_textual_data).

Within your Migration prepare function you want to set the UID of the content to whoever you want to be the creator of that piece of data.

As an example:

public function prepare($entity, stdClass $row) {
  $query = /* Query to figure out UID from site 1, from a UID in site 2 ... for current node NID*/;
  $desired_uid = db_query($query);
  $entity->uid = $desired_uid;
}


Problem with image styles : access denied I'm getting a problem with image styles being created. The files are there but the styles are not getting created. I have tried changing permissions recursively on the folder (udo chmod -R 777 /Applications/MAMP/htdocs/geoslate/sites/default/files/)but this isn't solving it. I've tried deleting the styles folder but it doesn't get recreated. There is an error in  the log:

access denied
Date    Wednesday, May 1, 2013 - 11:03
User    admin
Location    http://localhost:8888/geoslate/sites/default/files/styles/thumbnail/public/image-file-name-325x250.jpg?itok=zPXsGtyX
Referrer    http://localhost:8888/geoslate/node/1
Message sites/default/files/styles/thumbnail/publicimage-file-name-325x250.jpg
Severity    warning

It is either you update your Drupal core to the latest version or you You can add the following line to your settings.php to get the images in the site working:

$conf['image_allow_insecure_derivatives'] = TRUE;


Views Rewrite return html string instead of rendering them I am using Drupal 8.1.3 and in simple views I want to use rewrite feature of views, and I put {{ totalcount }} in rewrite section and on out put I see

Where is the problem and why view template engine not render HTML in rewrite section?
UPDATE
Exactly it that views I try rewrite title field and for it works correctly is seems problem is with statistics total view field !!!

I think it could be because of the .... tags part, if you take that out, does it render? Seems like views uses Filter HTML, and only popular html tags are allowed on Custom Fields or Re-Write boxes.

You should be able to achieve your goal by creating a template file.

views-view-fields--[view-name]--[machine-name].html.twig

{{ fields.totalcount.content }}


Can't login: user/login redirects to live site I copied a live site built by a previous developer to my local MAMP environment, and discovered that trying to use /user/login redirected me to the live site. I discovered that .htaccess had numerous dreaded 301 redirects. So, I changed the .htaccess to a clean one, cleared cache, cleared history, rebooted MAMP, tried a clean browser. I think I've now cleared the 301 redirects to regular pages, but user/login still goes to the live site.

Created fresh local install with a clean .htaccess; clear cache, reboot MAMP, etc, still can't login to local.

Is there a backend way to login to drupal? Through drush?

Could that demon-spawn developer have set something else that prevents local login?

If the live site uses HTTPS, implements SSL, try to check if is using modules like secure_pages. This kind of modules sometimes causes that kind of redirections.

Another thing to check could be the settings.php to see if there are something related to this issue.


Filter a view by the Group ID of the current logged in user I have been looking for an answer for 3 days with no success.

Looks like this is a common requirement among plenty of Drupal 8 projects with not a single answer accross the internet about how is possible to achieve it.

I, as user id 1, created 2 groups titled: "Basketball" and "Football" of the group type (sports) and then I added some users as members to those two groups...

So I have something similar to:

Group Title: Basketball

Group Members:

User A (whatever role)
User B (whatever role)
User C (whatever role)
User D (whatever role)

Group Title: Football

Group Members:

User 1 (whatever role)
User 2 (whatever role)
User 3 (whatever role)
User 4 (whatever role)

Now, what I really want to accomplish using views is to show a table with the names of all available members registered at the same group of the current logged user.

So if for example if User D is the current logged in user, I want to show him a table displaying:

User A
User B
User C
User D

without showing up the other members from other groups like user 1, user 2...

and for example if User 2 is the current logged in user, I want to show him a table displaying:

User 1
User 2
User 3
User 4

without showing up the other members from other groups like user A, user B...

Is that possible, and how?

I have followed this issue:
https://www.drupal.org/node/2793631#comment-11613765
but with no success!

And this question How do I show the members in a block, contextually filtered by the currently logged in user?
with no direct solution by using only the views UI.

My aim is to create an entity reference views to be called from a entity reference field element inside a webform.

UPDATE:
This issue (https://www.drupal.org/project/group/issues/2793631#comment-12808833) has a solution
On how to a list of all groups in which the current logged in user is a member.

However, for my requirement I need to show a list of all members that belong to the same group of the logged in user... so I did:

Create a page view and set the content of the view to be Group content with a url: /my-friends
Add a relationship to Group (The group containing the entity.)
Add a relationship to Group content for User (Relates to the group content entities that represent the User.)
Add a contextual filter to Group ID and when the filter value is not available set the default value to User ID from logged in user and the relationship is set to the Group content for User.

For the preview of the view, everything looks good and I, the admin, can see my name inside the display table along with all the other member with me inside the group.

However, if i log in as any other member inside this group such as: User 2 and go to the view page and receive a table with the message: no members available.

I just ran into this today. Found this article and here's the solution I did (only available recently).

I create Content view showing the Content Types that I want. I setup the Relationship to "Content group content" (checkmarking the Content Types I want). I then add a second Relationship to "Group" which is now available (based on the first relationship).

Once the relationships are done, I have access to add a new filter of Group ID.  I can manually enter a group ID number and it works... but current user has not been addressed yet.

Now I install:
https://www.drupal.org/project/token_views_filter
critically, with this patch:
https://www.drupal.org/project/token_views_filter/issues/3038695

I can go back into my Group ID filter and checkbox the "Use tokens".  Now I can access information about the current user via Tokens.

I felt like I should have been able to setup a Contextual Filter for this... but the system didn't allow for it, so this was my work around.


How to display an add to cart button for each product displayed in my views grid? I am creating an online store, for which I am using the Views module (grid) for product displays.

I want a 'Add to cart'-button to appear for every product displayed. How can I do so?

Note: I can display the product, but without the 'Add to cart'-button.

Surely your issue was solved a long time ago, but this could be useful for other people, so in short :

in advanced settings of the view, add a relationship Commerce Product: Referencing Node (Relate a product to the Node referencing it through field_product) with your product type
then add a Contextual filter
(Node referencing products from field_product) Content: Nid

then you're be able to pick up Add to cart form from Add fields menu

Enjoy ;)


limit the number of nodes per User I'd like to limit the number of nodes that an authenticated user can create.
For example users can not create more than One post for specific Content Type. I am wondering how can I do so? Thanks..

The Node Limit module does exactly that:

  The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create.

Among its features are:

  Per-role node limits
  Per-user node limits
  Per-time interval node limits
  Any combination of the above


overriden term name not translated on a taxonomy overriden views page I'm using Title module with Entity translation to translate my taxonomy terms.
I have overridden my term page with a view with term id as contextual filter.
In the contextual filter section, I'm overriding the title view page with the contextual filter %1.
I'm validating the contextual filter by checking if it's a term id.

Unfortunately the title page is not translated. In my case term name displayed is always the one in English.

Just to test further, if I'm adding 2 fields term name and term description to my views. The 2 fields are correctly translated, by switching languages.

Install Internationalization Views module.

then select this,
Advanced > Contextual filters > Content: Has taxonomy term ID (with depth)" > select the validator "Taxonomy term (i18n)"

See here


Layout problems (backgrounds and blocks region) I'm a non professionist dealing with drupal for the first time and it's killing me. I'm trying to create a page without having to code but it seems impossible! I need to adjust the position of the main menu (how can I move the writings to the center?), then I need to put a background, and basically I need very simple assistance to create this web site for an exam, please help me :'(
(yes, i tried to read the guide on drupal.com but it's too difficult for a non-expert

You would have to learn CSS and how to work with themes to do this yourself.

An alternative option, for no code solution, you could use Glazed Builder. However, it's not free, but might be worth the price of admission if you no time to learn how to code.

Important: There is Glazed builder for Drupal 7 & Drupal 8, remember to get the version of the Drupal version that you are using, as the 7 version will not work for Drupal 8 and vice versa.


How to render custom view mode in d7 I'm trying to render nodes with a custom view mode, having another tab for each node in the same place than "Edit", "View", etc. So I have declared my custom view mode with hook_entity_info_alter, my new "tab" with hook_menu, with a page_callback pointing to a custom function that should return the node according to my custom view node.
It works great, but the node title is rendered too. How can I remove the node title ?
Here is the code. Thanks!

   /**
   * Implements hook_entity_info_alter().
   */
   function test_custom_view_mode_entity_info_alter(&$entity_info) {
     $entity_info['node']['view modes']['another_teaser'] = array(
       'label' => t('Another teaser'),
       'custom settings' => TRUE,
     );
   }

   /**
   * Implements hook_menu().
   */
   function test_custom_view_mode_menu()
   {      $items['node/%node/another-teaser'] = array(
           'title' => 'Another Teaser',
           'page callback' => '_test_custom_view_mode_display_content',
           'page arguments' => array(1),
           'access arguments' => array('access content'),
           'type' => MENU_LOCAL_TASK,
       );

          return $items;
   }
   /**
   * Custom page callback hook_menu().
   */

   function _test_custom_view_mode_display_content($node) {
     $node_viewed = node_view(node_load($node->nid), 'another_teaser');

     return array(
              'content' => array(
                'node' => $node_viewed,
              ),
            );
   }

I think you need to render send the element as html out put since there is no any theme function defined. See how this output process here.

So your return array should be:

 return array(
          '#markup' => $node_rendered
        );


Making all REST Server calls to Drupal site as an authenticated user through Services I am making REST Service calls to my Drupal 7 site to either retrieve or create content.

Is there a way I can make all these calls through one specific authenticated user?

Thanks.

You can use jdrupal.min.js. and set variables as follows in your js:

 Drupal.settings.site_path = "http://example.com"; // SET Drupal site Path
 Drupal.settings.endpoint = "services_endpoint_name";  // Set the Service Resource REST endpoint path FROM services module in Drupal site.

and you can use directly functions for for doing operation such as:

user_login(username, password, {
                        success: function (result) {
                          cosole.log(result);
                        },
                        error: function (xhr, status, message) {
                            console.log(status +" Error Message"+ message)
                        }
                    });

If login successful then you are logged in with the authenticated user in your Drupal site. And also you can do number of operations node save, update, delete etc.


Using reverse proxy prevent login flooding I have set $conf['reverse_proxy'] = TRUE; in settings.php, but the IP address logged in the flood table is 127.0.0.1, not the one passed through the X-Forwarded-For header. Nginx is configured to send the X-Forwarded-For header to Apache, but it seems Drupal isn't recognizing it.

This is pretty bad because a few failed logins can lockout for everyone.

How can I make Drupal use the IP passed within the X-Forwarded-For header?

I had to edit the $conf['reverse_proxy_addresses'] = array('a.b.c.d', ...); part, and put in the address of reverse proxy address (127.0.0.1).


How to get delta of a file from within hook_tokens I am trying to create a delta token in my module.
In  hook_tokens, I manage to get the file object, but I have no clue on how to get the delta of my file...

Here is my implementation of hook_token_info

function artprod_token_info() {
  $types = array();
  $tokens = array();

  $types['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );
  $tokens['delta']['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );

  return array(
    'types' => $types,
    'tokens' => $tokens
  );
}

Here is the beginning of my implementation of hook_tokens

function artprod_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'delta') {
    $file=$data['file'];
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'delta':
          $replacements[$original] = $file->delta();// NOT WORKING
          break;
      }
    }
  }
  return $replacements;
}

It's the relationship between a file entity and another entity via a reference field that has a delta, not the file entity itself. A single file could, theoretically, be referenced by many entities, via multiple separate fields, or even twice in the same entity - meaning it doesn't conceptually have a single delta related to it.

What you'll need is to run an EntityQuery with sufficient contextual conditions to narrow down to one result, load up that parent entity, and loop through the field values until you find your file, giving you the delta.

If your use case enforces that a file can only be referenced by a single entity, it'll be a lot easier to implement. But it would probably be safer to include at least some kind of limiting.


Can the Autocomplete delay be lowered in forms? I have seen that the autocomplete widget in Forms API is started when I finish typing, or when there is a delay between one key hitting and the next one. Could it be configured so it is launched as soon as I press a key, like in Google Autosuggest or other search boxes?

As Clive suggested in a comment major part of the delay is because of the time taken by your server to populate the dropdown list. This generally happens because Drupal has to load all the enabled modules and do a complete Drupal bootstrapping.

In special cases like Autocomplete responses that may not be necessary. Hence you can load only what is required and do a minimal Bootstrapping.

You can check out the details of how this is done on this page.

Note : This involves custom coding and will not to perform any access checks unless you manually do it.


Undefined index: #attributes I have these errors :

  Notice: Undefined index: #attributes in theme_container() (line 3251 of /Applications/MAMP/htdocs/drupal-7.22/includes/form.inc).
  Recoverable fatal error: Argument 1 passed to drupal_attributes() must be of the type array, null given, called in
  /Applications/MAMP/htdocs/drupal-7.22/includes/form.inc on line 3251
  and defined in drupal_attributes() (line 2374 of
  /Applications/MAMP/htdocs/drupal-7.22/includes/common.inc).

And I do not understand why since I checked on other similar posts and my code seems ok :

.module file :

function gestion_videos_menu() {
 $items = array();

 $items['admin/config/media/gestionvideos'] = array(
 'title' => 'Gestion vidéos',
 'description' => 'Configurer le plugin VOD Infomaniak',
 'page callback' => 'drupal_get_form',
 'page arguments' => array('gestionvideos_configuration'),
 'file' => 'gestion_videos.admin.inc',
 'access arguments' => array('administer site configuration'),
 'type' => MENU_NORMAL_ITEM,
 );
return $items;
}

and .admin.inc file:

function gestionvideos_configuration() {
  $form = array(
    '#submit' => array('gestionvideos_configuration_submit'),
  );
  $form['config'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administration du plugin VOD'),
    '#description' => t('Pour fonctionner, le plugin a besoin de s\'interfacer avec votre compte VOD infomaniak.

                    Pour des raisons de securites, il est fortement conseille de creer un nouvel utilisateur dedie dans votre admin infomaniak avec uniquement des droits restreints sur l\'API.

                    Pour plus d\'information, veuillez vous rendre dans la partie "Configuration -> Api & Callback" de votre administration VOD.
                '),
  );
  return system_settings_form($form);
}

Do you have any idea how I could solve this ? Thanks a lot !

You need to accept the $form (and $form_state) parameters as part of the function signature, and not overwrite the form, rather add to it:

function gestionvideos_configuration($form, &$form_state) {
  $form['#submit'][] = 'gestionvideos_configuration_submit';

  $form['config'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administration du plugin VOD'),
    '#description' => t('Pour fonctionner, le plugin a besoin de s\'interfacer avec votre compte VOD infomaniak.

                Pour des raisons de securites, il est fortement conseille de creer un nouvel utilisateur dedie dans votre admin infomaniak avec uniquement des droits restreints sur l\'API.

                Pour plus d\'information, veuillez vous rendre dans la partie "Configuration -> Api & Callback" de votre administration VOD.
    '),
    '#default_value' => variable_get('config', ''),
  );

  return system_settings_form($form);
}

Choosing a different name than 'config' for your variable might also be wise. It's always preferable to provide a pseudo-namespace to variables as a prefix, usually the module name (e.g. gestionvideos_config). Don't forget to add the default value as in the above example as well, otherwise next time you go to the form it will have forgotten your config option.

If the above doesn't work for whatever reason, then the bug is somewhere else; try systematically disabling custom/contrib modules until you find the culprit.


Two variables in function I know this is my fault and lack of knowledge of php . Sorry about this .
I have a function in my template.php .

/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$vars) {

    if ($vars['node']->type == 'article') {
        // Remove Add comment link from teaser.
        unset($vars['content']['links']['comment']['#links']['comment-add']);

        // Remove login/register to comment link.
        unset($vars['content']['links']['comment']['#links']['comment_forbidden']);

  }
}

When i want to add a variable like &$variables to function , it does'nt work .

/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$variables, &$vars) {

    if ($vars['node']->type == 'article') {
        // Remove Add comment link from teaser.
        unset($vars['content']['links']['comment']['#links']['comment-add']);

        // Remove login/register to comment link.
        unset($vars['content']['links']['comment']['#links']['comment_forbidden']);
  }

    if($variables['view_mode'] == 'teaser') {

        $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__teaser';
        $variables['theme_hook_suggestions'][] = 'node__'.$variables['nid'].'__teaser';
        $temp = drupal_get_query_parameters();
        if(isset($temp['show_mode']) ) {
            $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__teaser__'.$temp['show_mode'];
            $variables['theme_hook_suggestions'][] = 'node__'.$variables['nid'].'__teaser__'.$temp['show_mode'];
        }
    }

}

Any advice ?

The $variables argument is passed by reference so you can name it whatever you want. There are two common conventions in Drupal for $variables in hook_preprocess functions:

Name it $vars
Name it $variables

I suspect you found some code that you want to use that used $variables; but your existing preprocess function uses $vars. Simply change the references to $variables to $vars in your code above and remove the $variables argument:

/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$vars) {

  if ($vars['node']->type == 'article') {
    // Remove Add comment link from teaser.
    unset($vars['content']['links']['comment']['#links']['comment-add']);
    // Remove login/register to comment link.
    unset($vars['content']['links']['comment']['#links']['comment_forbidden']);
  }

  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__'.$vars['type'].'__teaser';
    $vars['theme_hook_suggestions'][] = 'node__'.$vars['nid'].'__teaser';
    $temp = drupal_get_query_parameters();
    if(isset($temp['show_mode']) ) {
      $vars['theme_hook_suggestions'][] = 'node__'.$vars['type'].'__teaser__'.$temp['show_mode'];
      $vars['theme_hook_suggestions'][] = 'node__'.$vars['nid'].'__teaser__'.$temp['show_mode'];
    }
  }
}


Display expiry date of licence in list of orders I'm using Drupal Commerce and Commerce Licence.

I need to show in the list of orders in user profile, the expiry date of the purchased license.

I looked at the orders view, but it would seem that it is not possible to make a different view for "Commerce Order" and "Commerce licence".

Is there a solution?

I simply added a relation and it worked! Thanks Neograph734


How to style nested paragraph fields without duplication, in Views (and nested fields appear) Drupal 8.. This may be a two-part problem. I want to avoid repeated content due to multiple values in a nested paragraph reference, but ALSO put the nested paragraph fields into a custom text field, so I can change how they're rendered.

I have a content type "episode", with a field referring to paragraph "section", containing several fields. One of those fields inside "section" is a nested reference to a paragraph called "source".

I created a view for content type "episode". It pulls the results of "Section" matching a content ID  contextual filter. Then I added a reference to the paragraph "section", so I could get individual fields instead of a fully rendered value (I want to do this myself in a custom text field). I also created a reference for the "source" paragraph, to the "section" paragraph.

I'm able to add all the paragraph and nested paragraph fields, but the nested "source" fields are showing blank in the preview below, and it duplicates entries based on number of 'sources' I confirmed the paragraph fields are all set to show in the "manage display" for both paragraphs.

I then tried to see if there was a way I could just use the rendered paragraph "source" on the page. This shows the information, and I can set it to "Display all values in the same row" to eliminate duplicates.

But this prevents exactly what I'm trying to do: custom style the presentation of the information

What I want is to end it all with a custom field something like this:

{{ field_section_timestamp }}

{{ field_section_title }}

{{ field_section_description }}

Sources

{{ field_source_author }}{{ field_source_title }}

...And then apply whatever settings that get the sources to show as a list and not duplicate the entire section over-and-over, giving me something like this:

Episode
 - Section 1
    - Source 1
    - Source 2

 - Section 2
    - Source 1
    - Source 2

I know this can be done with the rendered paragraph and multiple field settings checked to "display all values in a row" But...

What I need is change how each field in Paragraph B is rendered - changing the tags.

But when I try to do this by adding the paragraphs as relationships and using individual fields, I get the repeating issue described above. I added the fields to a custom text field with everything, but this generates repeats.

Episode
 - Section 1
    - Source 1 (value blank)

 - Section 1
    - Source 2 (value blank)

 - Section 2
    - Source 1 (value blank)
 - Section 2
    - Source 2 (value blank)

Actually... as I'm typing this out and testing, I'm seeing that the paragraph B values aren't even showing at all. Though they take up space. just no content.

Hopefully this gives enough of a starting point for the question?

Seems I found an answer. I suddenly remembered there was something called the Views field View module. I installed it, played around with it until I found a "views" field. I was able to create a second view for the nested paragraph, add it to the first paragraph' view, through the and use a conditional field based off 'parent ID' and got exactly what I was looking for.

For reference, this video shows most everything you'd need to know, for using it:

[YouTube] View-ception: Using Views within Views.


How to generate URL alias without %20 in URL? We have a custom field that is being used to generate the URL alias.

One issue we have found is that when we set the page to "Autogenerate URL Alias" and set the URL pattern to "[node:field_custom_url]", we are still getting "%20" where the space should be.

We have done the following, but nothing seems to work. We needed assistance to see what else needs to be configured. Ideally, any spaces should be replaced with a "-" instead of "%20". Any thoughts?

Current settings (found in admin/config/search/path/settings):

Path pattern = "[node:field-custom-url]" (we even tried [node:field_custom_url], but it did not work)
Create a new alias. Delete the old alias. = Enabled
Separator = "-"
Transliterate prior to creating alias = Enabled
Reduce strings to letters and numbers

It is proved that I wrote wrongly in the beginning, thanks @Beebee.

  I have read through the code of pathauto module. The module
  implements the token replacement after replacing the space with
  defined separator. So there is no clue by configuration. I would
  consider it is a design fault of the module.

pathauto module clean the url only when the token name does not match with the pattern /(path|alias|url|url-brief)\]$/. You can find it in the function pathauto_clean_token_values(). Obviously, the module author would like to prevent the url alias to be clean twice. As your field name is custom_url, so it is escaped from the checking.

You can fix this by changing your field name or writing your own module as I stated before.

If you know how to create custom module. I would recommend you to implement hook_pathauto_alias_alter for the purpose.

/**
 * Implements hook_pathauto_alias_alter().
 */
function mymodule_pathauto_alias_alter(&$alias, array &$context) {
  $separator = variable_get('pathauto_separator', '-');
  $alias = preg_replace('/\s+/', $separator, $alias);
}


Making some Views Exposed Filters auto-submit but not others Background

I'm using Views and Better Exposed Filters and Search API. I have my filters set to 'autosubmit' so when a user makes a change to a filter it auto-updates the search result.

What I want to accomplish

This is cool but I only want the results to auto-update when CERTAIN selections are made. Otherwise I want the user to have to click the 'search button'.

Example

For example, I want the user to have to click the 'search button' for some things such as the text boxes and some of the radio buttons, but for SOME of the checkboxes I want the search results to auto-update when a new selection is made.

Question

Is this possible programmatically (or I suppose in Views itself) and if so, how?

Gonna add my 2 cents too on the topic, since I recently did my reading-into this topic (autosubmit for exposed filters).

Related:

This answer here answers a very similar problem => https://drupal.stackexchange.com/a/198274/57183.

Usefull things to know

The most important piece of relevant documentation lies inside the ctools/js/auto-submit.js file of CTools, at the top of that file.

Form API programming

Following that documentation, you should use the FAPI to programmatically do one of the following:

Exclude the specific filters that you don't want to be trigger an autosubmit (if you have autosubmit active, like in your case):

  If you want to exclude a field from the ctool-auto-submit-full-form
  auto submission, add the class ctools-auto-submit-exclude to the form
  element. With FAPI, add:

  '#attributes' => array('class' =>
  array('ctools-auto-submit-exclude')),

Include the filters that you want to trigger an autosubmit (if you have autosubmit deactivated, not your case)

  On gadgets you want to auto-submit when changed, add the
  ctools-auto-submit class. With FAPI, add:

  '#attributes' => array('class' => array('ctools-auto-submit')),

After that, you already have the functionality you need.

Example to the Example

Following your example here is some example code (with inline comments):

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

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  }

}

This should do it, now the exposed filters full_text_search' and 'field_categories' will not trigger an autosubmit event, all other filters will.

Hope this helps!

Addendum (follow-up question):

To get specific checkboxes from a BEF-checkbox group to trigger a form submit, you need to do the following:

Modify you form_alter implementation:

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

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
    'field_areas_of_interest_checkbox', // a BEF-checkboxes widget
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  }

  // This is the name of the select values and their target url
  $bef_checkboxes_autosubmit = array(
    '#area_of_interest_checkbox_1',
    '#area_of_interest_checkbox_3',
  );

  // This will attach a javascript to the checkboxes element
  $form['field_areas_of_interest_checkbox']['#attached']['js'][] = drupal_get_path('module', 'somemodule') . '/somemodule.js';
  $form['field_areas_of_interest_checkbox']['#attached']['js'][] = array(
    'data' => array(
      'bef_checkboxes_autosubmit' => array(
        'form_id' => $form['#id'],
        'checkboxes_ids' => $bef_checkboxes_autosubmit,
      )
    ),
    'type' => 'setting'
  );
}

Now, you also need a javascript file (somemodule.js) that will look sth like this:

(function($){

Drupal.behaviors.BEFCustomRedirect = {
  attach: function(context, settings) {
    $(settings.bef_checkboxes_autosubmit.checkboxes_ids).each( function( idx ) {
      $('.ctools-auto-submit-exclude.form-checkboxes input' + this).change(function() {
        $('#' + settings.bef_checkboxes_autosubmit.form_id).submit();
      });
    });
  }
}

})(jQuery);