How do I implement a one page navigation with anchors? So the specific functionality I'm looking for is a link on one page (e.g. drupalsite/home) leading directly to a specific section of another page (e.g. a section on drupalsite/otherpage).

I believe that to implement this I need to use hash based navigation such that the content I want to link to is has it's css class name preceded by a hash (pound sign or number symbol)
 and is linked to by including the hash referenced content in the href attribute of an anchor tag. Such that
 on page drupalsite/mypage via .

Will this work without out of the box with just HTML changes? Or is additional JavaScript configuration necessary?

I know that more specific and fluid implementations will necessitate JavaScript and jQuery, but I want to know if the core HTML works without conflicting with Drupal's internals.

This is the code I'm using on most of my projects

(function ($, Drupal) {
  var wt = window.wt || {}; //just my personal namespace

  wt.getFixedTop = function() {
    /* return pixel height of fixed elements, e.g. Admin Toolbar or a fixed main nav */
  };

  wt.scrollTo = function(uri) {
    if ((uri.indexOf(location.pathname) === 0 || uri.indexOf('#scroll') === 0) && uri.indexOf('#scroll') !== -1) {
      var selector = decodeURIComponent(uri.substring(uri.indexOf('#scroll') + '#scroll'.length));
      var regex = /^=[#\.\[\]a-zA-Z0-9-_]+$/;
      if (selector.search(regex) != -1) {
        selector = selector.substring(1);
        $('html, body').animate({scrollTop: $(selector).offset().top - wt.getFixedTop() }, 1000);
      }
      return false;
    }
  }

  $('body').on('click', 'a[href*="#scroll"]', function () {
    wt.scrollTo($(this).attr('href'));
  });

  $('body').imagesLoaded( function() {
    window.setTimeout( wt.scrollTo(location.pathname + location.hash), 200 );
  });

}(jQuery, Drupal));

It requires ImagesLoaded and works within and across pages, and with responsive images. It also allows linking to IDs and classes by appending the proper CSS selector, e.g. /some-page#scroll=.my_class

It certainly is not a perfect solution, but our internal, HTML-trained editors can quickly create deep links to any section they want by adding #scroll=<CSS_ID_OR_CLASS_SELECTOR> to any link.


Provide User with list field of images to select I am using the flexslider module in conjunction with the views slider to create a slideshow on my Drupal project. Instead of just allowing the user to upload an image for the slideshow (the image really just acts as a background), I would like to provide the user with a list of possible images to choose from. I'm new to Drupal, so this is probably a really easy thing to accomplish, but multiple Google queries have left me in the dark.

I previously used IMCE for FileField module:

it opens a simple file browser and let you select files from configured path of server.


Display webform submitted data in profile page I have created a webform with several fields. I have implemented webform registration module too. Now if the user registers, Soon after clicking register button he will need to see his profile page with the submitted values.I can use tokens for this but it's not a good idea because user should be able to edit his profile page too.
 -I have tried displaying webform submissions on view.which doesn't work here.
 -But specifically a user should see his profile page with submitted data after
   submitting the webform
 -Please help me on this.

If you're willing to use Webform Rules in combination with Rules, you can use the webform data (as submitted via the webform) in a custom rule (to copy those webform date to the relevant profile fields). Because you have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

With that, you should be able to create a custom rule with:

Rules Event: After a webform has been submitted.
Rules Conditions: Check the form's id (possibly with other conditions to further refine them, eg that the user is not logged in).
Rules Action(s): Set a data value (for the appropriate profile fields, and using the values submitted via the webform).

For more details about this approach, and a prototype rule to understand the idea, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.

PS: I'm assuming your question is about D7 ...


Upload media to different sub-domain I want to store all the uploaded media files on a different sub-domain on the same server (for CDN origin purpose).
I think I can point drupal to upload files to this location (using the File System configuration > "Public file system path ") but how do I config it to use the correct URL?
I guess I can do some htaccess redirects but it makes it more complex with multisite installation.

Does the CDN module does that?

Thanks,
Bnaya

Edit: I use Media module and only needs the files uploaded by it will use the CDN, I will handle the theme files.

I'm not 100% sure of what your goal is, but I just accomplished something similar and in case it helps you here is what I was looking to do and what I did.

I am uploading all images to the /sites/default/files/images directory and I wanted them to become available via http://images.example.com/filename.jpg and display on the node via ths subdomain.

To do this I setup a virtual host in /etc/httpd/conf/httpd.conf

<VirtualHost *:80>
  ServerName images.example.com
  DocumentRoot /var/www/html/example.com/sites/default/files/images
</VirtualHost>

You can then alter your subtheme node.tpl.php to reference the attached images via this subdomain.

<?php $img = 'http://images.example.com/' . $field_image['und'][0]['filename']; ?>
<img src="<?php print $img; ?>" />

I wanted the convenience of having the variables already present in the node so I used the template_preprocess_node(...) function in template.php.

function MYTHEME_preprocess_node(&$vars) {
  $node = &$vars['node'];
  if ($node->type == 'image') {
    $base_url = 'http://image.example.com';
    $vars['image_base_url'] = $base_url;
    foreach ($node->field_image['und'] as &$image) {
      $image['url'] = $base_url . '/' . $image['filename'];
    }
  }
}

With this I can access inside the node both $image_base_url as well as $field_image['und'][0]['url']

$image_base_url is http://image.example.com
$field_image['und'][0]['url'] is http://image.example.com/filename.jpg


How do I avoid behaviors are invoked after an AJAX call? I have a search result page, with the first set of data being fetched during the page load, and we add a Load More button. Clicking on this button fires an AJAX call, using the ajax_links_api module. After the AJAX call is completed, we append more search results to the current set.
I have a behavior where I read the URL parameter; if it exists, I open a Colorbox.

If the colorbox opens on page load, we close it, and then click on Load More (which fires AJAX); then the Colorbox JavaScript is fired again, and we see the popup in action again.

I don't want to fire the Colorbox JavaScript after AJAX is completed/fired.

I tried jQuery Once, but it didn't work.

How can I achieve this? Can I detect when an AJAX call happens?

The following is the code I am using.

Drupal.behaviors.openColorbox = {
  attach: function (context, settings) {
    if ($('body', context).hasClass('page-search-site')) {
      var nid = url('?node');
      if (nid != undefined) {
        if (nid.trim()) {
          $('div.search-result')
            .find('.node-' + nid)
            .once('colorbox-clicked')
            .click();
        }
      }
    }
  }
};

You are using .once in the wrong spot

(function($, Drupal) {

  "use strict";

  function openColorbox(context) {
    $(context).find("div.search-result").once("openColorbox").each(function () {
      if ($('body', context).hasClass('page-search-site')) {
        var nid = url('?node');
        if (nid != undefined) {
          if (nid.trim()) {
            $('div.search-result')
              .find('.node-' + nid)
              .click();
          }
        }
      }
    }
  }

  Drupal.behaviors.openColorbox = {
    attach: function (context) {
      openColorbox(context);
    }
  };

}(jQuery, Drupal));

Note that this is D8 style. If you are using D7, the above will not work as it is done differently, and you didn't tell us which Drupal version you are using.


View filter computed date field i have content type in Drupal 6 that has date field, that is date when some historical event happened.

I want to create a view that will show all historical events that happened today.

I created 2 computed fields that will take data from that date field, one for month and other for day. Also i created view and added this two fields as filter. And when i enter exact numbers in filter, like 9 and 20 it shows the articles that happened on this month and day.

But since its not exactly a date field i cant enter relative values like "now" or "today" and someone needs to change this manually every day.

What is best way to get this filter take todays day and month.

OK i found the solution.

I had to use Arguments ( contextual filters ), and in argument i would use php code as validator and than just get todays day with simple code:

$day = date("j");
return $day;

Hope this helps someone in future.


How to export Panels Everywhere template code to a module I would like to export a Panels Everywhere site template to code. I know you get some configuration code when you select the export tab, but I'm not sure how you turn that into a module that will generate the template with it's variants and layout on another environment.

You can try features module.

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

the features module converts every entity (views, content types, ...) in to a module and it can easily be installed and modified every where.


How can I filter nodes by author name? I'm trying to make page with nodes filtered by author name. My context filter is comming from url.

My path looks like domain.xx/drupal/authors/johny

If i set validation by user ID, and send user ID in path, all works properly.

You can see contextual filter setup in attachment.

On editing view, click the advanced settings then click relationships area, click Add.

There are many tables you can join to the content listing. In this case, search for "author" options, and select Content: Content author. Click Apply. Now add field 'user' in view also set filter criteria as needed.


Store mysqli-connection object in cache I have some code in a drupal 7 site that makes repeated requests to an external database using mysqli. To speed up the code, I was hoping that I could store the mysqli-connection object in the cache, like this:

// Check if DB-connection already loaded
$external_db = &drupal_static(__FUNCTION__);

if ( !isset($external_db) ){
    // Check if DB-connection in cache
    if( $cached_db = cache_get('external_db', 'cache') ) {
           $external_db = $cached_db->data;
        }

    // Else make a new connection
    else {
        $external_db = mysqli_connect('someip', 'someuser', 'somepass', 'somedb');
        cache_set('external_db', $external_db, 'cache');
    }
}

However, something spooky happens to the connection object when I fetch it from out of the cache: it seems to have lost most of its properties. For example, the properties client_info and host_infoare being unset.

Any idea what causes this? Does Drupal delete those properties, or is it something built in to mysqli? Are there alternatives to mysqli that are cacheable?

Thanks a lot you guys!

To speed up the code, I was hoping that I could store the mysqli-connection object in the cache

It doesn't work like that. For one thing a database connection cannot be serialised (not in any meaningful way at least, as you've discovered). Once the page request is done with, the connection is closed. You can't force it to stay open by maintaining a reference to it, as that physically won't work when you come to accessing the network.

Separately, you should never have any cause to use mysql_connect() in Drupal (or ever if you want to be technical - it was deprecated a long time ago). Drupal's database connection is as optimised as you'll need such a thing to be, so you should just use that.


Insert webform into content type field At the content type i add some field:

if you want to include or embed block into the body of your node
https://www.drupal.org/project/insert_block

if you want to include or embed view into the body of your node
https://www.drupal.org/project/insert_view

How about webform?

For webform: Use insert block module as well.
Structure --> block --> Click configure one of the webform you want to add.--> look at the URL

Example: http://localhost/example.com/#overlay=admin/structure/block/manage/webform/client-block-5/configure

Type this "[block:webform=client-block-5]"


Getting a true http address from file object's uri (Drupal 7 I have created a little module to try and unzip files that has just been uploaded through node creation.  Here is my unzip function (the $file parameter is a file object):

function unzip($file) {
  watchdog('beep','Unzipping a project!!');
  $zip = new ZipArchive;
    //This Works
    $res = $zip->open(drupal_realpath($file->uri));
    // This does not
    //$res = $zip->open($file->uri);
  if ($res === TRUE) {
    $zip->extractTo("/Applications/MAMP/htdocs/sites/default/files/");
    $zip->close();
    watchdog('Zip sucess','Unzipping worked!' . drupal_realpath($file->uri));
  } else {
    watchdog('Zip Failure','Unzipping failed for ' . drupal_realpath($file->uri));
  }
}

Included in this snipet are two different ways I attempted to open the zip file.

This first one works on my local MAMP server but would not work on a producitons server:

$res = $zip->open(drupal_realpath($file->uri));

This created a path like this:

/Applications/MAMP/htdocs/sites/default/files/Tumble arcade file_5.zip

and

$res = $zip->open($file->uri);

creates a path like this:

public://Tumble arcade file.zip

Now the first path is interpreted correctly by $zip->open and the file is unzipped correctly but with the second path, the zip open fails.  I believe this is happening because php does not know how to handle the second path and needs something more like this:

http://localhost/sites/default/files/Tumble%20arcade%20file_5.zip

Am I on the right track and if so how would I get this other kind of path?  If not, any idea what might instead be the problem?

There's a nice in-built function, file_create_url():

  Creates a web-accessible URL for a stream to an external or local file.

e.g.

$url = file_create_url($file->uri);


How can I display sql query from database? I'm trying to display sql query on page in drupal 8.2, but I get an error:

  The controller must return a response (Object(Drupal\Core\Render\Markup) given).

How should I change the following code?

if ($result = $mysqli->query("SELECT id, discipline, teacher FROM canteach")) {
  $output .= "Select вернул " . $result->num_rows . " строк <br />";
}

$mysqli->close();

$header = array('id', 'Discipline', 'Teacher');
$rows = array();

while ($row = $result->fetch_array(MYSQLI_NUM)) {
  $rows[] = array($row->id, $row->discipline, $row->teacher);
}

$result->close();

$items_array = array(
  '#theme' => 'table',
  '#items' => array('header' => $header, 'rows' => $rows),
);

return render($items_array);

From the error, I assume your code is in a controller? In that case, take note that you should return a render array or an object inheriting the Response class, not HTML.

In your case, just do:

return $items_array;

instead of

return render($items_array);

But wait!

The table render array should be constructed this way:

$items_array = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

For a reference of what you can pass in, check out https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21table.html.twig/8.1.x

Other notes

The way you are querying data is not wrong per se but definitely not the "Drupal way". To perform queries using Drupal's DBAL, check out https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!database.api.php/group/database/8.2.x


how to theme nodes in views results if logged in user equals node author I have a D7 site with search_api module, I'd like to change border color of nodes in views results if logged in user equals node author, in plain English, make easy to logged in users identify its own content in views results.

You'll need to check this in a preprocess hook.
You can load the global $user object and have views report the node author. In the preprocess hook you can check $user->uid against $node->uid and set a variable so you know in your tpl.php file which css class to set in your wrapper.


Set Taxonomy Description via Rules Question:
How can I access a taxonomy's description in the "Rules" module? When I create a new taxonomy entity I can only set the name of the term, I'd like to also add the term's description.

Goal (in case I'm doing this entirely wrong!):
Anonymous submission of new taxonomy terms with a description, for approval by a role. When node type of "new term" is approved, it copes it to a taxonomy vocabulary and then deletes the original node.

in Rules, after your Action Create a new entity (of type taxonomy term), when you set a new one, Set a data value, find the entity you just created -> Description .


Failing to uninstall a module because "The website encountered an unexpected error. Please try again later." It is something wrong with the Profile module I'm using together with the Commerce module and multilanguge module. I would like to uninstall all three modules and try to install them again, but it doesn't allow me as you can see below. How to proceed?
When I try to uninstall a module at /admin/modules/uninstall I get this error.

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

Detailed error message:
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pantheon.profile' doesn't exist: SELECT base_table.revision_id AS revision_id, base_table.profile_id AS profile_id FROM {profile} base_table LIMIT 1 OFFSET 0; Array ( ) in Drupal\Core\Entity\EntityStorageBase->hasData() (line 588 of /code/core/lib/Drupal/Core/Entity/EntityStorageBase.php).

I have clear all cash and run cron, still same issue. It asks me to run this update script:

15 PENDING UPDATES

profile module

8003 - Removes the langcode key from the profile entity keys.
8004 - Add the uid entity key to profiles.
8005 - Rerun uid entity key addition after incorrect entity type fixed.
8006 - Install the `data` field.
8007 - Set the 'published' entity key.
8008 - Adds a storage schema for profile that adds a multi-column index.
8009 - Update revision fields.
8010 - Update the status field.
Add new revision settings to profile types.
Change the plugin ID of the delete action.
Change the plugin IDs of the publish and unpublish actions.
Show the profile form at user registration using the profile_form widget.
Replace the "profiles" view with the updated version.

commerce_tax module
Add the tax_number field to customer profiles.
Add the tax_number field to customer profile view displays.

I click on Apply pending updates. I get this error
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /update.php/start?id=44&op=do_nojs&op=do
StatusText: parsererror
ResponseText:

Detail error log:
Error: Call to a member function hasKey() on null in profile_update_8003() (line 82 of /code/modules/profile/profile.install)
#0 /code/core/includes/update.inc(246): profile_update_8003(Array)
#1 /code/core/includes/batch.inc(295): update_do_one('profile', 8003, Array, Array)
#2 /code/core/includes/batch.inc(137): _batch_process()
#3 /code/core/includes/batch.inc(93): _batch_do()
#4 /code/core/modules/system/src/Controller/DbUpdateController.php(185): _batch_page(Object(Symfony\Component\HttpFoundation\Request))
#5 [internal function]: Drupal\system\Controller\DbUpdateController->handle('start', Object(Symfony\Component\HttpFoundation\Request))
#6 /code/core/lib/Drupal/Core/Update/UpdateKernel.php(115): call_user_func_array(Array, Array)
#7 /code/core/lib/Drupal/Core/Update/UpdateKernel.php(76): Drupal\Core\Update\UpdateKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request))
#8 /code/update.php(28): Drupal\Core\Update\UpdateKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#9 {main}

The uninstall & updated errors are like symptoms of the same problem; your profile module installation has corrupted DB storage so the module can't remove its DB tables, or retrieve its entity definitions to upgrade it.
You'll need to do a manual recovery on in a test environment so you can fully uninstall then reinstall so it has functional DB schema again. Manually restore the profile table (or any other DB schema) that the modules needs, then attempt uninstalling again. Repeat this process so you're able to successfully uninstall the module, then re-install it so it has a functional schema.
Once you've confirmed the process works, perform it on your live DB (after backing it up).


Breadcrumb with taxonomy path I use the theme "Bootstrap".

When I display a node, there is no breadcrumb. My nodes are related to taxonomy terms.

On the screenshots :

  Boutique / Les chocolats BIO

The second screenshot should be :

  Boutique / Les chocolats BIO / Tablette de chocolat noir artisanale
  BIO aux épices tchaï

"Boutique" is the vocabulary of taxonomy and "Les chocolats BIO" is the terms of taxonomy.

How to display the breadcrumb on the nodes without using any additional modules ?

you can implement hook_node_view and make alterations in the breadcrump
eg:

/*
 * Implements hook_node_view().
 */
function my_custom_module_node_view($node, $view_mode) {
  if ($node->type == 'my-node-type') {
    $type == $node->field_test_field['und'][0]['value'];
    if ($type == 0) {
      $breadcrumb = drupal_get_breadcrumb();
      $breadcrumb[1] = 'new breadcrumb';
      drupal_set_breadcrumb($breadcrumb);
    }
  }
}


Adding translations to installation profile upon installation Creating an installation profile for a french site.

I have hit a brick wall trying to have the profile install fr language translations.
I have tried adding this to my profile as this comment http://drupal.org/node/1297438#comment-6308144

// Add french language.
locale_add_language('fr', 'French', 'Français', LANGUAGE_LTR, '', '', true, true);
drupal_set_message(t('The language %language has been add and is now the default language.', array('%language' => 'french')));

Code above generates a fatal error:

[drush] Fatal error: Call to undefined function locale_add_language() in /home/stef/jmt-www/build/www/profiles/jmt_profile/jmt_profile.profile on line 19

I have the fr.po file in profile/jmt_profile/translations but have no clear way of getting the fr.po loaded. Has anyone dealt with installing secondary languages without going through ui?

You must include locale.inc before:

include_once DRUPAL_ROOT . '/includes/locale.inc';
locale_add_language('fr', 'French', 'Français', LANGUAGE_LTR, '', '', true, true);


How to bulk assign existing content to a group created with the Group module? The Group module is an alternative for Organic Groups. One of the features it offers is that you can assign nodes to a Group.

Question: how to bulk-assign a set of existing nodes to a specific group, using site building techniques only (not programmatically, which appears to be a possible alternative also)?

Step 1: Create a Rules Component

Have a look at this example of a Rules Component (in Rules export format):

{ "rules_assign_existing_content_to_a_group" : {
    "LABEL" : "Assign existing content to a group",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_to_assign" : { "label" : "Node to be assigned", "type" : "node" },
      "assigned_group" : { "label" : "Assigned group", "type" : "group" }
    },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "node-to-assign" ], "type" : "node" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node-to-assign:group" ], "value" : [ "assigned-group" ] } }
    ]
  }
}

This Rules Component will be used in the subsequent step.

Note that I've not added a Rules Condition here about selected content types, that's possibly an extra condition you might want to add also.

If you want, just grab (copy) the exported rule above, and simply import this Rules Component in your own environment.

After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node to be assigned. Use a similar technique to specify the Assigned Group and hit the Execute mode. The node you selected will be assigned to the group you specified.

After you're confident your rule works fine, move on to the next step below.

Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...


How to create a squeeze page for attached files under Drupal 7? I have a content type set up in my Drupal 7 site which has an attached file. As it currently stands, this file can be freely downloaded without requiring a user account.

I do not want to require users to create an account on this site, but I would like to set up a 'squeeze page' for the newsletter/mailing list. That is, when someone decides to download the file, I'd like to present a dialog or screen a bit like this:

  Enter your email here to sign up for our email newsletter:

  [_____] [Sign up and Download]

  OR

  [No thanks, I'd just like the file]

I found two modules which would have worked if I were using Drupal 6 - Webform Protected Downloads and Squeeze Page, but no equivalents for Drupal 7. I was considering using the Custom Formatters module and a light box/dialog of some sort to jury rig it, but then I'd still need to code something to save the emails out again.

Is there a more elegant solution out there for this requirement? I am capable of coding new modules myself if that's the only option, but the less new code I need to write for this the better. Perhaps there might a module or combination of modules which comes close, which I could then tweak or modify?

Thanks in advance!

There are a number of modules out there and I assume you found them, your particular implementation will affect which suits you, but for D6 or D7 take a look at the Comparison of file download gateway and tracking modules.

I have found each of these to be too specific and limiting in some or other way and have resorted to using webform and some custom coding.


How do I check if a single on/off checkbox is checked? There does not appear to be any way to check the value of a single on/off (boolean) checkbox in the data selector for the Rules module.  If "field-MyField" = checked or "field-MyField" = 1, then do 'blah'.  Can Rules do this?  I must be missing something

There's a mix of correct and incorrect details here, so I will try to sort them out. This is for Rules on Drupal 7, and applies to working with a Boolean field.

To make a condition that checks a field's Boolean state (true/false, yes/no, checked/unchecked), first make sure that you can access the field in the data selector. As Bojan mentioned above, and as it mentioned on the admin page itself,

  To make entity fields appear in the data selector, you may have to use
  the condition 'entity has field' (or 'content is of type').

The operator you want to choose is "equals".

For the "Data Value" field, you can input values in two modes, make sure you are using "direct input mode". You should then be able to check the checkbox that represents TRUE for that field.

Translated, what you are saying is, "Is this field equal to TRUE?" You can also negate it by leaving it unchecked or using the "negate" option below.


item.url generated at menu issue I am working on my client's project and they are using Drupal 8.
I discovered that when one uses http://example.com/index.php to access the webpage, the url generated by the menu items , the index.php part is included, i.e. http://example.com/index.php/aboutus instead of http://example.com/aboutus. And it leads to a wrong page.
And I checked with the template file which generates the menu, the url of the menu is generated by {{item.url}}, which item is one single item of items for the available variables in the menu templates.

Available variables:
-menu_name: The machine name of the menu.
-items: A nested list of menu items. Each menu item contains:
-attributes: HTML attributes for the menu item.
-below: The menu item child items.
-title: The menu link title.
-url: The menu link url, instance of \Drupal\Core\Url
-localized_options: Menu link localized options.

Therefore I am asking if there are ways to get rid of the "index.php" in this case and in order to avoid drupal generating wrong url? Thank you very much

I think you may need to enable apache mod_rewrite. You can refer this answer as well. To enable mod_rewrite, use the following command:

a2enmod rewrite

Then you need to restart apache for the changes to reflect,

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

Refer this page for information about clean urls, this might even help.


Form API focus on first input When my form load I would like to set the focus on the first field in the form. I know I can use jquery to do this by doing $('inout id').focus();. Where would I put this code so that it only runs on a certain form?

Is there a simpler way?

Updated

Using a mixture of smile's answer and clive's comment the code that got it working in the end was:

$form['#attached']['js'] = array('(function ($){$(document).ready(function() { $(".form-item-field-name input").focus()});})(jQuery);' => array( 'type' => 'inline'));

You can attach js only to your form. Use hook_form_alter()

function your_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form'){
  // Add JavaScript file
  $form['#attached']['js'] = array(drupal_get_path('module', 'your_module') . '/your_file.js');

  // Or for inline JavaScript
  $form['#attached']['js'] = array('/* some javascript here */' => array( 'type' => 'inline'));
  }
}


Access to a website only when I grant them access I have made a registration form and a login form using PHP.

The registration form saves user's information to a database.

But as I am pretty new to PHP I want to achieve this think. I have also made a whole e-commerce website with Drupal commerce(commerce kickstart) but I want as an entrance page to be this registration form and when I grant them access to be able to see the whole content of my e-commerce website.While i say grant them access when they give me the fields of the registration form,they wont be able to enter the website until I send them a password. So my question is : How can I achieve not be able to see the entire website?What I need to do to protect it? I mean I need to add code on the registration form? on the login form or the template/theme?

I know that I have to use $_SESSION[] and $_COOKIE[]

For example

if($_SESSION['loggedIN'] ===false){ header('location:login_page.php')}

but I do not know where to put the code so as to work. In which part of the commerce kickstart do I have also to say that the e-commerce website would be on a sub-domain as the domain will be used for the registration form if this helps.

Thanks!

Ah, you don't need to be doing stuff like that with PHP. Drupal has plenty of tools to handle permissions for users.

Drupal already has the ability to allow you to make sure users need to be approved by an admin - check the user settings.

As for restricting access to "enter" site... well you need to review your user permissions table. "enter" is a pretty vague word to be using in Drupal terms.


Set Views exposed filter to ignore case I have a view which uses an exposed filter to let the user filter the results via keyword (in other words it behaves like a text search).  The actual field is implemented using views_fields_combine module, but I assume this issues applies to any field which contains text.  The problem I have is that the filter only works correctly if the case of the "search" text matches the content in the field.

For example if the field contains "Cool Capacitors" and the user types "Cool" in the exposed filter then there will be a resulting match.  But it the user types "cool" then the filter will not find any matching results.

I would like to know if there is a method of making the exposed filter ignore the case when making matches.  Strangely enough I have not been able to find any information on this on the internet.  I am wondering if I am try to do something that exposed filters was not designed to do?  Perhaps there is some alternative method I could consider?

This should help you directly or get you started in the right direction -  Combine fields filter case-sensitive search


Views Output Field as Link: Change link text I've got a View showing some images. I want to include a link to the image which automatically downloads the file. I'm using the DownloadFile module which makes sure the browser actually downloads the image instead of just displaying it.

I've added the Image field that I want displayed in my View, and I'm checking the Output this field as a link but I don't see any field where I can control the link text. I see title, rel, etc., but I want the actual link text to simply say "Download".

i.e.:

Download

How can I control the link text of the link being rendered by Views?

While editing your view, open the field you want to modify.  In your case it would be your Image field that current output's Download

Scroll to 'Rewrite Results' and check the box next to 'Rewrite the output of this field.'

Enter the text that you would like to display instead of 'Download.'

I believe if you use the Tokens module, you will have several variables accessible to you as well.  See "Replacement Patterns" in the same menu to see what is available.


Packing taxonomy fields into one div not from SQL? I created 2 taxonomy entity-reference fields. One is Categories and one is Tags and some similar other fields.

In nodes, some of these taxonomy fields appear one above the other.

I want to give some padding-top and padding-bottom css code, not to each one - but to all together.

Yet, they don't sit inside a wrapping div and wrapping them through the SQL isn't quite comfortable, though I am not sure it's a minimalist/easy to supervise/safe solution.

Do you know a way to bias Drupal 8 to "pack" some of these into a div ? Maybe an intervention in the Twig could do that with some behavior-code?

This is the content of field.html.twig in the core theme classy:

{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}

{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes.addClass(classes, 'field__items') }}>
      {% for item in items %}
        <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}

Each field is packed into a div with its own class field--name-field-name. In your case field--name-field-tags and field--name-field-categories.

Steps for solution:

If you don't use classy as base theme you can put somehting similar in your custom theme or simply copy this twig from the classy theme and change as needed.

core/themes/classy/templates/field/field.html.twig -> themes/mytheme/templates/
Flush all cache.


Is it possible to create a panalized node in code? Is it possible to create a Panelized node programatically?

Perhaps something like the following:

$node = new stdClass;
// ... Set other properties
node_save($node)

// Then somehow add panalizer , layout, panels
// Something like:
$panelizer = array ( 'nid' => $node->nid )

//save it
panelizer_save_node_panelizer($panelizer)

// add existing panels/panes to the node
?>

Make sure that your content type is panelized (you've panelizer link at /admin/structure/types).
Double check the Panelizer settings of that content type, for instance whether to 'Provide an initial display named "Default"' (at /admin/structure/types/manage/%).

Above 2 steps can be achieved programatically by either exporting panelizer_defaults component into Features code:

features[panelizer_defaults][] = node:my_content_type:default

or define them using hook_panelizer_defaults manually.

At this point all your created nodes should be panelized automatically and the settings should be available in node object at $node->panelizer['page_manager'].

Still not sure if your node is panelized or not? Run this via drush (where 123 is your node id):

$ drush eval "print_r(node_load(123)->panelizer['page_manager']);"

and if you'll see an object printed out, your node is panelized.

Then if you would like to create/re-create panel display associated with the node, try the following code:

$node = node_load($nid);
$old_display = $node->panelizer['page_manager']->display;
$new_display = panels_save_display($display);
$node->panelizer['page_manager']->display = &$new_display;
$node->panelizer['page_manager']->display_is_modified = TRUE;
node_save($node);
// Clear caches just in case.
ctools_include('object-cache');
ctools_object_cache_clear('panels_node_display_cache', $node->nid);
$did = is_numeric($new_display->did) ? $new_display->did : FALSE; // Your display id.

The same thing can be achieved on newly created code by creating a panels_new_display(); instead and assign it to $node->panelizer['page_manager']->display.  Also note that the display should be only saved once (not on every node save), then it can be modified based on your needs.

See also:

How to attach node into panelized node?
Updating Panelizer content programmatically


How do I alter a form submission handler? I want to alter the form submission handler submit for the search block with a custom module.
Setting  $form['#attributes']['class'] works, but the submission handler doesn't seem to be triggered with any of the methods that I have alternatively found in many core and third-party modules.
/**
 * @file
 * Redirect search from search block to XXX.
 */

use Drupal\Core\Form\FormStateInterface;

/**
* Implements hook_form_FORM_ID_alter().
*/
function search_redirect_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
    $form['#attributes']['class'][] = 'test-class'; //Working
    $form['#submit'][] = 'search_redirect_search_block_form_submit';
    $form['actions']['submit']['#submit'][] = '_second_submit';
}

function search_redirect_search_block_form_submit(&$form, FormStateInterface $form_state) {
  \Drupal::logger('search_redirect')->notice("the function is triggered"); // Not happening
  \Drupal::service('messenger')->addStatus("the function is triggered"); // Not happening
}

function _second_submit(&$form, FormStateInterface $form_state) {
  \Drupal::logger('search_redirect')->notice("second_submit"); // Not happening
  \Drupal::service('messenger')->addStatus("second_submit"); // Not happening
}

Stupid question but have you cleared cache to register the new hook?
Also, try inspecting the form in hook_form_alter to make sure you are attaching the handler to the correct action.
Lastly, I've found that I usually need to reorder the array to include my handler first in order for my actions to actually trigger on form submissions using Drupal core forms that have existing handlers.
As an example, I did like:
$form['actions']['submit']['#submit'] = array_reverse($form['actions']['submit']['#submit']);

which will reverse the array. I also sometimes use array_unshift to pop my handler at the start of the array if the other handlers need to retain their order.


How to render a template declared in hook_theme directly in a twig template without preprocess? Lets say I have a hook_theme like this :

/**
 * Implements hook_theme().
 */
function mytheme_theme($existing, $type, $theme, $path) {
  return [
    'partial' => [
      'variables' => ['current_url' => NULL],
      'template' => 'partial'
    ]
  ];
}

Then in a node.html.twig, I want to call the template.

Currently I'm doing this :

{% include '@mytheme/partials/partial.html.twig' {'current_url': url('<current>')} %}

But the problem with this is that I never go into my

function mytheme_preprocess_partial(&$variables) {}

Also I can't benefit from the TWIG DEBUG mode.

Is there any way to do something like this :

{{ theme('partial', {'current_url': url('<current>')}) }}

Thanks for helping.

In D8 there is no theme() function, so if you want to render a template you use a render array for it. Put it in a twig variable and print it:

{% set partial = {
  '#theme': 'partial',
  '#current_url': url('<current>'),
} %}

{{ partial }}

As a side note, because of a security issue for Twig in Views you might be no longer be able to do this in Drupal 8.6 and are forced to use PHP in the near future. There is an ongoing discussion what to do about the code execution vulnerability without (hopefully) preventing such valid use cases, see https://www.drupal.org/project/drupal/issues/2860607


Looking for a workflow module that can control content access I have a content type called "article".  It needs to go through some workflow states when people try to submit a new article:
submitted -> review 1 -> review 2 -> published.

During each workflow state, only certain roles should be able to see it, modify it, and comment on it.  This needs to be done independently by its current workflow state.  The workflow module appears to have access control based on states, but then the access control part does not work so essentially everyone can see the content no matter what state it is in.  Not sure if this is a major security bug, permission being overridden by another module, or me doing something wrong.

Any other suggestions for modules that can do workflow?  I heard Workbench is another good one.  Can it keep track of comments and separate out comments based on workflow states?

Update and solution: Turns out that I was not using the Workflow module correctly and Drupal's permissions correctly. I was assuming that the Workflow module could remove permissions. Instead I had to start with the least privileges in Drupal and then let the Workflow module allow/deny access to the content type.

For example, if Drupal permissions allow a visitor to see unpublished content, then the Workflow module's content access control will not block the person from seeing unpublished content.


Best way to display PDF in drupal as a slideshow I'm looking to display a PDF on a page, but don't want to outsource the hosting to scribd or slideshare, or one of the other players.  My constraints are basically...

I want to host it on my site.
I want it to look like a slideshow (can click to go forward, navigation backward, etc.)
I want most users to have whatever they need to access it already (ie, if it's SWF, fine.)
I want the whole PDF to be downloadable easily, as a PDF (rather than SWF, etc).

Does anything fit that bill?  I saw on stack overflow, at one time the answer was no.

https://stackoverflow.com/questions/291813/best-way-to-embed-pdf-in-html

But wondering if the Drupal way can offer any better.

Drupal is essentially a framework, it can't do anything that a 'normal' website can't do. This includes displaying PDF files in the format you want.

The only way is to use Flash (as suggested on the SO post you linked to). This would involve either building the SWF file yourself using Adobe's tools, or using one of the dozens of tools available to build a navigable SWF from a PDF file (e.g. SWFTools).

Drupal only comes into the equation when you actually want to display the Flash file.

Some purists might actually argue that this is a bad idea anyway; you should probably allow your users to read PDF files using the software that they have chosen for that particular job.

If you were trying to DRM your PDF for whatever reason then it might make sense, but as you're providing a download link to the direct file anyway I don't think this applies.


How to order input fields? For displaying a content, I can modify the fields order using display and field weights.

However, in a node/add/content-type page the input fields doesn't obey the weight given to the display. How can I reorder the input fields in a node/add/content-type page?

Taking as example the Article content type, on admin/structure/types/manage/article/fields, you alter the field's order in the edit form; on admin/structure/types/manage/article/display, you alter the order the same fields are shown when rendering a node.


View multiple images with Lightbox I have a list of projects in a view with one image for each project, which is displayed with Lightbox.
The client asked me if it is possible to:

Have more than 1 image, but show the first one (done)
Clicking on the image, make the other images visible

How can I achieve this? Is there any method that is not changing the image formatter?

Use Colorbox instead:

Formatter: Colorbox
Content image style: Hide (do not display image)
Content image style for first image: Thumbnail
Colorbox image style: None (original image)
Gallery (image grouping): Per post gallery

Under 'multiple field settings' I set it to display 'all', choosing Display type: 'Simple separator' and changing this from ', ' to ' '.

https://www.drupal.org/node/1026112 #50


Entity operations and redirect destination (using EntityListBuilder) I have an entity collection page that's built with my own subclass of EntityListBuilder. My problem is that the operations links do not set a redirect destination, so after clicking e.g. on an edit link, it is hard for the user to find their way back to the listing.

Redirect destinations work fine with simple links. But I couldn't figure out an easy way how to tell EntityBuilder::buildOperations() to include the destination query string. Any suggestions?

buildOperations is to change the render array for the link wrapper.

The method you are looking for is getOperations. Just pick the operation you want and add the query string to the url.


hide certain fields on the edit form of content profile I would like to hide certain CCK fields on the edit form of the user's content profile. Showing them without editing is done by a custom page. The problem is that if the user edits his content profile node all fields are displayed.

Already tried these:

field permissions module
content permissions module
profile permissions module

but no one worked as expected..

do you have any suggestions what to do?

Content permission can be quite tedious, because once it's installed you have to configure every single CCK field's permission both for view and edit. While you're connected as the admin you will always see everything but you have to test this with a normal user.

However if you just want to hide your field you can do this in several ways.

Hide them in CSS with a display: none; rule.
Hide them with a hook_form_alter()


How can I show referenced terms on other term page with view My web site has two vocabularies for event content type.
Vocabularies: City and Dance School.

School terms use city terms.
I want to show school terms as a list on city term page
( Eg. Newyork Dance Schools).

My city url is ../city/newyork/145

145 is term id.
I changed city/newyork url to /city/newyork/145.But it didn't work.

I tried many combinations with views & Conceptual filter&relationships but no result.

I tried this but empty results.(https://drupal.stackexchange.com/a/74605/88821).

I'm stuck on how to handle it. Any advice please..Thanks

You have to create a list of all School terms, and then use a Contextual filter to feed Views with information about the City term you're currently viewing (City page), so the School terms results can be reduced to show only the School terms that are related to that particular City.

Build Views that list Terms that reference another Term

Create a View of type Taxonomy term, you only need the Block Display, and choose only the School terms vocabulary
Add a Contextual filter from Taxonomy term Category named after the reference field you're using on the School term Vocabulary to reference Cities
Configure it with these options:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term
City
Filter value type: Term ID
Save the View (adjust other options if you wish) and place the Block in a region of your theme, limit Visibility to show only on City term pages.

You should now see the list of School terms on city pages that relate to that City.

Test Contextual filter from Views UI

To test the Contextual filter while building Views you can use the Preview with contextual filters: field.

Enter all and press the Update preview button to see all results irrespective of the Contextual filter.

Enter the number of a City term TID to see the School terms related to it. For example if the term newyork has the TID 16 enter 16 into the Preview field, and you'll see the School term list is reduced to only those which reference newyork.


How would I override misc/ui/jquery.ui.theme.css I have theming being automatically applied by misc/jquery.ui.theme.css that I need to modify. I am using Views Accordian plugin in an instance of EVA for a FAQ category.

What is the Drupal way to override some of the css in this instance?

I read the "How to override a theme function?" but I don't think it would work in this case, I could be wrong.

I don't have enough rep to add comments, but here is my two cents. In addition to Clive's comment, take a look at the weight and group option being used in drupal_add_css, in views_accordion.module. You can implement your own stylesheet here and assign a CSS_THEME for its group and a larger weight number than that of views_accordion, which I'm pretty sure would have used CSS_DEFAULT instead. Here are the docs page. drupal_add_css


How do we replace the token  in a custom module? I am using the following in my custom module but the token is not being replaced. Is this a namespace issue?

$token_service = \Drupal::token();
$post_login = $token_service->replace('<front>');

As already mentioned, <front> is a route, not a token, so you can't use the token API to work with it.

You can resolve it using the Url class:

$path = \Drupal\Core\Url::fromRoute('<front>')->toString();

// $path is equal to '/'

But I'm not sure how useful that will be. Perhaps you want to get the front page that's set in config instead:

$path = \Drupal::config('system.site')->get('page.front');


How can we define twig template based on checkout flow in Commerce 2.x? I am using Drupal Commerce 2.x. I try to build different twig templates based on the checkout flow.

So, I use hook_theme_suggestions_HOOK_alter to register other theme suggestions. However, I can't find any useful variable which we can use in the function.

The following code is what I tried now.

Please give me some advice.

Thanks a lot.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function bootstrap_sass_theme_suggestions_commerce_checkout_form_alter(array &$suggestions, array $variables) {
    if( $variables['form']['#id']=="commerce-checkout-flow-multistep-default" ){
    //add theme suggestions.
    $suggestions[]='my_new_checkout_template';
    }
}

I found out the answer. Share here if someone needed in the future.

I think if we want to define the twig template based on the checkout flow, we shouldn't create ones using the same plugin. (default is Multistep - Default)

Instead, we need to create a new plugin for the checkout flow. I followed the instruction here. https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-flow

After I finished the custom checkout flow plugin, we can create another flow based on the custom one.

Therefore, we can use Implements hook_theme_suggestions_HOOK_alter() to implement what we need.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function bootstrap_sass_theme_suggestions_commerce_checkout_form_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables["form"]["#form_id"];
}


One-time link without valid email address Spam Registrations I have a D6 site that gets a lot of SPAM account registration and they all follow a pattern, however from different IP addresses (often during the following process):

1) User account is created

2) One Time registration link is used to log in

3) account page is visited

4) node/add page is visited

I am using both a Math captcha AND spamicide on the user registration form.
Users have to be verified via email.
Password Reset form also has a captcha and spamicide enabled
I have found out that some of the email addresses being used are from servers that according to their operators are not in service to send or receive email.
This often happens within 1-15 min and either from the same IPs or different IPS for the same username.

So, how are the bots logging into my site? How can they get the one-time link token without checking the email account.

EDIT: The email listed in users.mail is equal to users.init for almost all accounts. There are some that have changed but they look like legitimate users.

Any idea on how to stop this would be appreciated.

FAKE User Data:

uid     name        mail                init                modesortthreshold   theme   signature   signature_format    created access
1975    Gomez.S.    sele.99@hotmailit   sele.99@hotmailit   0   0   0           0       1359319030  0                   0

I can only think of a few ways this is possible:

There's a vulnerability in the one-time-login link system for new users (I'm not aware of one)
There's a vulnerability in some other module (in which case please give some more details of what modules you are running)
Your server does actually resolve the domain hotmailit or has a default place it sends mail and thus the mail is being delivered to somewhere which is then getting the login link and spamming.
Something about your configuration is different than you've described it (e.g. Users do not have to be verified before posting)


Mismatched entity and/or field definitions I have no idea how to fix this, I don't even understand what the problem is.

Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Taxonomy term

The Term ID field needs to be installed.
The UUID field needs to be installed.
The Language field needs to be installed.
The Vocabulary field needs to be installed.
The Name field needs to be installed.
The Description field needs to be installed.
The Weight field needs to be installed.
The Term Parents field needs to be installed.
The Changed field needs to be installed.
The Default translation field needs to be installed.
The taxonomy_term.field_icon field needs to be installed.
The taxonomy_term.field_link field needs to be installed.
The taxonomy_term.field_meta_tags field needs to be installed.

I tried drush entity-updates but it finishes on error:

Character set 'utf8mb4' is not a compiled character set and is not specified
in the '/usr/share/mysql/charsets/Index.xml' file
PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Component/Serialization/Yaml.php on line 54
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected 'class' (T_CLASS), expecting
identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in
/var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Component/Serialization/Yaml.php,
line 54

EDITED (after fixing drush install) I get the following for drush entity-updates

-sh-4.1$ drush entity-updates
The following updates are pending:

taxonomy_term entity type :
  The UUID field needs to be installed.
  The Language field needs to be installed.
  The Vocabulary field needs to be installed.
  The Name field needs to be installed.
  The Description field needs to be installed.
  The Weight field needs to be installed.
  The Term Parents field needs to be installed.
  The Changed field needs to be installed.
  The Default translation field needs to be installed.
  The taxonomy_term.field_icon field needs to be installed.
  The taxonomy_term.field_link field needs to be installed.
  The taxonomy_term.field_meta_tags field needs to be installed.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while performing a schema update. Cannot add unique key                              [error]
taxonomy_term_field__uuid__value to table taxonomy_term_data: unique key already exists. in
Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException() (line 1470 of
/var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Failed: Drupal\Core\Entity\EntityStorageException: !message in Drupal\Core\Entity\Sql\SqlContentEntityStorage-&gt;wrapSchemaException() (line    [error]
1470 of /var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Cache rebuild complete.                                                                                [ok]
Finished performing updates.

The bizarre thing is that all these things (field_icon, link, meta_tags..) are installed.

The site has many modules (both custom and from the drupal community) and it works alright. Should I export it all and do a clean install and then import it?

UPDATE

I did not manage to fix this and it was giving very weird problems out of the blue, although the already created content types and nodes worked fine. After 24h+ of non stop working I reset the stype up from a clean install and copied content manually (tried doing the Configuration > Configuration synchronization with single items, but it didn't work very well).

I can report now that the problem is gone. I have no idea what could have caused it or even when.

I got the above errors but with the node table. I am not sure if this is a safe thing to do but I executed the following MySQL command at the prompt:

ALTER TABLE node DROP INDEX node_field__uuid__value;

After that the entity updates executed without any problem.

For the author's problem I suppose you could adapt the command to:

ALTER TABLE taxonomy_term_data DROP INDEX taxonomy_term_field__uuid__value;

The key should be generated the next time you run that entity updates Drush command.


Navigate to next page / previous page based on entity reference field instead of Book module I am trying to create next/previous page links like the Book module.

I have two content types, Chapter and Page.

The Chapter content type contains an entity reference field (unlimited) for pages.

So, each chapter contains an arbitrary number of pages in the entity reference field Pages in Chapter, and these are re-ordered to determine the order of the pages.

Now, on each Page, I want to make links to the previous and next pages based on the values of the parent Chapter's entity reference field Pages in Chapter.

Specifically, using a view or block or similar on the Page, I need to get the Chapter that references the current Page, iterate through the values of the entity reference field Pages in Chapter, find the Page that is immediately before and the Page that is immediately after the current Page, and then output this as a simple unordered list.

I can code a little but I'm not very good so I'm having trouble finding an approach to implement this.

What I tried

I tried to build this in Views.  The problem I encountered was that it is very difficult to iterate through the subdivision entity reference field and filter out the previous and next links.

This is a similar question for Drupal 7 but since Drupal 8 includes so much more in core (Views and Entity References, for example), I think it's fair to ask the question again.

Why not just use the Book module?

I only need the next/previous page functionality, and ideally it would be based on my entity reference field Pages in Chapter.  The book module navigation in Drupal 8 doesn't follow the same patterns as the rest of core (it's not a block, and it's not a menu).  I spent a couple hours this afternoon going through the Book issue queue and cleaning up old issues, and it seemed there is very little effort to "modernize" the module, so I thought it would be better to try to implement this feature on my own.

I can code a little but I'm not very good so I'm having trouble
  finding an approach to implement this.

I started 7 years ago from zero, I only knew HTML and CSS. I learned and mastered Rules & Views. But like 4 or 5 years ago, I ran into scenarios like this one where the existing modules didn't quite do what I needed or felt I had to do overkill/bulky-overhead workarounds with existing modules. So I learned PHP from online resources and I learned how to create custom modules for Drupal.

I highly suggest you improve your backend/coding game. Specially since Rules in D8 is barebones compared to D7.

  I tried to build this in Views. The problem I encountered was that it
  is very difficult to iterate through the subdivision entity reference
  field and filter out the previous and next links.

While it's possible to programmatically solve it with Views, it feels overkill/unnecessary to do this in Views just for prev and next links. A better approach is to create prev_url and next_url variables for Twig. Using a preprocess function we can create and pass those variables to the appropriate template file, node.html.twig in this case.

I've put lots of comments, so you can follow and hopefully learn a thing or two.

In mytheme.theme (since this particular hook can also be used in theme, rather than creating a custom module).

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node']; // obtain current page node object
  if ($node->getType() == 'page') { // check it's a "page" content type
    $page_nid = $node->id(); // get the current page node id
    // get Chapter nids using Entity Field Query
    $query = \Drupal::entityQuery('node')
      ->condition('type', 'chapter')
      ->condition('field_reference', $page_nid); // check if current page NID is set on any Chapter's reference field
    $chapter_nids = $query->execute(); // returns array of Chapter nids
    if (!empty($chapter_nids)) { // check we have a result
      $chapter_nid = reset($chapter_nids); // Extracts the first array value, since we assume current page can only belong to one Chapter.
      $chapter_node = Drupal\node\Entity\Node::load($chapter_nid); // load chapter node
      $referenced_page_nodes = $chapter_node->field_reference; // get referenced nodes
      foreach ($referenced_page_nodes as $key => $referenced_item) { // loop though referenced nodes
        if ($referenced_item->entity) {
          if ($node->id() == $referenced_item->entity->id()) { // check if current page nid equals referenced nid
            $prev_key = $key - 1; // we'll use these keys to access prev/next array values
            $next_key = $key + 1;
            if (!empty($referenced_page_nodes[$prev_key])) { // check if previous key exists
              $prev_url = $referenced_page_nodes[$prev_key]->entity->toUrl()->toString(); // get prev URL
              $variables['prev_url'] = $prev_url; // creates prev_url variable in node.html.twig
            }
            if (!empty($referenced_page_nodes[$next_key])) { // check if next key exists
              $next_url = $referenced_page_nodes[$next_key]->entity->toUrl()->toString(); // get next URL
              $variables['next_url'] = $next_url; // creates next_url variable in node.html.twig
            }
            break; // since we found it, exit from loop as no point in continuing to loop through.
          }
        }
      }
    }
  }
}

Note: Rename field_reference (2 places) to the machine name of your actual reference field in Chapter content type.

In mytheme/templates/node.html.twig, you can place them after the {{ content }} part

{% if prev_url is not empty %}
  {{ 'Previous page'|t }}
{% endif %}
{% if next_url is not empty %}
  {{ 'Next page'|t }}
{% endif %}


Theme the View/Edit Tabs I would like to be able to theme the view/edit tabs.

That is, I'd like to add a class to the <li>.

Any help with this would be much appreciated.

Cheers in advance.

If you want to create tabs use this module: http://drupal.org/project/tabs

else you can modify the tab wrapper in your page.tpl.php and then costumize your tabs with the api functions, to see more read:
http://api.drupal.org/api/drupal/includes--menu.inc/function/theme_menu_local_task


How can I view & access all available variables for a Drupal Commerce cart? For theming purposes I'm trying to access any and all available Drupal commerce cart variables. For starters, I want to give the user feedback regarding the cart in the global nav.

I thought these vars would be available within the $_SESSION var but not so(?).

an example of what i’m trying to do is as follows, via some pseudo code to be put into the global nav…

<!—- Global nav—->

Cart
    <?php  if($items_in_cart == true) {
        echo ‘*’;
     } ?>

or,....

<?php
if($items_in_cart) {
print $total_items_in_cart;
}?>

You can use the function commerce_cart_order_load & commerce_line_item_load() to load the current order(cart) object & order product objects respectively:

  global $user;
  $order = commerce_cart_order_load($user->uid);
  $cart_items = array();
  foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item) {
    $cart_items[] = commerce_line_item_load($line_item['line_item_id']);
  }

In this example, $order contains the Commerce order(cart) object for the current user & $cart_items contain an array of line item (order products) objects.


display the entities that are referencing the current entity with views I have a content type "reservation" and another "room" this is a simple booking app that Im making from stracht "just for learning purposes"

Im using entity reference for make the reservations, so I can create a new reservation and reference the room it belongs to.

So I need to create a view into a block that displays all the reservetions for the current room.

So how to make that in views?
display all the entities that are referencing a certain entity.

You create a View that lists all reservations and then add entity_reference_field as the context.

If you use Panels, you should create a content pane and require a node id as context.

If you don't use panels, you should create a block and provide a default value to the context being the node id from the url. (When you insert the block on the node page, views will grab the node id from the url and use it in the query to display only reservations for that room).


Why is UUID column VARCHAR(128)? Just wondering if anyone knows why uuid columns created by Drupal 8 in MySQL are of type VARCHAR(128), not CHAR(36)?

Basing on this comment by Damien Tournoud, the idea was to support arbitrary string identifiers.
Since Drupal uses a service to generate UUIDs, using a VARCHAR(128) as database field for the UUID would allow a module to override the current service with one using a different implementation, and using more bytes for the UUID.


Why aren't my pages caching? My Cache-Control header is always set to must-revalidate, no-cache, post-check=0, pre-check=0, private on the front page as well as every other page.

I've gone to configuration>performance and set Page cache maximum age to 5 mins, and I've gone to every view and set time-based caching to 5 mins as well.

There are a lot of articles about what to grep for in modules that might disable caching on a page, but these are all for Drupal 7, and I'm on Drupal 8.

What should I be looking for in my D8 modules that might be killing my caches?  If I don't fix this header, CloudFront won't like my pages very much.

EDIT: The poll module was invalidating my caches on pages that were showing poll results, but that didn't turn out to be my main issue.  After disabling the poll module, I was still getting must-revalidate, no-cache, post-check=0, pre-check=0, private, but only on my Firefox Developer Edition (with browser caching disabled, though that probably doesn't matter) while all other browsers (including regular Firefox, with or without caching disabled) are returning max-age=300, public as they should.  I'm concerned, does this mean users can bypass caching under the right circumstances?

In general, this is pretty hard to answer without going into details and knowing what you did with your site. But to give you a few starting points...

To ask the obvious, you are testing this as an anonymous user without a session, right?
If you do have a session, check what values you have in there and who sets them
One thing to grep for is \Drupal::service('page_cache_kill_switch')->trigger();, although it could also be injected, so just look for ->trigger(). That's the equivalent of drupal_page_is_cacheable(FALSE) although are other ways to plug into that too.
Typical modules that set this are captcha or poll
If all else fails, look at FinishResponseSubscriber, that's the one that  adds those headers, specifically look at the request policies that return if a page is cacheable or not (the kill switch is one of those, as is the check for a session)


Custom submit handler stops working when checking route I'm trying to setup a custom submit handler, so I can change the redirect URL after submitting comments. Edit: I just want to send users back to the page they were viewing to begin with, but it's a webform with a couple of route parameters, so I need to save them somehow.

This works (the function is called and I see the debug messages):

function mymodule_form_comment_form_alter(&$form, &$form_state) {
    $form['actions']['submit']['#submit'][] = '_submit_foo';
    kint($form['actions']);
}

function _submit_foo(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    kint('Hello world!');
    \Drupal::logger( 'foo' )->info('hello world');
    exit;
}

This DOESN'T work - i.e. as soon as I add a check on the route:

function mymodule_form_comment_form_alter(&$form, &$form_state) {

    $route_name = \Drupal::routeMatch()->getRouteName();

    if ($route_name == 'entity.webform_submission.canonical') {
        // it's DEFINITELY getting this far!

        kint( 'in conditional' );
        kint( $route_name );
        $form['actions']['submit']['#submit'][] = '_submit_foo';
        kint( $form['actions'] );
    }
}

I know the conditional is being reached, I'm seeing the debug statements.
_submit_foo() isn't called
user is sent to comment.reply instead

Here's a screenshot of the kint($form['actions']):

Context:

these comments are shown inside a view block (format - show: content, single contextual filter, also generated from URL), which is placed, in block layout,  below webform submissions on the standard entity.webform_submission.canonical route - e.g. URL like  /admin/structure/webform/manage/application/submission/123
there's also code in HOOK_comment_view_alter that adds a 'user' cache context to the view (because each user has their comments filtered, so doing it by role is not enough) - in any case, I've tried disabling that and clearing cache
the comments are in a node that has an entity reference to the webform (in case you're wondering how I've managed to combine comments and webform)
comment previews are disabled, and I assume I can rule out that submit action based on the first piece of code working as designed?

The comment form sets an #action to the comment.reply route, which will rebuild the form and no longer go inside your condition as the route there is differdnt.

Whatever you're trying to do exactly, you need to find a different way to do it.


creating a view showing nodes referenced from the currently selected node I have a content type called shops and another called products. on creating a product content, one can type in the shops name, which is provided as an autocomplete node reference field. what i would like to achieve is to create a view showing products in a selected shop. how can i achieve this. I have tried to use reverse node reference module but its not working for me.

Reverse Node References is indead a good solution as it should provide what your are asking for. It's documentation describe how to use for that exact purpose: query children nodes referencing a parent node matching a filter.

Another solution is the Node Referrer module which will create a auto-populated fields on the parent content type with references to all the nodes referencing it. You can then build a view using this field to create a relationship to the children nodes.


Why are there module files like [modulename].pages.inc? I start to learning moding Drupal and I have a look for the current ones. There are files like [modulename].pages.inc or [modulename].api.inc and I can't find why it exists? I read that base files are only [modulename].module, [modulename].info, [modulename].install in Drupal book.

Can somebody explain me these files or post names all this kind files?

It's just a convention used for separating logic out of the main .module file.

The [modulename].pages.inc file typically contains page callback functions (those defined in hook_menu()). Since these functions aren't used in every page request there's no point including them, so they're auto-included from the file property defined in hook_menu() when needed.

You'll probably come across [modulename].admin.inc too, which typically contains callback functions for admin pages.

[modulename].api.php is another convention that Drupal core uses (and subsequently a lot of contrib modules use) to show examples of the hooks they provide, and usually how to use them.

There are other [modulename].[group].inc files that can be auto-included when another module implements hook_hook_info():

  Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.


Moving Drupal database from MySQL to Oracle I've developed a website with Drupal 7 running on standard PHP/MySQL server. Now there's a need to move it to server with Oracle database. While I managed to set up testing environment with a fresh Drupal 7 install and all my modules, to check if they are working with Oracle DB, now all data from original development version needs to be moved to new server.
First option was to use Oracle SQL Developer "Migrate" function, but I ended up manually copying tables from repository to Oracle DB and in the end it failed to function.
Next thing I tried some migration tools. DBTNG migrator failed, because production server has no MySQL or SQLite extensions, so it was impossible to import anything from original database. Backup and Migrate module works only with MySQL. Other modules were migrating limited number of data types or didn't support i18n.
There's a third option of manually recreating all content types, menus, taxonomy, views and other elements, but in the end it would be very convenient to have a system for migration from MySQL to Oracle database.
What needs to be migrated: custom content, fields, blocks, menus, taxonomy, views and all translations.
Does anyone have any ideas how to achieve this task? Preferably using open and free software, but commercial products are an alternative, if they work fast and efficiently.

This may be another long shot and I certainly haven't tried it myself, but assuming that the Features module works on a fresh install on top of Oracle, you may be able use it to export your content types, menus, and views from the MySQL-based site. The Features extra module might allow you to export the taxonomy too.

You could then add the Services module on the MySQL site to serve up content to either the Feeds module or maybe the Web service client module on the Oracle-based site.

Another caveat is that I don't know how well either of these steps would handle the i18n.

Good luck!


How to convert a menu tabs in menu links block? It would be very useful to be able to change the "tabs menu" in "menu links" to specific pages and users roles. In order to customize the UI.

I have not found any module for this.

One of the ways is to simply change the menu type from MENU_LOCAL_TASK to MENU CALLBACK, and then simply create a menu item with the path.

Sample Code:
Cherry pick menu tabs and convert:

function MYMODULE_NAME_menu_alter(&$items) {
  $items['node/%node/view']['type'] = MENU_CALLBACK;
  $items['node/%node/edit']['type'] = MENU_CALLBACK;
}

Convert all at once

function MYMODULE_NAME_menu_alter(&$items) {
  foreach ($items as $key => $value) {
    if ($items[$key]['type'] == MENU_LOCAL_TASK) {
      $items[$key]['type'] = MENU_CALLBACK;
    }
  }
}


Two field multiple values Not sure if this is the correct terminology to explain my question, but I have a client on Drupal 7. My client organization is related to another organization that possibly has a Drupal 8 site. There is a content type that is very similar to both organizations, but the other organization has what seems to be a field group of two fields that allows for multiples in the group, as opposed to the fields. I have used field grouping quite frequently in Drupal 7, but can I duplicate that function?

Sounds like the field collection module would fit your needs perfectly, however that doesn't have a Drupal 8 version yet so it's hard to know what the Drupal 8 site is using to do this.

For Drupal 8 there is a sandbox version of the field collection module however I'm not sure how stable it is.

Another possibility is that they have created a custom field for their site that is a combination of multiple elements.

If you want any sort of compatibility with the two sites' data the I would suggest asking them how they have implemented theirs and use that option for your Drupal 7 site.


Content sorted by machine name not title I've drupal 8 configured on my server then I created content types. Now When I click Add Content on content page all the content types are sorted by machine name and not by their title.

For e.g I've following content types

Alert

Article

Basic Page

Category Landing Page

TimeLine

Events

Visual Navigation

Here all the items have same machine name except for Category Landing Page as it have machine name of "visual_navigation_landing" therefore when I click add content button on content page their I see the list as following

Alert

Article

Basic Page

TimeLine

Events

Category Landing Page

Visual Navigation

Here you can see "Category Landing Page" is at the bottom with visual navigation, can anyone help with this. I just want to sort this list by title and not machine name

Regards.

Just had to apply patch of "Content types are ordered by machine name on node/add"

https://www.drupal.org/project/drupal/issues/2693485

It resolved the issue


Taxonomy - populate child dropdown based on parent dropdown? I am wondering if there is a way to populate a taxonomy dropdown menu with the child terms of a selection made in another taxonomy dropdown menu. I would like to have two taxonomy dropdown menus, one for genre (parent) and one for sub-genre (child). When the a selection is made in the genre menu, I'd like the child sub-genre terms for that genre appear in the menu. Is there a way to implement this?

In Drupal 6, a good way to do this is to use a single taxonomy vocabulary and make the children terms selectable via Hierarchical Select.  This will give you a single menu of the parents and then when users select one of the parent terms the menu of related children will automatically appear.

However, Hierarchical Select hasn't yet been fully ported to Drupal 7 (most notably, Views support does not work at all) and the timetable to do so is unknown.

For Drupal 7, you could try using the Conditional Fields module (or just use the States API directly if you're a developer) to set up logic to show/hide child menus based on the value of the parent menu.  However, doing so has two big drawbacks:

Users will see all fields if they have Javascript disabled.
Depending on the number of items you have, this can get very complicated.


Restricting Video upload to mp4 format alone - in media module I have been struggling put restriction for uploading video to upload only mp4 videos in media module, other media content like image etc. can be uploaded, but I need to put restriction for video type alone.

I am newbie in Drupal, can some one help me in this, what are the places I need to change in media module.

I would really appreciate any help on this. I did found sites\all\modules\media\includes\media.pages.inc file which had a function media_add_upload_validate($form, &$form_state) also then I found sites\all\modules\media\includes\media.variables.inc which had function media_variable_default and media_variable_get. Then I got lost. I am not sure if these are the correct files where I need to make the changes. Also I was wondering if I have to make change in Drupal core module to do the video upload restriction to mp4 perfectly.

Thanks

Go to admin/config/media/browser to change settings.


Trouble passing PHP variables to JS using "attach" Module-noob here. I've seen plenty of threads on this topic in general but haven't found any concerning use of "attach." I'm working on a fairly simple module that applies some JavaScript to every page on the site. It was working fine, but pareview told me not to use drupal_add_js() in hook_page_build(), instructing me to use attach instead. I can't figure out how to get my PHP variables over to my JS using this method.

The JS file itself is loading, but it is not receiving the data from the PHP variables. From what I have read, I understand that the following is the way to accomplish what I am trying to do, but obviously I've got something wrong somewhere. Here is my code:

mymodule.module:

function mymodule_page_build() {

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
    array(
      'data' => array(
        'mymodule_status' => variable_get('mymodule_status', 0),
      ),' => 'setting',
    ),
  );
}

mymodule.js:

(function ($) {
  "use strict";
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      var moduleStatus = Drupal.settings.mymodule.mymodule_status;
      var milk = 'milk';
      $(document).ready(function () {
        // Debug:
        console.log('first');      // works
        console.log(milk);         // works
        console.log(moduleStatus); // Says mymodule is undefined
    }
  };
})(jQuery);

Thank you for any help you can offer.

Have a look on this page

For getting the value of a variable that has been set in the module you have to use like this Drupal.settings.<modulename>.<variablename>

In your module file

function mymodule_page_build() {
  $status = variable_get('mymodule_status', 0);
  drupal_add_js(array('MODULENAME' => array('mymodule_status' => $status)), 'setting');

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
  );
}

So in your case it should be

Drupal.settings.mymodule.mymodule_status


How to create a pie chart using the chart module in Drupal 7? I'm trying to create a pie chart using the chart module. I was able to create a pie chart that looks similar to the pie chart shown on https://developers.google.com/chart/ . But I am not getting any percentages.

My Question: What is needed to also show those percentages, or what might I be doing wrong)?

Note: I cannot do those interactive additions, but I can live without them.

Yes it is possible to do so. Use the google chart tools to achieve that. This module also integrates with the views module nicely.


How can I create a custom calculator on a drupal site? What I want to do is have a page that collects a few pieces of information from the user and then calculates a result of a formula.

I do not want to store the information at all, and was thinking I may need to use the PHP Input type.

I see you've tagged this question with JavaScript, so it looks like you want to make a calculator using JavaScript.

To do this, you could make a custom module.

Create a module called calcform.
Create calcform.js
In your calcform.module you could create a custom block that has the calcform form.

You'll need to checkout: Creating modules | Block examples

function calcform_form(&$form, &$form_state){
  $form['number1'] = array(
    '#type'=>'textfield',
  );
  $form['number2'] = array(
    '#type'=>'textfield',
  );
  $form['calc_button'] = array(
    '#type'=>'button',
    '#value'=>'Calculate',
  );
  return $form;
}

Then in your JavaScript:

(function($){

  Drupal.calcform = {}

  Drupal.behaviors.calcform = {
    attach:function(){
      Drupal.calcform.bindEvents();
    }
  }

  Drupal.calcform.bindEvents = function(){

    $('#calc-button').click(function(e){
      // Prevent default button from submitting the form.
      e.preventDefault();
      // Do your magic here.
    });

  }

}(jQuery));

This is all very pseudo-cody, but it's the general idea.
You actually don't need to write ANY JavaScript. You could create a form submit function that does the calculations and prints out the result to the form. You can then use the $form['#ajax'] capabilities to do all the magic for you.

Drupal is amazing like that.


How to translate a view and keep contextual filters? I'm building a bilingual website (French/English). I created the "user biography" for me to display later in the view. The biography is translated.

The view is called in the page : biography.php?id_author=405 with a contextual filter (405 in this example). Now when we click to see the other language version, we are redirected to "biographie.php" (in french), but we lose the parameter.

How can i keep the parameter ?

Thanks

I decided to "patch" the code, by adding the paramaters using Javascript.

 if($('.language-link').length > 0 && location.search != ""){
        $('.language-link').each(function(){
            var href = this.href;
            if (href.indexOf('?') != -1) {
                href = href + location.search;
              }
              else {
                href = href + location.search;
              }
              $(this).attr('href', href);
        });
    }


How to set static field on Display Suite i would like to set a static field using Display Suite in Drupal 7 but don´t know how.
It´s a text snippet that won´t change so i want to place it using a field.

Can somebody help me how to do it?

Thank you very much.

Kind Regards

Add a code field to Display Suite. In that code field you add your html (with token support if token is installed). Then just place the code field in the display tab for the content type.

Tutorial here.


How to display the table select query values in the same form in drupal 7? Just newly working on Drupal 7. Using Form API I created a text field with one submit button. I need to pass the text field's value in the select query as a parameter. I need to output the result set of the select query in table layout. Please help me out by providing a set of codes.

This is actually very easily done out of the box with form-api, you just have to know how to use it. You have to read up on drupal 7 forms, especially the validate and submit functions/hooks. A quick and dirty example to output form values in submit function (called after function form_*_validate() hook) is shown below.

function form_example_tutorial_7_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. name="@first @last", year of birth=@year_of_birth',
    array('@first' => $form_state['values']['first'], '@last' => $form_state['values']['last'], '@year_of_birth' => $form_state['values']['year_of_birth'])));
}

Of course, you can also show messages like this in the validation step. You would need to change above code to use whatever variables you want shown.

Tons of very helpful form api code examples here.

If videos are more your thing, these explains the basic basics ok.

Cheers!


Showing Discount labels for products that are linked to any discount offer? I created a view (table) of my products and I want to display the ID field of the related discount.

So I added a relationship with Trade Discount Offer referencing products from commerce_free_products and referencing Trade Discount Trade Discount Offer from commerce_discount_offer
Then added the field Trade Discount: Discount ID I have my column but in the 0 if I add (referencing Trade Discount Trade Discount Offer from commerce_discount_offer) Trade Discount: Title for administration (Title for administration) my column is empty.

What did I do wrong?
I found it this ticket but it does not help.

If by "ID field" you mean the name of the discount shown to customers, this is doable.

You must have a product that is the object of a "Free product" offer.

Once that is done, you'll need to add two relationships to the view. The first, you've already gotten is the link from the product to the offer:

  Commerce Discount Offer referencing products from commerce_free_products
  Trade Discount Offer referencing products from commerce_free_products

The other relationship is the link from the offer to the Discount entity itself:

  Commerce Discount referencing Commerce Discount Offer from commerce_discount_offer
  A bridge to the Commerce Discount entity that is referencing Commerce Discount Offer via commerce_discount_offer

Then you can add fields attached to the Commerce Discount entity:

Commerce Discount: Name
Commerce Discount: Admin title

And now your labels should be visible.


Drupal 7 Custom Content form_alter validation Hi I was wondering if anyone could give me some advice on this.
Basically what I have is a custom content type created by the content creator GUI, I am writing a custom module to alter the appearance and values of the content form.

like so:

function sswap_content_validation_form_alter(&$form, $form_state, $form_id)
{
if (isset($form['type']) && isset($form['#node']))
{

if ($form_id == 'advertise_node_form')
{

  // Unset the options we don't want user to see.
  unset($form['menu']);
  unset($form['comment_settings']);
  unset($form['revision_information']);
  unset($form['author']);
  unset($form['options']);
  unset($form['path']);

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

  // we need to tell the form to follow a validation function
  $form['#validate'][] = '_surplus_cck_validation';
  $form['#submit'][] = '_surplus_cck_submit';
    }
  }
}

This all works fine and I am able to alter values in the form_alter section as expected, however once I get to the _surplus_cck_validation custom function I am unable to change values, basically what I am doing is checking if a value is X if not I'll replace it with something more suitable after some processing. At this point I can't even change X to a static string though.

To alter my form content I am using:

$form['field_adpostcode']['und'][0]['value']['#value'] = 'TESTING';
$form['field_adpostcode']['und'][0]['#value']['value'] = 'TESTING';

These lines do actually work in the form_alter part as mentioned. I should also note the function for surplus_cck_validation is being called I have experimented with a few echos and notices, and the $form and &$form_state are being passed to it also.

Any help on this would be greatly appreciated I've spent the last few hours trying different things and digging down into the form structure with dsm and debug, but can't seem to find what I need.

Perhaps try $form_state.

$form_state['field_adpostcode']['und'][0]['value']['#value'] = 'TESTING';
$form_state['field_adpostcode']['und'][0]['#value']['value'] = 'TESTING';

I suspect the array structure is different but you get the idea.


commerce show message if anonymous user adds product to cart What I am trying to accomplish is :

If an anonymous user adds a product to the cart, I would like to display a message on the site that says : Login to check out

what I did is the following:
Added a new rule with the event: After adding product to cart

Condition: Data comparison, Data to compare: site:current-user:roles, The value to compare the data with: anonymous user

Action: Show message on the site : Please Login or Sign Up in order to checkout

but the message still does not show if an anonymous user adds a product to the cart

OK things worked out when I changed the condition to : user has role and passed in the current user as a parameter

I would still love to know where I went wrong in my first approach


Views Geolocation field proximity: How to alter views field setting I'm using a Geolocation field in views to order results by distance. The module provides a special views proximity plugin/field, which can be used in the "sort" section of the view. This plugin/field has a "proximity setting" (lat/long) to define the center point for distance calculation. I got this far in views UI and this all works.

I now need to programmatically change that center point based on a custom logic derived from the current user, but I don't know which views hook to use to alter this field setting.

Tried, didn't work:

function MYMODULE_views_pre_view($view, $display_id, &$args) {
  //my field's machine name is "field_geo"
  $geoField = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofield) is empty

  //suffix "_proximity" seems to be added by geolocation module, but does not work either
  $geoFieldProximity = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofieldProximity) is empty
}

I've got two questions:

Is pre_view the correct hook to alter the field setting? (If not, which hook should I use instead?)
How to I get/set those field settings?
I thought I need to use $view->display_handler->getHandler() but didn't get any results.

Digging through the exported views.yml config helped me to get on the right track:

function MYMODULE_views_pre_view($view, $display_id, &$args) {

  if ($view->id() == 'WHATEVER' and $display_id == 'MY_DISPLAY') {
    $allFields = $view->display_handler->getOption('fields');

    $user = _MY_BUSINESS_LOGIC();
    if (!$user->get('field_geo')->isEmpty()) {
      $allFields ['field_geo_proximity']['proximity_lat'] = $user->get('field_geo')->lat;
      $allFields ['field_geo_proximity']['proximity_lng'] = $user->get('field_geo')->lng;
      $view->display_handler->overrideOption('fields', $allFields);
    }
  }
}


Ecommerce Subscription How to setup subscription for a particular role using the ecommerce module.
I want certain users to only be able to access certain content using a role. On registration I want the user to have to pay for a subscription to access special content.

This answer is based on the tutorial http://www.stonemind.net/blog/2008/02/07/tips-for-implementing-a-subscription-based-drupal-site/.
Here is further information in EC subscriptions:Role products
http://drupal.org/node/88239

Firstly the user needs to install various modules

All modules in the E-Commerce Core package.
Your payment gateway choice.
Generic Product
EC Recurring.
EC Role.

It is important to note that subscription are intangible. They are not solid objects and therefore don't have an arrival time. For this reason the type of product is a "Non Ship able product"
E-Commerce configuration (at /admin/ecsettings)

The tool mentions that the way rebelling is achieved is due to the cron tasks. So therefore its imperative that is can be achieved.

Multiple roles can be purchased to achieved so there can be different types of subscriptions. To enable only certain users to access  certain content the node option premium module.  http://drupal.org/project/nopremium. This is the replacement for the module premium that was used in drupal 6.

If you want different types of roles to be only able to see a teaser. You can use the contemplate module to achieve this task. This means that you could have content that certain users will not be able to see. A good example is news site which give a teaser and ask you to register to find out more information.

http://drupal.org/project/contemplate