Block visitors based on geographic location conditionally in .htaccess on multi-site install I have a Drupal 6 multi-site install that runs numerous different websites for a single instance of Drupal. These web sites attract worldwide traffic which is what my client wants, with one exception.

One of the sites attracts lots of visitors from Italy, which my client doesn't want as it creates problems for them. As I result of this I would like to block visitors from Italy visiting the site by blocking them based on IP addresses (note that I already have the IP addresses and the method of blocking the visitors). The way I want to block the visitors is in the .htaccess file like so:

<Limit GET HEAD POST>
order deny,allow
deny from 2.16.70.0/23
deny from 2.19.16.0/20
etc...
allow from all
</Limit>

My issue is that if I put that code into my .htaccess file, it will block visitors from Italy visiting each of the websites in the multi-site install, which I don't want. I simply want to block them on a particular website, perhaps based on the URL or something. Can anyone point me in the right direction?

You can add this restriction directly in the vhost of your client instead of .htaccess. At that level you should hace a vhost per site.


How could i configure drush to be always affirmative and verbose in a drush.ini-file? Could I configure drush for non-interacive usage from bash-scripts to be always affirmative as I would pass the --yes and -v-option in /etc/drush/drush.ini? I'm aware that I could set a bash-alias and that I could set it in /etc/drush/drushrc.php. But for reasons of clarity I'd like to use the ini-style-configuration.

Drush will not read options from php.ini / drush.ini by default.  Your best option would be to use a bash alias, or set $options['yes'] = TRUE; in a drushrc.php file.

If you really really have to set an option in drush.ini, you could hack this functionality by writing a policy file.  It would look something like this:

function policy_init() {
  if (ini_get('drush_yes')) {
    drush_set_option('yes', TRUE);
    // Drush does not expect a globla option to change
    // at this time, so you need to re-call _drush_preflight_global_options().
    // This is not a public API, so the name may change, etc.
    _drush_preflight_global_options();
  }
}

The only motivation I can see for doing this is if you already have some fancy mechanism for selecting your php.ini based on context.  If you wanted to do that, then put policy.drush.inc in ~/.drush, or some other location where Drush searches for commandfiles.

I have not tested this; post a follow-up comment if you really want to do this and have trouble with it.


Images within content of page but not separate fields I would like to create a basic page within Drupal 7 that would consist of some images mixed with HTML. I would use CSS to position the images within the HTML content, sort of like a magazine or newspaper article.

I would like for the end user to be able to edit/replace these images along with the HTML yet the image field did not seem to give me flexibility to place the image within the HTML content.

I could upload the images via FTP directly to the ../sites/default/files directory and manually reference the images ...

<img src="../sites/default/files/image-name.png" />

but that would not allow the end users to manage the images from with Drupal, plus I would need to give them FTP access to the filesystem which I would like to avoid.

Any suggestions on how to work around this?

You can do this with the following modules:

WYSIWYG
CKEditor module with CKEditor library
IMCE module:

Lot of setup and config, but once its there, its there so to speak.


Why do I get Call to undefined function updatedb() I am attempting to wrap my head around some of the advance features of drush.  i am using Drush User's Guide and it's example code and ran into this error [Fatal error: Call to undefined function updatedb() in /home/trakz/.drush/user_blocker.drush.inc on line 68]from the code below.

Line 68 is: [$query= updatedb('users')]

Can anyone tell me what is wrong?  I have checked the Drush guide and updatedb() is valid.  Googling around did not help.

drupal 6.28
drush 5.7

any assistance woudl be greatly appreciated.  Thank you.

/**
 * Callback implementation for user-blocker command
 */
function drush_user_blocker() {
  // Grab all languages given. If any.
  $languages = func_get_args();

  // See if we received a date from which we should filter
  $since = strtotime(drush_get_option('since', '2 years ago'));

  // Perform the update over the users table
  $query= updatedb('users')
  ->fields(array('status' => 0,))
  ->condition('uid', array(0, 1), 'NOT IN')
  ->condition('access', array(1, $since), 'BETWEEN');

  // Add the condition to filter by language
  if (count($languages)) {
    $query->condition('language', $languages, 'IN');
  }

  $total_blocked = $query->execute();
  drush_log(dt("Blocked !total_blocked users", array('!total_blocked' => $total_blocked)), 'success');
}

drush updatedb is a valid command.

updatedb (updb)       Apply any database updates required (as with running update.php).

However, I'm not sure about using it in place of db_query.

In D7 you would use db_update there.

In D6, you're stuck with db_query

It looks like a syntax error in the module code, it probably needs to use D6 style db_query


reCaptcha does not display on modal window(colorbox) webform I have a webform that I want to add a reCaptcha to. So far I've done everything properly, the webform will display a recaptcha box below the form when viewing the node form. I have a modal window webform (thats similar to an opt-in form), that uses ajax to grab the specific webform and display it as a block in the window. Now the issue is that the reCaptcha does not display below the form.

I've tried replacing the recaptcha with a math challenge captcha, and it would display properly on both the webform and modal window.

The good news is that the ajax webform shows an instance of the captcha when you look at the html.

<input type="hidden" name="captcha_sid" value="561">
<input type="hidden" name="captcha_token" value="4bbbf337ec22df5fe3befde6f601601d">
<input type="hidden" name="captcha_response" value="Google no captcha">

//g-recaptcha is where the captcha is supposed to be rendered, however it is empty

I've been stuck on this issue for almost a week. Is there suggestions or approach that I should take?

Fixed the issue, there was a patch on issue's forum on the Module page.
71 @ https://www.drupal.org/node/2493183


How to change a filter handler of the view? I have created a nice Filter Handler for my View, and I set it up using hook_views_data_alter.

Does this mean that this will ALWAYS be the Filter Handler for this particular field? What if I want a different Filter Handler later, in a different view?

How can I specifically say "Only use the X handler on page X?"

For posterity, I thought I'd outline more of what I was trying to accomplish here:

I have "Friends" page and a "Content" page. On the "Content" page, I wanted to be able to filter by "Content posted by my friends." However, on the "Friends" page I want to filter by "Users in my Groups." Both of these query on the user.uid field, so it was making the filters the same, even though I wanted totally different logic for the two views.

I always take the following approach: Copy the existing views_data code via php:

// Copy the existing definition.
$data['table']['field_special'] = $data['table']['field'];
// Force the real field, so views still consider it as a different field in SQL.
$data['table']['field_special']['real field'] = 'field';
// Set a special handler.
$data['table']['field_special']['field']['handler'] = 'foo_handler_field_...';

This allows you to easy reuse the custom handler if needed, but at the same time not conflict with existing views.

In contrast to the approach of berliner (which certainly works) this does not add any runtime code execution, which adds potential bugs. This approach just uses basically configuration.


Why I don't get the encryption methods? Encrypt module I'm working on a Drupal 8 project. I want to send a link to the user via email and passing as parameters some user details that I want to encrypt. When the user clicks the link, I will get those encrypted data from URL and I will decrypt them.

After some research, I decided to use the Encrypt module.

I installed it, I added my key in settings.php, I also created a key in admin/config/system/keys, and now I'm trying to create an encryption profile, but the encryption method list is empty.

Is this the correct way to implement data encryption/decryption? If so, how can I get the encryption method list?

The Encrypt module provides an API, but no encryption methods. You'll need to install a module that provides one. I recommend the Real AES module


How to load XML to SWF on each node? Here is my problem: I have 2 SWF files for a crossword puzzle: first one is for creating puzzles and outputting XML files upon clicking the "Save" button and second SWF is displaying those puzzles to the users by listing and loading those XML files and upon clicking it loads the selected XML file into SWF. This is okay so far here. But I need to use web interface so that a user inside a website sees those XML list on the web page and upon clicking/selecting, the second SWF will load with the related XML file. I need this because I will organize those XML files with some modules inside drupal such as Organic Groups. So each user will see different lists of XML files. For example, I have 2 groups created with my organic groups module inside drupal, each group has a different editor. So those editors will create puzzles and will set them for their groups with Organic groups module.

After some research I think I figured a possible and reasonable way to achieve this with a help of a friend. So, to wrap up things so far;

-I have a puzzle maker swf and a puzzle player swf.
-Puzzle maker actually generates some xml files that could be played by Puzzle player(swf).
-These xml files are to be stored in Drupal.
-The stored xml files behaviour is same as Organic groups behaviour. Where the files belonging to a particular group is accessible to the group members.

So the idea of implementation is here,

1.) A custom page for creating puzzle using Puzzle maker(swf). A "Puzzle Data" content-type to hold the xml files. This node is under organic groups.

2.) The editors creates puzzle (things okay so far here) and the xml file will be downloaded to editor's computer.

3.) Now the editor may upload the xml file and attach it to "Puzzle Data" node.

4.) Now I may create a view to display all the "Puzzle Data" nodes in a Organic Group with Views module.

5.) Now comes the tricky part. The actual node display should be a Puzzle Player(swf) that uses the "xml" file uploaded to the node.

After some research I may achieve this either Creating a custom node template or creating a custom field formatter. So here I need a bit help with the php codes part so that each node will post/sent the attached xml file to puzzle player(swf) attached to the node.

(Btw this 2 step: downloading xml and later uploading it to a node is something unwanted, maybe puzzle maker(swf) can be embedded inside node/add path for Puzzle Data content type and editors may download xml so will upload it again into the field on the same page. )

You would create a new node.tpl.php by copying the existing one from your theme or from the node module (part of core).  Rename your copy node--mycontenttype.tpl.php and place it in your theme directory (along side your other .tpl files).

Install devel and use dpm() to explore the $content variable.  Hide the XML field and extract it's file id (fid) and pass it to file_load.  This should return an object containing your file path, again use dpm() to explore this array and get your file.

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

Embed your .swf directly into your new node.tpl.php and pass the XML to it as you would any other Flash argument.


How to add a views block in a basic page via editor? I have created a basic page through the editor of drupal 7 and I have started coding the body using the PHP code text format. So far so good, apart from the fact that I want to embed a block from a view (showing three nodes) and the code below which seems to work when I put it directly into a php file, doesn't activate within the body. I am using Bootstrap by the way.

    <?php print views_embed_view("mylatest_events", "block"); ?>

Flavour text to describe the view here.

Any suggestions?

Have you tried to use the simplest php-code inside your body field ?
For example,

<?php print 'The simplest text'; ?>

It can be situation, where filter for content of your field is configured wrongly.

Moreover, it would be nice to try names of the view and view mode.


How to use other properties in hook_entity_property_info_alter() I want to extend the entity properties of OG-Membership to use it as a token in rules.

It works fine adding the property (for example the string 'test' as returned in the getter_callback is printed in a reaction rule (sending email)).
But I could not find out, or how to debug/access, the other properties present in OG-Membership in the rules context. To put it differently:

How can I access the group id ($gid) of the OG-Membership in my getter callback?

This works well:

function mymodule_entity_property_info_alter(&$info){
  $properties = &$info['og_membership']['properties'];

  $properties['og_custom_property'] = array(
    'label' => t('My custom Label'),
    'type' => 'test',
    'description' => t('OG Membership Custom Property.'),
    'getter callback' => 'mymodule_callback'
    );
  return $info;
}

But here I cannot access the $gid, or anything, for that matter:

function mymodule_callback(){
  //do some stuff with the $gid and $etid of the OG-Membership
}

Any help is appreciated; maybe someone knows how to debug the in rules available properties?
Thanks.

If you use hook_entity_property_info_alter() you have access to the entity in question in the callback as well.

function mymodule_callback($item){
  //$item is the entity in question in my case $og_membership
  //hence I can acces the gid like this:
  $og_membership = $item; //redundant, just to show what I mean
  $gid = $og_membership->gid;

  //either do some more stuff or just return the gid as an example
  return $gid;
}

Now I can access the property and it returns the gid. For example in rules:

[og_membership:og_custom_property]

Hope this is useful to others as well.


How to Filter Node Reference Field Values Using Multiple Views? I have a node reference field called field_parent_dept. I re-use this field in several content types.  The list of nodes that can be referenced are provided by a view.  The values are filtered based on logged in user.

I'd like to add this field to a new content type, but the departments need to get filtered in a completely different way.  I need a new view to accomplish the filtering.  It appears I need to create a new field, because the view is a field setting.  Field settings apply to the field everywhere it is used.

Are there any other options?

According to my understanding and the following answer, I believe you can reuse that same field. It will get cloned and then you can go and modify the field settings. This will affect only that field instance, specific to the entity/bundle (node/content-type).

Hope this helps!

Difference between Field and Field Instance?


Are Wysiwyg and CKEditor modules incompatible now? Apologies if this question has been raised elsewhere, but I couldn't find anything directly related to it.

I'm in the process of setting up my first Drupal site. I want to be able to include images in the body of posts but without turning on "full HTML". Chapter 4 of Using Drupal (2nd Edition) describes a way of doing that involves using both the Wysiwyg and CKEditor modules.

However, when I install the latest versions of both modules (Wysiwyg: 7.x-2.2; CKEditor: 7.x-1.13), I get the following message on the CKEditor configuration page:

  "The WYSIWYG module was detected. Using both modules at the same time may cause problems. It is recommended to turn the WYSIWYG module off (click here to disable)."

If I ignore the message and try to configure Wysiwyg I get the following message:

  "The version of CKEditor could not be detected.
  Extract the archive and copy its contents into a new folder in the following location:
  sites/all/libraries/ckeditor

  So the actual library can be found at:
  sites/all/libraries/ckeditor/ckeditor.js"

But ckeditor.js is saved in the above directory.

I've tried installing other editors besides CKEditor (e.g., TinyMCE), but I get a similar result.

I've got CKEditor installed and working fine, but it only generates HTML code, not tags that the Media module can process. Consequently, images only appear in "Full HTML" mode, not in "filtered HTML" mode.

I'm really interested in finding out how can I include images in posts using filtered HTML mode (either by using CKEditor/Wysiwyg or by some other method). Very grateful for any suggestions.

Yes you use one or the other of the CKEditor & WYSIWYG modules.

They both provide the same sort of functionality.

As to which is better is up to your preference. You can try them both and see which one you prefer.


How to style a view in Omega I want my view to use Omega's grid system, but could not find a way to do it.

There is this thread http://drupal.org/node/1491678 that suggests using "Views Column Class" module. Is that the best way to do it or I am missing something?

Yes, Views Column Class is the best way to do it in my experience.

All you need to do is set the row class to an alpha grid class, and the number of columns for the display mode you're using, e.g.

and the module will take care of adding the alpha/omega classes to the appropriate elements on your page, giving you properly responsive views for very little work.

It's worth remembering that a 'row' in the context of a floated list is each individual item, not a row of x number of elements. So when you apply grid-4 etc, it's applied to each individual element, not the whole row. It can be confusing at first.


Fatal error: Unsupported operand types in common.inc on line 2287 when registering new user I am receiving this error message when registering as a new user on a site-in-progress:

  Fatal error: Unsupported operand types in common.inc on line 2287

The actual line 2287 is:

  $query += $options['query'];

Here is the surrounding code:

// Without Clean URLs.
  else {
    $path = $prefix . $path;
    $query = array();
if (!empty($path)) {
  $query['q'] = $path;
}
if ($options['query']) {
  // We do not use array_merge() here to prevent overriding $path via query
  // parameters.
  $query += $options['query'];
}
$query = $query ? ('?' . drupal_http_build_query($query)) : '';
$script = isset($options['script']) ? $options['script'] : '';
return $base . $script . $query . $options['fragment'];
  }
}

I use LoginToboggan, not sure if that has anything to do with this issue. Does anyone have any ideas on what might cause this issue and how it can be fixed?

Thanks!

The problem is in the url() function and is because either the l() or url() functions are being called with a 'query' that is not an array.

Those functions expect the 'query' option to be an array and it is likely that something is passing a string into them.

Do you have any custom code in modules or themes that is calling l() or url()?

I see you have already seen the issue at http://drupal.org/node/1275048

To debug the problem, add this code to the line before the error line:

if (!is_array($options['query'])) {
  die(print_r(func_get_args()));
}

Then reload the page with the error and you will get a bunch of text on a white screen.
Post that text back here and/or that drupal.org issue.

After your latest information
There is a bug in logintoboggan that makes this break whenever you have a redirect url with a query string in it (that is the part with ?key1=value1&key2=value2).

I have made a patch to fix it in the issue mentioned above.


How to block users from editing a node of a content type? (D7) This should be easy, but I can't figure out what I'm doing wrong: In my Drupal 7 site, I've defined a content type in the usual way.  I want regular users to be able to create instances of that type, but not edit them.  Trivial, right?

The content type is in place, and, in admin/people/permissions, there are entries like "My Type: Create new content" and "My Type: Edit own content".  I've set the checkboxes so authenticated users have "create new content" permission but not "edit own content" permission.  Just to be on the safe/superstitious side, I've cleared the cache and done a Rebuild Permissions.  But, nevertheless, my regular users can still edit their nodes.

Shouldn't this work / any ideas what's wrong?  Do I need to write a _node_access handler?

Oops: My bad.  I had given authenticated users "bypass node access" permission to deal with a pending bug in the apache_solr module.  Once I dropped this permission, everything worked the way it was supposed to.

Sorry for cluttering up things...


How to configure the views slideshow from the CMS? Currently I am configuring the views slideshow from the views edit. where I can set the interval time, slide show type and effect, control of the slideshow pause/stop/start etc.

My need is that I want to configure all these things from the CMS not from editing the view.

Is it possible? Is there any module which will do this? Or any other alternative for this?

Thanks in advance.

You can check a very helpful module in Drupal JCarousel. It has views integration and the settings which you want as well.

  This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.


Mapping field columns with D8 migrate and d7_node source plugin I'm trying to write a D8 migrations files but the following one isn't working on the source 'body/value' because it resolves to a null value instead of the intended string.

id: my_d7_node_news
label: 'Nodes (News)'
langcode: en
status: true
dependencies: {  }
class: Drupal\migrate\Plugin\Migration
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
source:
  plugin: d7_node
  node_type: news
process:
  nid: tnid
  vid: vid
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  'body/value':
    plugin: get
    source: 'body/value'
  'body/summary':
    plugin: default_value
    default_value: some summary
  'body/format':
    plugin: default_value
    default_value: rich_text
destination:
  plugin: 'entity:node'
  default_bundle: news

I tried multiple writing for the source: 'body/value' (e,g: source: body_value, etc, ...) with no luck...

Which syntax should I use to make successful mapping on body/value: body/value using the d7_node source plugin?

Something like this:

  body:
    plugin: iterator
    source: body
    process:
      value: value
      format:
        plugin: default_value
        default_value: filtered_html


Flag a node after click on the link I want to check if user has downloaded the file so afterwards I will allow him to post a review. To do that I want to flag the node after user download file, flag the node and allow flagged node to be commented. I have a script:

global $user;
$flag = flag_get_flag('downloaded');
$node = node_load(arg(1));
$flag->flag('downloaded', $node->nid, user_load($user->uid), TRUE);

but I don't know how to make that event to occure when clicked on link. Link is in span.file a

Does anybody have an idea how to achieve my goal? I will be so grateful for any answer.

If you're using the private file system, you can make use of hook_file_download, it is normally used for granting access but I don't see why not you can use it for flagging stuff.

See an example of this in Example of hook_file_download

If you're using the public one, it will be way trickier, you're going to need to wrap the download link to react with your custom code, this could be done by replacing the download link like the Public Download Count module does, or providing your own hook_menu callback that is called via ajax to flag the content, but then you depend on whether the user has js enabled or not.


Solr facets returning deleted TIDs This seems to be a common issue when deleting terms linked to indexed content via term/entity reference, but no solution has worked so far.

I am using the following:

Drupal 7
Solr 5.5.3
Search API 7.x-1.22
Field reference delete 7.x-1.0-beta1

The terms are linked via a term reference field on a node.

When the term is deleted, Field reference delete module informs Solr the referenced nodes need reindexing, which removes all articles containing the TID. This works fine. However after reindexing the term ID is still shown with (0) results on display instead of the term name.

Only deleting all indexed content and reindexing removes the facet as expected.

Before this, querying Solr for facets returns this:

{
  "response": {
    "numFound": 1139,
    "start": 0,
    "maxScore": 0.43971312,
    "docs": [
      {
        "item_id": "124618",
        "score": 0.43971312
      }
    ]
  },
  "facet_counts": {
    "facet_queries": {},
    "facet_fields": {
      "im_field_tax_tags": {
        "1107": 8,
        "1108": 212,
        "1109": 29,
        "1110": 619,
        "1111": 0,
        "1112": 61,
        "1114": 59,
        "1115": 105,
        "1117": 48,
        "1118": 35,
        "1119": 67,
        "1121": 120,
        "1124": 234,
        "1125": 15,
        "1127": 60,
        "1129": 6,
        "1133": 304,
        "1134": 59,
        "1214": 856,
        "1215": 317,
        "1216": 397,
        "1217": 819,
        "1219": 597,
        "1220": 6
      },
    },
    "facet_dates": {},
    "facet_ranges": {},
    "facet_intervals": {},
    "facet_heatmaps": {}
  }
}

Note 1111 has been deleted and has 0 results, yet still appears in Solr's list of facets. I presume this is cached somehow. Searching for im_field_tax_tags:1111 also returns 0 results.

It is also worth noting that the facet display has a Minimum facet count of 0, as the way they are displayed requires empty facets to be shown. I understand changing this to 1 would solve the problem (I suspect this is a more common configuration, which may explain why others have had more success), but it is unfortunately not an option.

Any help would be appreciated.

Go to Solr Admin (usually http://localhost:8983/)

Go to Core Admin or your core selector and click Reload. When refreshed, you should see a green check mark on the "current" field. After this, your solr cache will be deleted and refreshed with new indexes.


How can I import multiple taxonomy terms using Feeds and the Feeds XML Parser Currently the xml feed looks something like this

<hotel>
    <hotel_facilities>
        <facility>Gym</facility>
        <facility>Restaurant</facility>
        <facility>Bar</facility>
    </hotel_facilities>
...
</hotel>

I've trying to import all the facilities as taxonomy terms using the Feeds XPath Parser but I am only able to import a single facility. I'm not sure if the module supports this. What currently happens when I set the context to hotel and the xpath query as hotel_facilities/facility it results in the error:

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'Restaurant', 'Bar'' at line 1

If I use the query: hotel_facilities/facility[1] it returns and inputs the term into my taxonomy vocabulary, but I require all the terms to be added.

Is there a query/module or setting that I need to run; or is this a limitation of the Feeds/Feeds XPath Parser parser modules?

Feeds Tamper will sort this out (I know this for a fact, as I've done this in the last week).

Set your query to hotel_facilities/facility which will return a comma separated list of facilities (you won't see this array as you'll be exploding it. Feel free to dpm() it though). Using Feeds Tamper, you can explode this array.

Go to your feed, and there will be a "Tamper" menu item at the top. If you click this, and then go down whatever xpathparser if importing these facilities. Then click Add plugin and find the explode plugin (you can find it under List)

Don't forget to set your Feeds mapping to Search taxonomy terms by: Term Name and check the "Auto create" checkbox.


How to add confirmation to ajax link? I am rendering ajax link as follows:
l(t('Click here'), 'mypath', array('attributes' => array('id' => 'my-id', 'class' => array('use-ajax'))));

How to display confirmation dialog before ajax request is called?
I do it as follows in javascript, like I have found on this thread:
  Drupal.behaviors.module = {
attach: function() {

 Drupal.ajax['my-id'].beforeSerialize = function () {

      if(confirm('Are you sure?'))
          return true;
      else
          return false;

  }
 }
}

When I click on link, ajax request is not called but the dialog appears. It is ok. The problem is, that after I click "Cancel" in confirmation dialog, Ajax request is then called after closing the confirmation dialog.
Can anybody help, how to get the confirmation dialog work?

I don't think this is the best way to go about it as you are messing directly with Drupal's Ajax object.

The best way to do this, is to basically write your own click handler and handle the confirmation yourself, then trigger a Drupal AJAX call yourself.

Here is an example:

l(t('Click here'), 'mypath', array('attributes' => array('id' => 'my-id', 'class' => array('toms-ajax'))));

In your js file:

(function($) {

Drupal.behaviors.tomsAjaxLinks = {
  attach: function(context, settings) {
    $('.toms-ajax',context).once('toms-ajax').on('click', this.handleAjax);
  },
  handleAjax: function(e) {
    // Cache the anchor link
    var $element = $(this);

    // We need some unique id, either ID of link or create our own
    var nowStamp = new Date().getTime() + Math.floor(Math.random() * (1000 - 0) + 0);
    var base = $element.attr('id') || 'toms-ajax-'+ nowStamp;

    // Change the event type to load, so we can trigger it ourselves
    var drupal_ajax_settings = {
      url : $element.attr('href'),
      event : 'load',
      progress : {
        type: 'throbber',
        message : '',
      }
    };

    // Create the ajax object
    Drupal.ajax[base] = new Drupal.ajax(base, this, drupal_ajax_settings);

    // Your confirmation code e.g. Jquery UI Dialog or something
    // Open dialog
    if(yes) {
      $element.trigger('load');
    } else {
      // Dont trigger ajax
    }
  }
};

})(jQuery);

Essentially what this does is:

Attaches the handleAjax function to your ".toms-ajax" links once to ensure we do not attach multiple event handlers
On click, the handleAjax function is called
A corresponding Drupal Ajax object is created with it's own unique ID.
It is attached to the link and triggered on the event 'load'. You then
handle the confirmation box.
If the confirmation box confirms the ajaxcall, we simply trigger the 'load' event on the link object and therefore make the Drupal AJAX object do it's thing.


Where to collect business logic for Entity models? Thinking of entities as an MVC 'Model', where would the business logic for an entity sit? I have a custom EntityController, but that isn't attached to an instance and seems to be intended only for serialization logic. I need a Model class that has the same properties as the entity StdClass, but also has functions for operating on the data and presenting it.

I am currently wrapping the entity with a real Model class that is created by its static function Model::createFromEntity($entity)

You can use the Entity API which allows to specify the class in hook_entity_info(). Then entity_load() will use that class (assuming that you're using/extending from EntityAPIController, not the core one) then it will return instances of the defined class and not dumb stdClass objects. Then you can define your own methods there.

See http://www.trellon.com/content/blog/creating-own-entities-entity-api for an example.

This feature will be in Drupal 8 (already is and core is currently being ported to it).


Additional file entity fields in widget_form I've added additional fields to my file entity types and would like to have them in upload widget, just like file description.

How can I add my custom fields element using field_widget_form_alter? (if that's the way to go)

You have to add it to the field type, not entity type.  Extend FileItem and override propertyDefinitions() to add it to the field properties. Like the description you've mentioned was added by FileItem extending EntityReferenceItem:

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['display'] = DataDefinition::create('boolean')
      ->setLabel(t('Display'))
      ->setDescription(t('Flag to control whether this file should be displayed when viewing content'));

    $properties['description'] = DataDefinition::create('string')
      ->setLabel(t('Description'));

    return $properties;
  }


Forms API #states with multiple radios I've got one radios element:

$form['trip_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new trip'),
    'existing' => t('Use an existing trip'),
  )
);

I've got some #states prepared:

$trip_states = array(
  'visible' => array(
    ':input[name="trip_radios"]' => array(
      'value' => 'new'
    )
  )
);

And some other elements that use $trip_states for their #states:

$form['itinerary_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new itinerary'),
    'existing' => t('Use an existing itinerary'),
  ),
  '#states' => $trip_states
);

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => 'Itinerary name',
  '#required' => FALSE,
  '#states' => $trip_states
);

The title form element (and many others) properly listens to the #states condition and works just fine. However, itinerary_radios always shows up no matter what (if anything) is checked on trip_radios. Why does a visible condition on a radios element's #states not listen to another radios value?

In misc/states.js, it looks for the closest form-item, form-submit, or form-wrapper. Here's the line:

$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);

This does not play well with the way radios are themed, and states.js does not find anything to toggle. Wrapping the itinerary_name radios in a container and applying #states to the container item is what I would call the quickest workaround.

$form['itinerary_radios'] = array(
  '#type' => 'container',
  '#attributes' => array(),
  'radios' => array(
    '#type' => 'radios',
    '#options' => array(
      'new' => t('Create a new itinerary'),
      'existing' => t('Use an existing itinerary'),
    ),
  ),
  '#states' => $trip_states
);


Page not found when trying to access my custom module Something is very strange. I have built 8 modules and they all work fine.
When I installed the 9th one, it said "Configuration options have been saved"
but when I access the path, I receive a "Page Not Found".

Tried :
 reinstalling module / clearing cache / recoding the whole module / renaming the module / using other path / rebuild permissions / ... even reinstalled the whole site and reconfigured it all.

All other modules are working but the 9th one fails.

I have seen many posts about this, but none of the options have helped me so far.
Where did I make a mistake? Where can I look in the database to find out more?

hook_menu() had 3 entries: one for entering parameters, one for showing the question selection, and one for showing the answers.

The error was in the second page, which still pointed to an old (disabled) URL.
The very very strange thing is that the module didn't show even the first working path and that there was no error of it.


Unable to generate the derived image Today I uploaded my site to the server, and I get errors like the following:

  Unable to generate the derived image located at public://styles/sponsor_image/public/TerraThermaSponsorLogo.png.

Image styles cannot generate images. I have tried to set permissions on styles/* folders with chmod -R 775 styles/, and even tried chmod -R 777 styles/. The folder's owner is OK. I don't get what can be wrong.

The directory associated with public:// is sites/default/files, and it is OK.

You should also make sure you do have a graphical library (like php-gd) installed on your server: check /admin/config/media/image-toolkit (D7).


When to use taxonomy vs content type? I have a project that allows people to add 'skills' and 'resources' to a system. Initially I was using a taxonomy field for the objects themselves because it seemed to make it easy to look up other 'skills' and 'resources' that had already been added to the system.

However, I am beginning to wonder whether this is the best plan.
The taxonomy system allows for a 'library' of objects to be created which can be shared but this isn't the right way to use taxonomy which should be for 'meta-information'.

I could have a preexisting taxonomy structure of 'stuff' like ebay's categorie and allow people to add their own stuff to this library. People would add 'skills' and 'resources' as their own content types with additional fields- title, body, image, and then tag them within this taxnonomy structure. However, I was attracted to the idea of keeping it really simple; e.g. a drill is only a drill not a bosch, 12v battery powered handheld drill with hammer setting and masonry bit :)

If I wanted to have a 'drill' categories with a pool of 'drills' with more specific drill information what would be the best way to do that?

Sorry there are a few questions here, but I'm hoping to put together question an exciting distribution from this project, so any thoughts will help and hopefully go to something worthwhile.

Content type defines kind of information, different content types means different structure and different nature of content. Taxonomy is for categorisation. They can be interchangeable to some extent, but it's really up to how you want your data defined.

If all nodes we are talking about perform the same function in the system and are supposed to have the same fields, keep them categorised by taxonomy. If their function should be different, make content types - it does not mean you need to give up taxonomy then (but you may if it's no longer needed).


Conditional 404 response based on inclusion of /node/# in URL I've been requested by a client to completely block the URLs that contain a /node/## after the hostname to prevent these locations from being indexed by search engines.  My issue is that I've already defined a Page Not Found node that gets shown with error 404s.

I've already implemented a modification in the robots.txt file to include

Disallow: /node/
Disallow: /?q=node/

to prevent the web-crawler bots.  However, the URLs are still directly accessible.  So in this case, the client wants two different 404 actions:

www.clientname.com/testttt -> Drupal renders 404 page
www.clientname.com/node/897 -> blocked completely without returning Drupal's 404 page.

Does any module allow for this kind of functionality?

What about using hook_init in a custom module?

function hook_init() {
    // check arg(2) is empty as otherwise will block node edit and delete pages
    if(substr($_SERVER['REQUEST_URI'], 0, 5) == '/node' && arg(2)=='') {
        die(); // to stop completely
        //return drupal_not_found(); // to return 404 page
        //return drupal_access_denied()(); // to return 403 page
    }
}

Saying that it would be quicker to block these pages in .htaccess...


In-place editor buttons in footer missing I installed the Panels in-place editor which, in principle, should allow me to edit page layouts on the front-end.

But the two big buttons "Customize this Page” and “Change Layout” which should show up at the bottom of the page in the footer, are simply missing; I have a blank footer bar. I have already set the default renderer to IPE as well as given appropriate permissions. Any ideas on how to fix this - get the IPE buttons?? There are no missing dependencies AFAIK, but the evidence suggests I am probably wrong..

Did you enable Node template in page manager? -> /admin/structure/pages
That should make the toolbar appear.


Content type access permission by user role I have created 4 different content types and all except only one content type are visible to every user.  Here, I am not using any type of access module like content access, field permission or organic groups even I have also uninstalled my custom module but still could not able to find out the root cause .

In the attached screen shot
1) The above section is permission on a node created in that content type as per user roles.
2) The below section is what, which is visible to user other than site admin.

I have also gave "View published content", "View own published content" and "View content revision" permissions (and cleared the cache) but it still not fixed.

Appreciate any guess or suggestion !!

Yes, I have got the issue.  This was a silly mistake, the nodes in that content types were not published.

I just published them and they are now visible to allowed roles.

Thanks


How to show a form in Dialog Modal jquery? Regards,

I need to display a form within a modal dialog when clicking on a link. In which the user can put data and save the data.

I thought about making a template in which I have my form, but not as display them using the method. Dialog () to show me the Modal.

Does anyone know how I can display the dialog template with the method? or does anyone have any other ideas of how to do that?

Thanks.

There's 2 good options I know of currently: iframe (in colorbox for example) and CTools. Which option to use depends of the circumstances. I guess this information I found in the CTools modal.html file brings out the main difference:

  CTools provides a simple modal that can be used as a popup to place forms. It differs from the normal modal frameworks in that it does not do its work via an iframe. This is both an advantage and a disadvantage. The iframe simply renders normal pages in a sub-browser and they can do their thing. That makes it much easier to put arbitrary pages and forms in a modal. However, the iframe is not very good at actually communicating changes to the main page, so you cannot open the modal, have it do some work, and then modify the page.

I have no personal experienced with CTools on this subject so I can't add anything else to that, but I've implemented the iframe method in a couple of projects. In the most recent one I used the Colorbox plugin to show a few forms created with the Webform module in a popup.
I'll add some example code here in case there's some interest.

Link to the form:

'.t('Send message').'

Javascript code to open the linked address in a popup:

if ($('a.colorbox_form').length > 0) {
  var link = $("a.colorbox_form").attr('href');
  link = link.concat('?colorbox=true');
  // colorbox=true is attached for later use (read below).
  $("a.colorbox_form").attr('href', link);
  $("a.colorbox_form").colorbox({iframe:true, width:500, height:450});
}

In the theme template file:

function mytheme_preprocess_page(&$variables) {
  // Different template and additional stylsheet for colorbox content.
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    $variables['theme_hook_suggestions'] = array('page__iframe'); // page--iframe.tpl.php
    drupal_add_css(path_to_theme() .'/iframe.css');
    $variables['styles'] = drupal_get_css();
  }
}

I attached 'colorbox=true' to the links using javascript so that users with javascript turned off would see the form with the normal template. The iframe template only has messages, title and content printed.

This already works, but I ran into a issue with Webforms: 'colorbox=true' wasn't preserved when the form got submitted. My attempt to fix it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    // The id-s of the forms that are possibly shown within a popup.
    $form_ids = array('webform_client_form_2', 'webform_client_form_4');
    if (in_array($form_id, $form_ids)) {
      $form['#submit'][] = 'mymodule_webform_submit';
    }
  }
}

function mymodule_webform_submit(&$form, &$form_state) {
  //drupal_set_message('
'.var_export($form_state['redirect'], TRUE).'
');
  if (!isset($form_state['redirect'])) {
    $form_state['redirect'] = array($_GET['q'], array('query' => array('colorbox' => 'true')));
  }
  else {
    $form_state['redirect'][1]['query'] = array('colorbox' => 'true');
  }
}


Node is flagged, node author comes back to the site, how to show how many new flags since last visit? I created a "new activity feed" view page in which a user can see how many new comments have been posted to his own nodes since his last visit

Eg : since you last last visit :
- 21 new comments have been published on your node #title, in a total of 65 comments
- 3 new comments have been published on your node #title2, in a total of 8 comments

The nodes can also be flagged by other users.

Using flag module and views, it is possible to get the total amount of flags a node has received at any time.

I would like to be able to show the node author, how many "new" flags each of his nodes has received since his last visit.

Any help is welcome

To answer your posted question (title), you'll need to extend functionality.

By default, the core comment module & flag module have no default mechanism to store comment/flag view history. You would need to do something like:

Build something like the Drupal core history module that tracks a user's comment/flag views
Build a simple aggregate comment/flag query based on a user's last login/access time
...or maybe find a module that offers this functionality (not sure it exists and module recommendations are off topic here)


Fatal error: Call to undefined function field_create_instance() I'm helping to convert a Drupal 7 module across to Drupal 8 and getting an error on the install.

  Fatal error: Call to undefined function field_create_instance()

I've seen in the Drupal 7 database that a table is created for field_first_name as field_data_field_first_name. Does this still happen in Drupal 8?

I resolved the fact that field_info_field() and field_info_instance() are now deprecated in Drupal 8 and have updated accordingly with \Drupal::entityManager()->getFieldMap() and FieldConfig::loadByName() respectively, but I can't find anything to suggest what to use instead of field_create_instance(); can someone suggest how I get around this?

My code is this.

/**
 * Implements hook_install().
 *
 * Adds custom fields used by module.
 */
function indicia_api_install() {
  $fields = array(
    'field_indicia_user_id' => (object) array(
      'type' => 'number_integer',
      'title' => 'User ID for this key on the warehouse',
      'name' => 'field_indicia_user_id',
    ),
  );

  foreach ($fields as $fielddef) {
    if (!\Drupal::entityManager()->getFieldMap($fielddef->name)) {
      \Drupal::logger('ima', 'Adding field: ' . $fielddef->name);
      $field = array(
        'field_name' => $fielddef->name,
        'type' => $fielddef->type,
      );
      if (isset($fielddef->required)) {
        $field['settings'] = array('required' => TRUE);
      }
      field_create_field($field);
    }
    else {
      \Drupal::logger('ima', 'Field already exists: ' . $fielddef->name);
    }
    if (!FieldConfig::loadByName('user', $fielddef->name, 'user')) {
      \Drupal::logger('ima', 'Adding instance: ' . $fielddef->name);
      $instance = array(
        'field_name' => $fielddef->name,
        'entity_type' => 'user',
        'label' => $fielddef->title,
        'bundle' => 'user',
        'required' => isset($fielddef->required) && $fielddef->required,
      );
      field_create_instance($instance);
    }
    else {
      \Drupal::logger('ima', 'Instance already exists: ' . $fielddef->name);
    }
  }
}

Just to update this question, if anyone else comes across this - I worked out the solution in the end. Rather than implementing the hook_install() function I added the field information to the config/install/ folder which adds the necessary user fields instead.


Split Webform Items into two rows i'm working on a problem for a while and still found no answer.
I'm using the Webform Plugin to show a contact form on my site.

The current structure is:

<form>

...

...

...

...

</form>

Is it possible, maybe with a hook because i want to apply it to a special form, to get this HTML structure:

<form>

...

...

...

...

</form>

I want to split the form items into two rows.

Thanks for hints and tips!

Last version of webforms lets you do this outofdabox (put fields in a fieldset though)

You can also achive this using a hook_form_alter implementation (Have not tested this but i think that should work) and using the FAPI #type container element, for example:

$form['left'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array(
      'left',
      drupal_html_class($class_left),
    ),
    'id' => array('lefttoleft'),
  ),
);

Create as many container as you want and then move all fields FAPI element inside the container


Add on domain does not have access to "../privatefiles" at public_html level I have a Drupal site that accepts private file uploads from some authenticated users.

The directory where those files are stored is privatefiles and it is located above the www directory, at the same level than the public_html directory. In the file system, the private file system path is defined as "../privatefiles"

That seems to work well.

I But I am transferring the site to another hosting company and putting it there as an add on domain to an existing one. The uploaded private files are no longer visible.

To make the add on site, I had to create another directory. The new directory is example1.com/example2.com If I move the private file directory one level down (i.e. under the public_html directory, then the private files become visible again.)

The only problem is that those files are now accessible from the web.

Does anyone know why this is so? How can I keep the private files at the same level? Should the "../privatefiles" be written differently? Or is this issue a limitation imposed by the new hosting company?

Any pointer for this would be greatly appreciated. :)

OK, I figured out what was going on and how to fix it.

The problem was indeed with the "../privatefiles" declaration for the private files directory. Just like for the old DOS files, the "../" means "one level up" and that is okay when the core file are in the www directory.

But when they are below or way below, the "../privatefiles" has to be replaced with the full path: "/home/whatever/privatefiles"

Now it works well.


How to hide the label of a entity referenced image field I am using drupal core 8.4.2 and lightning 8.x-2.23. I have a entity referenced image field that I am printing out like this {{ content.field_main_image_2.0 }}. I think there was a change starting in drupal 8.4 that now the image label is displayed above the image even if you set it to hidden in the media image bundle. Looking at the source for theme template suggestions it says this.

name fish

I want to remove the label "name fish" from appearing above the photo.
My entity referenced field name is: field_main_image_2
My content type is called: person
How should I rename the template named field.html.twig? I tried renaming it to
field--field_main_image_2.html.twig and field--field-main-image-2.html.twig, but this didn't work. It says to use this method field--field-foo.html.twig. For now I placed the file field.html.twig in my template folder and it is being used but I dont see where I can remove the label. The template says Available variables: label_hidden: Whether to show the field label or not.

Starting in Lightning 2.2.4, you can manage the label in the Media Entity's Manage Display tab.

See this issue for more information: https://www.drupal.org/node/2922289

  Include patch to omit media name

  Until this is fixed in core, it would be good to have the patch from [#2912298: Make media name available on manage display] included so that media name can be removed from display. This is especially crucial for lightning upgrades with existing media embeds.


How to Restrict views Date popup to only year/month I want to have views exposed filter on node created field with popup.
I've installed date_popup, the popup appears but I'm looking for a way to restrict it to only year and month.

I tried the following solutions but no success.

function HOOK_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if( $form['#id'] == 'views-exposed-form-news-page-1') {
    $form['created']['#date_format'] = 'm-Y';
    $form['created']['#date_date_format'] = 'm-Y';
    $form['created']['value']['#date_format'] = 'm-Y';
    $form['created']['value']['#date_date_format'] = 'm-Y';
    $form['date_needed'] = [
      '#type' => 'date',
      '#title' => 'test',
      '#date_date_format' => 'm/Y',
      '#date_format' => 'm/Y',
    ];
  }
  return $form;
}

You'll need a external library to do that. Something like jQuery UI Month Picker Plugin and you'll probably will need to use a textfield rather than date.

OR

Use the Month Year module

  This module provides a month year field type.


Which hooks can I use in profile development? Which hooks are available in profile distribution development? Which other hooks can I use except hook_install_tasks()?

I can't find a documented list anywhere, but a quick look at the code suggests these are the available hooks:

hook_install_tasks()
hook_install_tasks_alter()
hook_install()
hook_form_alter()
hook_form_FORM_ID_alter()


Clean URL not working I have downloaded Drupal 8.x-dev at https://drupal.org/node/572834 to test on my local PC (Xubuntu 14.04 Beta 1).

I have successfully installed but when I try to access Admin menu is giving me "Not Found" pages, though on a simplytest.me sandbox it working ok.

What am I doing wrong?

SOLUTION:

Thanks to @tenken for giving me a hint this was related to "clean urls" issue.

I got this working with the following steps:

Run sudo a2enmod rewrite # Enabling "rewrite" module
In /etc/apache2/apache2.conf and look at the block <Directory /var/www/> changed from AllowOverride None to AllowOverride All
Run sudo service apache2 restart

This reference was helpful https://drupal.org/getting-started/clean-urls


Body Class, Drupal 7, change language name programmatically I am trying to add a the language being displayed in the html body class. Drupal 7 for example, when i open firebug  it displays the body class  with these values

body class=html not-front logged-in no-sidebars page-node page-node- page-node-187 node-type-page toolbar toolbar-drawer i18n-el show-grid no-rgba

Is it possibe to add the language as lang-el instead of il8n-el?
Which file is it responsible for outputting these values?

sites/all/modules/i18n/i18n.module

Line:267:  $variables['classes_array'][] = 'i18n-' . $language->language;

You can create your own small module mysmallmodule.module and put this in it:

/**
 * Implements hook_preprocess_html().
 */
function mysmallmodule_preprocess_html(&$variables) {
  global $language;
  $variables['classes_array'][] = 'lang-' . $language->language;
}

Which wont get rid of the i18n class but will just add your own version :)

EDIT: Step by step to create a small custom module.

Create a new folder in the sites/all/modules folder called custom, in here you can keep any custom modules you may need.
Create another folder in the custom folder and call it something suitable like customclasses.
In the customclasses folder create two files, customclasses.module and customclasses.info.
In the customclasses.module file paste the code above but call it "function customclasses_preprocess_html" instead of "mysmallmodule".
In the customclasses.info file paste

name = Custom Classes

package = Custom Stuff

description = Custom class to get "lang-" in the body class.

core = 7.x
Finally, go to the modules page and enable your first custom module.


Adding a class to a  in .theme file Using Drupal 8 and Bootstrap sub-theme.

I see that classes are being added to my divs in the page template file using the following:

<section{{ content_attributes.addClass(content_classes) }}>

That's great. But what if I wanted to add additional classes to these div tags. How would I do that...in my .theme file somehow?

OPTION 1

In your template file, you could find the set content_classes and add another class name to the list.

{%
  set content_classes = [
    'class-name',
    'class-name-other',
  ]
%}
<section{{ content_attributes.addClass(content_classes) }}>

OPTION 2

In your .theme file

function themename_preprocess_html(&$variables) {
  $variables['content_attributes']['class'][] = 'class-name-other';
}

Note: This preprocess is for the html.html.twig file, you need to use the correct preprocess depending on your template file name.

If it's the node.html.twig then use function themename_preprocess_node(&$variables)

If it's the page.html.twig then use function themename_preprocess_page(&$variables)


Services can not create an user with role I follow this answer How to create user with role(s) through REST service?

{"name":"user343","pass":"kes35@r4","mail":"user343@sample.com","status":"1", "roles":["4"]}

But When I check the created user, It role still is '2' (authenticated user)

Just install Auto Assign Role Module.

Then use this following json code:

{"name":"user3431","pass":"kes35@r4","mail":"user343@sample.com","status":"1", "user_roles":{"6"}}


Rules with condition on taxonomy Im doing a simple Rules that when a content is created of type X, and has taxonomy term of T1, simple action to display a message in the page.

Events: After saving new content (rules_entity_insert:node)
Conditions:

Node is of type
How to configure this item to select taxonomy term???

Action: Show a message on the site

add one condition that checks if the node has field_term_ref (term reference) equal to what term name you wish for it.

Choose the action "Set a data value".
Choose the taxonomy term reference field to set.
"Switch to the direct input mode" button to reveal the terms available in your taxonomy field.


How can I add an unescaped script tag and contents to a page? I would like to add to my pages the structured data in JSON-LD (https://developers.google.com/search/docs/guides/intro-structured-data)

Basically, what I need to do is to add somewhere in the HTML for, let's say a basic page, a snippet like the following:

<script type="application/ld+json">
{  "@context":"http://schema.org",
   "@type":"WebSite",
   "name":"Site name",
   "alternateName":"Site alternatime name",
   "description":"Site description",
   "keywords":"list of keyword",
   "inLanguage":"en",
   "url":"http://www.example.eu/en",
   "potentialAction":{
   "@type":"SearchAction",
   "target":"http://www.example.com/en/find/{search_term_string}",
   "query-input":"required name=search_term_string"
   }
}
</script>

I've tried to use the full HTML input but the snippet gets (kind of) escaped with the CDATA and google cannot parse it.

So, how can I provide that snippet without any escaping?

Here's a simple way to do this with no additional modules required. For the sake of this example, I'm going to add this field to the Basic page content type that comes with the Standard installation profile.

First, let's create a new Text format. Go to admin/config/content/formats and click Add text format. I name the Text format JSON-LD and make it only available for Administrators. Be sure to leave all options blank and set Text editor to None, like so:

Then, let's add a new field to the Basic page content type. Go to admin/structure/types/manage/page/fields/add-field and select Text (formatted, long). I name the field JSON-LD with an automatic machine name of field_json_ld.

Then let's make sure we hide the field's label. Go to admin/structure/types/manage/page/display and make sure to set the Label to our new JSON-LD field to - Hidden -, like so:

Now it's time to add the script to a new page. Go to node/add/page and fill in the Title and Body as you like. Here's the important bit: for the JSON-LD textarea, be sure to set the Text format to JSON-LD, like so:

Now click Save and publish. Your node will look like this:

Nothing special, right? Now let's take a look at our source code:

Bingo!


How to get Final SQL query when using Views? How do I get complete SQL query from Views, the one I could run in mysql directly.For example biggest stumbling block is fields part. Like below

SELECT users_node.uid AS users_node_uid, node.created AS node_created, node.nid AS nid, users_node.mail AS users_node_mail, 'user' AS field_data_field_first_name_user_entity_type, 'user' AS field_data_field_last_name_user_entity_type, 'node' AS field_data_field_purchase_date_node_entity_type, 'node' AS field_data_field_serial_number_node_entity_type
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid
WHERE (( (node.status = '1') AND (node.type IN  ('product_registration')) ))
ORDER BY node_created DESC
LIMIT 50 OFFSET 0

this lines are problematic
field_data_field_first_name_user_entity_type,
field_data_field_last_name_user_entity_type
etc

They are not real fields in DB, they somehow get rewritten somewhere, but I can't find where and how. How to get the FINAL query to DB in drupal when using views?

p.s.
in image, you can see what I get for those fields in phpmyadmin if I run query. Not really useful.

Try the Views Show Query  module

This module shows real SQL query in Views UI during live preview.
'Real query' means it is rewritten by query_alter hooks. For instance, node access checks are added, so this requires selecting the user on behalf of which the query is supposed to be executed. So the module adds 'User ID to show final query' field in views preview form. You must enter numeric user ID in this field to view the real SQL query.
This module makes it possible to show SQL query not only during live preview, but when the view is executed normally. You can add footer to the view with the following PHP code:

<?php
$rows = array();
$view->exposed_input['views_show_query_uid'] = 1;
views_show_query_views_preview_info_alter($rows, $view);
drupal_set_message($rows['query'][0]);
?>


Dynamic Field Adition / Subtraction using FAPI Goal Provide a user with a drop down menu defaulted to a value of none. Other options are the number 1 through 27. Based on the value select have drupal FAPI generate a fieldset that has anywhere from 1 to 27 required text fields. And should they then change their mind it would re-render accordingly.

What I have
So far I am able to get the FAPI to hide the field on initial form render however I can't seem to figure out how I'd take the selected array value and use that to generate out a new field set dynamically.

function single_add_ucm_form($form, &$form_state) {
$form['number_subscribers'] = array(
'#type' => 'select',
'#title' => t('How many subscribers are in the CUCM cluster?'),
'#required' => TRUE,
'#default_value' =>  0,
'#ajax' => array(
  'callback' => 'ajax_select_callback',
  'wrapper' => 'replace_subscribers_div',
  'effect' => 'slide',
 ),
'#options' => array(
  0 => t('none'),
  1 => t('1'),
  2 => t('2'),
  3 => t('3'),
  4 => t('4'),
  5 => t('5'),
  6 => t('6'),
  7 => t('7'),
  8 => t('8'),
  9 => t('9'),
  10 => t('10'),
  11 => t('11'),
  12 => t('12'),
  13 => t('13'),
  14 => t('14'),
  15 => t('15'),
  16 => t('16'),
  17 => t('17'),
  18 => t('18'),
  19 => t('19'),
  20 => t('20'),
  21 => t('21'),
  22 => t('22'),
  23 => t('23'),
  24 => t('24'),
  25 => t('25'),
  27 => t('26'),
  27 => t('27'),
),
);
$form ['subscribers_wrapper_container'] = array(
'#type' => 'container',
'#prefix' => '
',
'#suffix' => '
',
);

if (isset($form_state['values']['number_subscribers'])) {
$form_state >= 1;
$form['subscribers_wrapper_container']['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}
}

function ajax_select_callback($form, $form_state) {
return $form['subscribers_wrapper_container'];
  }

if (!isset($form_state['values']['number_subscribers'])) {
   $form_state['values']['number_subscribers'] = 0;
}

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}

You should add '#tree' => TRUE on your form, it will be easier to extract the form values afterwards


After installing any module I get "The website encountered an unexpected error. Please try again later." I'm a Drupal beginner and after setting up my site and installing some modules I now have this annoying bug.

After installing any module, doesn't matter what one, I get this white page:
http://imgur.com/a/z5MFp

Even though it says it has encountered an error, the module actually just gets enabled without any other error logs.

http://imgur.com/a/U6ymD

(In the screenshot I tested it by enabling ban and telephone module, each time after  enabling it in the module list I got an error page. But the modules actually work and there aren't any errors to be found on the logging page.

It's quite annoying to get a white error page instead of the blue loading bar.

Anyone have an idea what the issue here is?

Enable error reporting in Drupal. This way, Drupal can print the errors and stack traces on the page when the errors occur. Also, consider enabling the module using Drush particularly with --verbose and --debug options. This prints logging info while enabling the module.

The source of this could be anything. It could be a bad module install script, bad configuration, bad module hook code, or a malformed template (for that page). I usually get these pages when code tries to access non-existent properties or indexes or have modules that don't play nice with each other. This usually look harmless. But if the error cuts into execution and there was data that was still to be saved, it might result in a bad system.


Notices and Warnings Drupal Commons 7.x 3.9 Undefined index, invalid argument, illegal string offset I get these 7 messages every time a user goes to an event listing.
Happens in this order.  I'd like to troubleshoot and eliminate.

Notice: Undefined index: title in commons_origins_preprocess_form_content()  of profiles/commons/themes/commons/commons_origins/template.php).
Notice: Undefined index: #items in commons_events_entity_view_alter() of ….profiles/commons/modules/commons/commons_events/commons_events.module).
Warning: Invalid argument supplied for foreach() in element_children() of /includes/common.inc
Warning: Illegal string offset '#children' in drupal_render() (line 5890 ) of …includes/common.inc
Warning: Illegal string offset '#children' in drupal_render() (line 5900 ) of …includes/common.inc
Warning: Illegal string offset '#children' in drupal_render() (line 5983 ) of …includes/common.inc
Warning: Illegal string offset '#printed' in drupal_render() of /includes/common.inc).

title is not defined. #items is not defined. foreach is not getting a value to work with. #children doesn't exist to render.#printed doesn't exist to render.
go into the function where title is supposed to be defined and check that there is a value. Do the same for the rest. Check what further up the chain in your code is calling these values. Try doing a backtrace.


FormStateInterface::setValidationHandlers not working properly? I'm using Drupal 8. Within \Drupal\Core\Form\Form\FormBuilder::buildForm, if $cache_check == TRUE, i.e. - the form has a form_id and a build_form_id, then the $form_state object which results from the call made to retrieveForm() in \Drupal\Core\Form\FormBuilder::buildForm() is overwritten by the form_state that is cloned prior to the retrieval.

This would seem to effectively nullify any modification done to the $form_state object within the buildForm() method of a Form class implementing FormInterface. Is this correct?

For example, MyForm class extends FormBase -- which implements FormInterface. If I make a call to $form_state->setValidateHandlers() within the buildForm method in MyForm, the extra validate handler methods set in that call will never be invoked, as the $form_state object will be overwritten after being rebuilt within MyForm::buildForm().

Is this the expected behavior? i.e. - Is it not expected to be able to alter the $form_state within buildForm() in this way?

If that is the case, then is simply using the more "Drupal 7-ish" syntax of $form['#validate'] = ['::method1', '::method2'] the accepted/best-practice way to accomplish multiple validate handlers?

This will work, because the $form array does not get overwritten after the MyForm::buildForm() method is invoked. However, if this is the accepted/best-practice way to achieve multiple validate handlers, how would one set a validate handler that exists outside of the current form class (in this example's case, MyForm)?

You should add the below method in drupal 8. I hope it should work.
// buildForm

public function buildForm(array $form, FormStateInterface $form_state) {

    $form['company_name'] = array(
        '#type' => 'textfield',
        '#title' => $this->t('Company Name'),
        '#required' => 'TRUE',
        '#placeholder' => $this->t('Your company name'),
    );
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#validate' => array('::validateForm', '::method1', '::method2'),
    );

    return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {
   // do your code stuff..
}

public function method1(array &$form, FormStateInterface $form_state) {
  // do your code stuff..
}

public function method2(array &$form, FormStateInterface $form_state) {
  // do your code stuff..
}


Migration: Combine Profile2 and file migration I need to migrate profiles from an external database (not drupal) to Drupal 7. The target system uses Profile2 profiles. I already wrote the migration of all the "primitive" fields with the help of this cookbook, but I'm stuck with the profile images. They are only accessible via url (blah.org/blah/[user_id].jpg, so the migration needs to download them, and store them into a Profile2 profile field with type image. I know there is MigrateDestinationFile, but I dont see how to make the file<->image<->Profile2_field connection.

Has anyone done that before?

This is not a complete working example but is still more an answer than a comment.

I'm assuming you're familiar with migration code in general.

I also assume you are using Migrate extras, which provides profile 2 support and has an example of a profile2 migration.

Because files are a separate entity from profiles you have to first have a file migration, which migrates the files into Drupal.
In that linked example the first part of code is the file import and the second part is the node import that then uses those files in a file field.
In your case the second part will be very similar but will be in your profile2 migration.

I haven't actually done an import that pulls in images from the web like this so this is an assumption.
I would say set your source directory for your file import to the directory that you intend to download the remote files into.
You can specify your directory like this and make it anywhere on your server: 'source_dir' => '/var/www/my-downloaded-files',

Then after that you import your profile2 profiles.

Unfortunately I have only done file migrations from Drupal to Drupal so I'm not sure off the top of my head what you specify for the source field when you add your field mapping (I will have a look into it when I get some free time but I'm not sure when that will be).

As far as the actual pulling in of the files goes a possible, relatively straight forward way to get your files from the external source might be to implement one of the migration methods like prepareRow() (see Commonly implemented Migration methods) and have it download the file (you could use drupal_http_request() or cURL or similar) for use in your file migration.

Be sure to handle the case of rollbacks and either remove the local files or before downloading, check if you already have the file then only download if you don't.


Why does field_get_items() sometimes return "blank" field_get_items('node', $my_node_object, 'field_[fieldname]') is returning the string 'blank'. Not an array, not NULL, but a string reading 'blank'. It's causing errors in media_wysiwyg module. What causes this? How can I fix it?

Reading the function's source code it seems that the only way to return 'blank' is when the field's value for the selected langcode is actually 'blank':

https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7

I suggest you to use XDdebug to check the node_object value just before this function is called. You can also use a dirty-and-quick trick: edit the code function and add a dpm (but remember to revert it!). But with XDebug you really can see where that 'blank' value comes from.


What is an alternative and easy way to test if Webform is in fact sending mail? I'm not sure if its the webform module or my server, but a few days ago i was receiving webform submissions via email, but today its not working when I did a test on the same webform. Is there a easy way to test if its webform that's the issue or my server?

Try one of the Mail Logger or Maillog modules. That will enable you to see whether there is an email actually being created. I personally used to use the second, with D6 though.


Can't load library path files I have added a library to the libraries folder. I have the Libraries API module installed and I wrote this code:

function my_module_libraries_info() {
  $libraries['google-api-php-client'] = array(
    'name' => 'Google Api PHP Client',
    'path' => 'src/Google',
    'vendor_url' => 'https://github.com/google/google-api-php-client',
    'download_url'=> 'https://github.com/google/google-api-php-client',
    'files' => array(
      'php' => array(
        'Client.php',
        'Service.php',
      ),
    ),
  );
  return $libraries;
}

and the code to call it

$library =libraries_load('google-api-php-client');
dpm($library);

This dpm did give me a library array, so it looked like it was ok. But then I tried

$client = new Google_Client();

and I got an error:

PHP Fatal error:  require(): Failed opening required 'http://[site-name-here]/sites/all/libraries/google-api-php-client/src/Google/Client.php'

When I tried this

 global $base_root;
  require $base_root . '/'. libraries_get_path('google-api-php-client') . '/src/Google/Client.php';

I got the same error message. I checked and saw tat the files were still there. What is going wrong?

Clearing the cache might help. I had tried to use libraries_flush_caches but that didn't seem to work. General CC did though - that will ensure libraries_load detects and loads the files you put in your files array.

Also, for this library (at least composer version "google/apiclient": "1.0.*@beta") , you want to put 'autoload.php' in your files array - it'll do what it sounds like, auto-load all the classes you want to use instead of you manually having to do it.


need to have image dragging option to position images in Gallery I have created a image content type and upload few images. And then I created another content type for Gallery and using node reference field, I added several images under a  gallery. I followed the tutorial in youtube https://www.youtube.com/watch?v=MUSpTSTVL0Q

Now I wish I could have dragable like feature, so that I can adjust the serial order of each image in a gallery. Image in 1st order should be cover of the gallery. Please suggest.

This is solved by module called "Draggable Views"


Display database query results in custom module I have a custom block and I'm able to update its content using #pre_render if I'm using basic text.

However I'm unable to print database query results using the same way. Below is my code.

function _maintenance_prerender(array $build) {
$build['content']['#markup'] = myDatabaseQuery();
return $build;
}

function myDatabaseQuery() {
  $query = \Drupal::database()->select('menu_link_content_data', 'm');
  $query->condition('m.title', 'Visit');
  $results = $query->execute();
}

Is there a special way to print database query results on a custom block?

To be able to exploit your result, you should fetch your result with one of the function of the Statement class.

If you use the function fetchAll() for example, you will have an array of objects with all your result.

$results = $query->execute()->fetchAll();

You can do a function to create your markup with that array.

You can also not use a function from Statement and do a foreach directly on the result generate by the execute() function to create your markup

$results = $query->execute();

foreach($results as $res) {
    $markup .= "
$res->field_1	$res->field_2
";
}

If you want see how is design your array, you can install the module kint (from the devel module) and display your result with

ksm($results);

Additionnally, to work, your query should have the list of fields it should select.

$query->fields('m', ['field_1', 'field_2']);


How can I get Elysia Cron to run every 15 minutes? I'm running drupal 7 on a shared host with cpanel and apache. I don't want to use regular cron because i want to run some tasks more regularly than others such as the search index. So i added Elysia Cron module. It doesn't run at the regular intervals I intend though. I'm hoping you all can give me some guidance.  Here's how I set it up:

I added a cron job in my cpanel like so:

http://mysite/sites/all/modules/elysia_cron/cron.php?cron_key=key and set the frequency to *****.

Then in Drupal I went to admin > configure > elysia cron and did the following:

Set search to run every 15 minutes and everything else either every hour or every day.

I also set the installation settings so that 'never/use external crontab' is selected for 'run cron on visitor's requests, every'.

But when I save these settings...cron doesn't run every 15 minutes for the search index as planned.

Any idea what else I might need to change?

Given the explanation in your question about how you've set things up, at least one reason your external cron does not ping Elysia Cron is that you've got the key wrong, or that the key is missing.

You need to up look the right key. Navigate to Elysia  » Settings  » Installation Settings  » Cron key and copy the key has you find there so that your Cpanel setup to looks like this:

http://example.com/sites/all/modules/elysia_cron/cron.php?cron_key=ZvMtg5HAaRzjz5NtkwoDs0F3jOWrbpIX5JVi3ACJl7Q

Note: Use the actual key you find on your site - not the dummy key I use as an example.


How to stop Drupal for setting node changed date on creation? This is my second question about my issues with creating custom migration script.

I am creating only new nodes and don't care about updates.

Code:

        $node = new stdClass();
        $node->type = 'migrate';
        $node->title = $content['title'];
        $node->language = LANGUAGE_NONE;

        $node->created = (int) date('U',strtotime($content['created']));

        $modified = $content['modified'];
        if (! empty($modified) && $modified != '0000-00-00 00:00:00') {
            $modified = (int) date('U',strtotime($modified));
        } else {
            $modified = 0;
        }
        $node->changed = $modified;

        node_object_prepare($node);

        #some lines later
        node_save($node);

E.g my $modified is set to 0 and after save I see updated column of this node row in admin content list with current datetime value.

You should be able to preserve the original changed time by first setting a custom property on the node object, say $node->modified, in your migration script prior to calling node_save(), and then implementing the node_presave hook:

/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {
  $node->changed = $node->modified;
}

This will work since node_save() sets $node->changed prior to calling all modules which implement hook_node_presave().


Display comments from other nodes with a reference Here's a doozy.

I have a certain content type where nodes of this ct serve as a sort of portal for other nodes. The other nodes (which are all different content types themselves) have entity reference fields, linked too this portal-node.

I need a view that displays the latest -comments- of the nodes linked too the portal node which the user is currently viewing.

Well, I couldn't get this to work with views, so I wrote a custom module with an sql query. Not very clean, but it does the trick.


How to exclude multiple nodes based on their ID in taxonomy term view? In taxonomy term view I want to exclude multiple nodes based on their id.

I tried to add a new CONTEXTUAL FILTER so I can handle multiple values in my Content: ID but the problem here is that it overwrites the url taxonomy/term/%/edit.

Also I have tried to add Content: ID filter in my FILTER CRITERIA but I cannot add multple values in "Not equal" field.

How can I solve that?

Add more than one ID Filter

You can simply solve it by adding as many Content: ID Filters as you need, each excluding only one node. As you already know set the Operator to Is not equal to and enter one value, then add another Content: ID Filter and so on for all the nodes you need to exlude.

Use Regular expression

Or you can use the Operator Regular expression in a single Content: ID Filter. This way you can use a regex pattern that matches all the ID numbers you want to exclude.

For example the expression (2[45]) matches two numbers, 24 and 25, so those two nodes would be filtered and shown in results.

In your case you need to exclude some numbers, so you would have to have a regex that excludes. That is a bit out of scope for this question so I won't go into it. There are online regex generators you can use to help you construct the expression, but I expect it would take some time, regex is notorious for being complex and mind-boggling.

For whole range of numbers take a look at this tool: Regex Numeric Range Generator. Don't forget you need to modify the expression to exclude the list!


How to add a menu link to a menu programmatically? I want to add a menu link to a menu programmatically. Here is my code

MenuLinkContent::create([
      'title' => 'Example link',
      'link' => ['uri' => 'internal:/node'],
      'menu_name' => 'main',
    ])->save();

But it gives me the following error

PHP Fatal error:  Call to a member function get() on a non-object in /var/www/drupal8/core/modules/menu_link_content/src/Plugin/Menu/MenuLinkContent.php on line 105

Is there any way to add menu links to a menu programmatically?

I was using the wrong namespace.
Use the following namespace

use Drupal\menu_link_content\Entity\MenuLinkContent;

and then the following code will work.

MenuLinkContent::create([
      'title' => 'Example link',
      'link' => ['uri' => 'internal:/node'],
      'menu_name' => 'main',
    ])->save();


Can't create foreign key using SCHEMA API I am trying to create 2 tables, linked together, using this code:

$schema['parent'] = array(
    "fields" => array(
        "id" => array(
            'description' => 'The primary identifier',
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE,
        ),
        'data' => array(
            'description' => 'The stored data.',
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
            'default' => '',
        ),
    ),
    'primary key' => array('id'),
);

$schema['child'] = array(
    // {{{fields

    "fields" => array(
        "id" => array(
            'description' => 'The primary identifier',
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE,
        ),
        "parent_id" => array(
            'type' => 'int',
            'unsigned' => TRUE,
        ),
        'data' => array(
            'description' => 'The stored data.',
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
            'default' => '',
        ),
    ),
    // }}}
    'indexes' => array(
        "parent_id" => array("parent_id"),
    ),
    'foreign keys' => array(
        'parent_id' => array(
            'table' => 'parent',
            'columns' => array('id' => 'parent_id'),
        ),
    ),
    'primary key' => array('id'),
);

foreach ($schema as $key => $value) {
    print $key . "\n";
    db_create_table($key, $value);
}

The tables are created, but the foreign keys are not. Using MySQL/InnoDB. How to fix it?

Also how to set ON DELETE CASCADE and ON UPDATE CASCADE?

Schema Reference

  Foreign key definitions were added in Drupal 7 for documentation
  purposes only, and do not modify the database.


how can i store an image in my postgresql database? I want to save some data in my module's form like an image.

In fact i want to store an image in my Postgresql database.

You need the Storage API module.

This allows you to set a field's upload destination to a custom storage class, one of which is database.

I've used this module for this exact purpose and worked well.


Variables dump to Javascript console Is there any equivalent of var_export or var_dump available in Drupal, that would output variables directly to the console object (FF, Chrome - console.log() or console.info())?
I just don't feel like turning Devel & Themer stuff on and off every time I want to peek into variables...

The Drupal for Firebug module (which can be used with Chrome or Firefox) has a firep() function built in which will log a print_r of any variable passed to it into the Drupal for Firebug widget. That might be an option.

If you really want a console log, though, I think you'd have to write the functionality yourself. It isn't too hard though, here's a quick module I knocked up that works well for me:

File: js_debug.info

name = JS Debug
core = 7.x

File: js_debug.module

function js_debug_log($var = NULL) {
  $log = &drupal_static(__FUNCTION__, array());

  if ($var) {
    $log[] = $var;
  }

  return $log;
}

function js_debug_page_alter(&$page) {
  drupal_add_js(drupal_get_path('module', 'js_debug') . '/js_debug.js', 'file');
  drupal_add_js(array('js_debug' => array('messages' => js_debug_log())), 'setting');
}

File: js_debug.js

(function($) {
  $(function() {
    if (Drupal.settings.js_debug.messages) {
      for (var i = 0; i < Drupal.settings.js_debug.messages.length; i++) {
        console.log(Drupal.settings.js_debug.messages[i]);
      }
    }
  });
})(jQuery);

The above code is obviously very bare, and doesn't check to make sure console.log() is available, etc. But it will work fine in Chrome/Firefox for any var (including arrays and objects).

To use, simply call js_debug_log($var); from code; the variable you pass will be logged in the console as you'd expect.


Installed Views Module but It did not appeared in Structure I installed a fresh Drupal 7.22 on my localhost and installed Ctools and Views modules.

When i go to Structure i dint find Views link

I also cleared all cache but still same problem.

This is not my first Drupal experience, I created many views.

Here are the screen shots.

You have to enable Views UI in order for it to show up under Admin -> Structure.


How can I export the "Enable for OG Menus" content type option status in a feature? How can I export the "Enable for OG Menus" content type option status in a feature?

I have successfully exported several different OG content types into their own feature. All my settings have exported, except for the "Enable for OG Menus" option. I have a couple types where that option is enabled, and I have og_menu as a dependency. But when I enable the content type feature on a new Drupal instance, that option remains in it's default unchecked state.

I have Drupal 7.39, Features 7.x-2.6, OG Menu 7.x-3.0, and Strongarm 7.x-2.x-dev installed. As well as their dependencies.

Is there a Strongarm variable I'm missing? I don't see any in the list that look like they come from OG Menu.

I have Googled, didn't find anything relevant with the search terms I tried.

I searched the issue queues of Features, OG Menu, and Strongarm to no avail.

Any suggestions?

I was missing a Strongarm variable.

Strongarm lists:

og_menu_assignment
og_menu_block_links
og_menu_context_limit
og_menu_create_by_default
og_menu_enable_page
og_menu_enable_section
og_menu_hide_create_option
og_menu_hide_help
og_menu_max_menus_per_group
og_menu_show_blocks
og_menu_show_nodetype

The variables I needed were:

og_menu_enable_page
og_menu_enable_section

og_menu appears to create a variable per content type you want to use it on. In my case I had two content types, page and section. Once I added those variables to my feature, it successfully exported the setting.


In the views are not displayed in the widget attributes field Form add to cart I need to display the attributes of the widgets in the representations in the Form add to cart, at the moment I have shown only a choice of the number and Add to Cart button

Now this (is not right):

How do I need to make it (what you need):

In the second image I have in the base table of contents it is possible to select the field of Content: Product variations and in it there are all the necessary attributes to me colors and sizes.

In the first image I have a base table Search API prime field Commerce item: Form add to cart in does not display attributes such as color or size selection, I can not achieve that result as the second image I have of the field Content: Product variations, as it were, I did not connect the relationship, the entity does not have the right, there is a field Indexed, Commerce item and some of the fields Content.

This capability is necessary for me to make a quick order from the catalog.

Try to use instead Content: Product variations field Content: Rendered Node witn selected to render custom view mode like a "Product variation".

In display custom view mode should be disable all fields, but Add to cart form keep enable.


Is there a way to trace PHP errors logged from Rules? Occasionally I'm seeing an error in the error_log

[10-Apr-2015 10:16:45 America] PHP Parse error:  syntax error, unexpected 'Some text' (T_STRING) in /home/simulab1/public_html/profiles/commerce_kickstart/modules/contrib/rules/modules/php.eval.inc(146) : eval()'d code on line 1

This could be coming from any number of Rules we have. Is there any way to pin this down to the specific Rule in question?

TIA

If Xdebug is installed in the machine, it dumps a stack trace to your Apache logs. That might give you a better hint at the context.

If that fails, look at all your Commerce rules and try to find the one with a execute PHP action.


Displaying content based on the field value I have a view that displays my content of a specific content type that has a image field. I also have a check box field for that content type. My requirement is that i need the content that has the checkbox checked to be displayed at the top of the list in the view. Could someone tell me how to achieve it?

Under Sort criteria add your check-box field and set it to Sort ascending (it may be descending in your case depending on your field values).

Then if you have more than one Sort criteria Rearrange them so that the checkbox field comes first, on top. This way the results are first sorted by the check-box field value.

This works independently of the image field. Is your image field tied to the check-box somehow?


What's the event triggered after an autocomplete has run and how to retrieve the value selected I have a node add form with a term reference that uses autocomplete widget.

I want the "tid" of the filled term by the user using the autocomplete widget.

No event is triggered at the moment (as of 7.34), but there's a patch on this issue that should let you use something like:

$('#input-id').on('autocompleteSelect', function(event, node) {

});

or if you're using on old version of jQuery

$('#input-id').bind('autocompleteSelect', function(event, node) {

});

Where node is the selected item. You should be able to get the tid from one of the properties on that object.


profile 2 module with services module i am creating a web service for user registration. I just add some fields in user registration form using profile2 module. How can i integrate this with services module. i just want to make a services with the new fields

I'm assuming you're familiar with Services.  In your endpoint,
Copy the pattern here:

                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'A valid username',
                        'source' => array('data' => 'username'),
                        'optional' => FALSE,
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'A valid password',
                        'source' => array('data' => 'password'),
                        'optional' => FALSE,
                    ),

For your arguments, and add your field machine names.

Inside your callback, you can set $form_state['values'][...] with the passed values, and then use

 drupal_form_submit('user_register_form', $form_state);

To register the user.


How to enable insert module in installation profile? I want to use the insert module for a file field but I can't get it to be enabled programmaticly. Is there a setting like 'insert' => true, or something like that? Is there any documentation about the these settings because I can't seem to find any info on the web?

You can enable insert by updating the field instance settings with these two core functions:

field_info_instance
field_update_instance

for example:

/**
 * Enable insert field settings
 */
function MODULE_field_settings_enable_insert($entity_type, $field_name, $bundle){
  // Load field instance
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  // Build insert settings array, these image styles are just examples
  $insert_settings = array(
    'insert' => 1,
    'insert_absolute' => 1,
    'insert_styles' =>
    array (
      'image_236w' => 'image_236w',
      'image_237x147' => 'image_237x147',
      'image_486w' => 'image_486w',
      'colorbox__236w' => 'colorbox__236w',
      'colorbox__237x147' => 'colorbox__237x147',
      'colorbox__486w' => 'colorbox__486w',
      'auto' => 0,
      'link' => 0,
      'icon_link' => 0,
      'image' => 0,
      'image_60x60' => 0,
      'image_62x62' => 0,
      'image_62x82' => 0,
      'image_67x67' => 0,
      'image_69x52' => 0,
      'image_71x44' => 0,
      'image_71x71' => 0,
    ),
    'insert_default' => 'image_237x147',
    'insert_class' => 'caption',
  );
  // Add the insert settings to the field instance widget settings
  foreach($insert_settings as $key => $setting){
    $instance['widget']['settings'][$key] = $setting;
  }
  // Save the field instance
  field_update_instance($instance);
}

// Then you can enable insert on a field instance with
MODULE_field_settings_enable_insert('node', 'field_images', 'article')


Image source path - secure way which is the secure way of displaying the image_path in src ?

`a. <img src = "<?php print check_url($image_path) ?>" />`
b. <img src = "<?php print check_plain($image_path) ?>" />
c. <img src = “<?php print htmlspecialchars($image_path) ?>” />
d. <img src= “<?php print strip_tags($image_path)?>” />

check_url basically checks for dangerous protocols in the url and escapes any special characters as HTML entities for output. Normally it's not needed unless outputting a raw external / absolute URL. For relative URLs, Drupal adds the base url automatically.

better to use first(a) option.


Drupal private field I have got  a status column for a web form event and so that it is editable by admin. Once the status is updated the end user is not able to see it, because it is a private field.

Use one theses modules :

User Field Privacy

  All the user fields should have an "alterable privacy" checkbox.
  If this checkbox is ticked, the user should be presented with an    additional checkbox for the privacy-enabled fields on user edit forms
  to be able to make that fields' values private.
  If this second checkbox is ticked for a field of a user, only the    site administrators (members of roles with the "Access private
  fields" permission) and the user herself should be able to view that
  field's value.

CCK Private Fields

  This module allows users to mark administrator selected CCK fields as
  Public (visible to everyone), Hidden (visible to node author, hidden
  from everyone else) or Private (visible to node author and "friends";
  see requirements section below).

Field Permissions

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned    based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on    who the entity owner is.
  Permissions for each field are not enabled by default. Instead,    administrators can enable these permissions explicitly for the fields
  where this feature is needed.


views_query_alter add condition This looks appropriate for D7, but add_where doesn't exist in D8. What should I use?
/**
 * Filter out the current node from the view query
 */
if ($view->id() == 'videos') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node) {
        $query->add_where(0, $node->ID(), 'nid', 'NOT IN');
    }
}

You try code:
 use Drupal\views\ViewExecutable;
 use Drupal\views\Plugin\views\query\QueryPluginBase;
....

   /**
    * Implements hook_views_query_alter().
    */
    function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
     $query->addWhere(0, 'node__field_data.nid', [1,2,3], 'IN');
    }