Rules scheduler reacting on last comment? I have a content type with comments activated and would like to have a rule that triggers a component when there is no new comments posted after a week. The component works as designed with rules scheduler, but I am having problems with creating a rule.

I have tried to create a rule that reacts on the event "After saving new comment". However, without proper conditions every comment will be scheduled to trigger the component one week after is is posted. The rule needs to overwrite existing scheduled actions if a new comment is posted on the same node. How can I achieve this?

To my knowledge, there is nothing in Rules to "overwrite existing scheduled actions" (as in your question). However, by every time attempting to perform an appropriate delete of an already scheduled rule, prior to scheduling a new rule, you achieve a similar result. And such attempt just gets ignored if there was no scheduled rule yet. Read on for more details ...

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" for an illustration about how to delete scheduled tasks, using the "schedule_delete". As explain in that answer: the schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

To make this work (that you actually indicate the exact scheduled task to be deleted), you need to specify an appropriate "identifier", like "[account:name]" in my example. To understand how I know what in my case the identifier is of the task to be deleted, look at the way I specified my (new) scheduled task to be created: it is "identifier" : "[account:name]", which  is what I used as my identifier to schedule a task.

In your case, I think using the node's ID as part of the identifier would be a pretty good choice for such identifier.


creating links containing anchors In relation to Drupal 8 ... if a user wanted to create a link such as the following:

link

How could such a link be created, normally creating a link requires the use of the Url object and so the symbol '#' can't normally be used, nor can 'javascript:void (0)'.

Essentially I'm trying to create an link with an anchor tag in it.

Thanks.

Url component is not able to generate URLs with empty anchors, so you need  create an anchor on your page or use existing one.

use Drupal\Core\Link;
use Drupal\Core\Url;

$url = Url::fromUserInput('#main-content');
print Link::fromTextAndUrl(t('Link text'), $url)->toString();


Undefined function user_load() My Drupal 7 installation works fine, except for drush, which does not.

  $ cd /srv/www/drupal_site

  $ drush pm-refresh

  PHP Fatal error:  Call to undefined function user_load() in
  /usr/share/php/drush/includes/drupal.inc on line 138

  Drush command terminated abnormally due to an unrecoverable error.

  Error: Call to undefined function user_load() in
  /usr/share/php/drush/includes/drupal.inc, line 138

  Drush was not able to start (bootstrap) Drupal.

This is Drupal 7.24 and drush 5.10.0 from Debian. A couple of modules and themes have been installed from drupal.org but IMHO nothing fancy. Curent versions of drush6 or drush7 refer to a missing drupal_get_profile() function but otherwise don't help.

Any ideas what the cause of this problem is, and/or how to debug this?

EDIT: It works fine, except for these spurious error lines displayed on the web page (even though I do not use any sort of debug mode), as reported by a user:

  Notice: Undefined index: post-load integration files in libraries_load_files() (line 697 of /var/www/drupal7/modules/libraries/libraries.module).

This may or may not be related to my problem.

I tried using Drush 6.x/7.x, but it just returns a different error message.

  Call to undefined function drupal_get_profile() in /usr/share/php/drush/includes/bootstrap.inc on line 963

drush cc hits an error before it can do anything; the same happens with drush rr, which returns a different error, but equally intractable.

php-apc is not installed; I have Memcached, but killing it didn't change anything.
I did not change any module weights.

We got the same errors here.

After some time we recognized that our database-import (cloning production db to local dev machine) went wrong and the database wasn't populated properly. After fixing the db the errors went away...

So - my hint: check your database structure and data.

BTW: There is a similar question - but with an memcached in the drupal setup


How to hide 'Configuration' tab for specific user I'm looking for a way to configure the Backend for a specific user.
For example: I want to hide the 'Configuration' tab.

This can be done easily without any coding or other modules. Just go to /admin/people/permissions and then uncheck the box titled "Use the administration pages and help" in the System section. The user's with that role will no longer see the configuration link.

Also note that you should make sure all your permissions are set accordingly. Just because you hide the link doesn't mean one who knows the right URLs can't still use the functionality.


How can I edit my search box I want to customize my search box. I want it to auto complete as I type and not to be case sensitive. What should I do to achieve this?

For the autocomplete search box, there is a fantastic module Search Autocomplete with a detailed installation guide, and also has functionality such as integrating Views and Transliteration modules (which will overcome special characters/capitilisation etc.)

There is also a Patch for an exposed filter that may be of some assistance (if you are using a custom search box that you have made) that will help with the "contains" or "contains any word" operator.


How to alter the uc_address:city form field? I have to alter cities form field in checkout page under delivery section. I have to change it from a textfield to a select options dropdown.

I have managed to do that using a separate template file for checkout page but I
am not able to use #ajax functionality of form field
In Drupal 6 it was possible using hook_form_uc_cart_checkout_form_alter(), but in Drupal 7 the address fields are rendered in a different way, and I'm not able to alter the address form fields as desired

What are other ways of changing it?

I used hook_form_alter() with an #after_build callback; I was able to change the field from text field to select option, but the #ajax parameter attached to this is not working.

It seems like ajax callbacks are attached with the hooks at an early stage. Is there any way to have the #ajax property working?

If you are using Addressfield module you can easily do that extending the module itself.

Look into the sites/all/modules/addressfield/plugin/format & you will see address.inc, where you can extend the list of region or city.

You can look for the example in sites/all/modules/addressfield/example/plugin/format to better understanding of the the format which module will accept for extending it for your list values.


Node tabs leading to related nodes I am using a webform to build a basic person node and other related nodes (contact, address) at once.

I'd like to have node tabs ("Contact Infos", "Address") when showing the person node, which are showing the related nodes using url aruments like "/node/1234/contact" or "/node/1234/address".

Do I have to use the hook_menu in a custom module or is there another way to do this?

I used panels for this. I added a new panel, which has the node with the nid of the webform as only content item in the main content area. I set the menu entry for the panel to "Menu Tab" and set the access rule of the panel to "Show only when node is of type person". This shows the desired tab element when a person node is selected.

For the webform itself I used the hook_form_alterwith the $form_id == "webform_client_form_<nid>" having <nid> as the node ID of the webform to set the #default_value of the webform field with the data coming from the person node. The ID of the person node I get by using the arg(1) function and the loading the node data with node_load($nid).

Hope that helps others.


Pass argument in view from custom form I have a view content page. I want to filters its content on the base of a custom form data.
So how we can pass or filter a view content using custom form data there?

View is built on node. In this particular node we have a field type select list.
The same select list we have created in our form. Now what ever option is selected in form, we want to use it's value in view.
We also do not have idea how to use its value.

Assuming the custom form sits in its own page. You can rewrite the output of the field, using replacement patterns, in the view to pass the required information as part of the url.

Then using hook_menu, define parameters to pass to the form

function hello_world_menu() {
  $items=array();
  $items['hello_world/%/%'] = array (
    'title' => 'My Custom Form',
    'page callback' => 'hello_world_form_function',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);
return $items;
}


Manually adding sdk for AWS SDK PHP Module The AWS SDK for PHP Module comes with a drush make script:

; Drush Make (http://drupal.org/project/drush)
api = 2
core = 7.x

projects[awssdk][type] = library
projects[awssdk][download][type] = git
projects[awssdk][download][url] = https://github.com/amazonwebservices/aws-sdk-for-php.git
projects[awssdk][download][tag] = 1.5.10

projects[libraries] = 2

What do I need to do to get this SDK manually? I am running Windows and I ran into some issues trying to add the script using drush. I already tried adding the sdk folder to /sites/all/libraries as "awssdk" but that did not work as I keep getting "Failed to load the AWSSDK" in Drupal reporting.

Assuming you have git installed, you should be able to run the following from within your /sites/all/libraries directory:

git clone git://github.com/amazonwebservices/aws-sdk-for-php.git awssdk

Alternatively, you could use the Zip button on the Github project page or the link it points to to download the zip file and put it in a subdirectory of libraries directory called awssdk.


Drupal 7 Views Table Blocks Common Fields Sorting not working in single page My site having dashboard page where I am displaying multiple Views blocks (2-3) with Table format. Each block have few common fields to display with different filters. These blocks have exposed form as well.
The issue I am facing with SORTING on common fields. The fields which are not common, sorting on those are working as expected. Filter and Paging are also working fine on each block as I have set different page id for those.

Do you have any idea how to make those sorting possible ?
Note: Ajax is ON in each block and machine id is also set different.

You need to change the Filter identifier under the More fieldset at the bottom of the exposed filters in the View


How to implement a node limit per taxonomy term? I created a Taxonomy with a "Limit" field, so that I can add term within "limit" number. Here is a screenprint of it:

My question: How can I limit the number of nodes that are using each term, so that the 'count of nodes' (= number of nodes that are using some term) can't be above this "Limit" field?

UPDATE: I try @Pierre.Vriens Answer and i think still not working..

You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed in the "blueprint" below.

Step 1

Use the Views and Views Bulk Operations module to create a view of all nodes that have a specific taxonomy term, in which you add a VBO field to it. Simply include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Step 2

Create a Rules Component like so:

Using these Rules Component parameters:

a parameter of data type that matches with the data type of your 'Taxonomy with "limit" field' (probably "integer"), let's assume the parameter has machine name node_limit.
a parameter that matches with the term reference field as defined in your node's content type, let's assume the parameter has machine name node_termreference (which can be either a single value, or it can have multiple values, depending on how you defined it in your content type).

With a Rules Condition "Check number of results returned by a VBO view", whereas:

you select the VBO view created in Step 1.
you want to check if that number of results is greater or equal to  node_limit (which is the 1st parameter used by this Rules Component).

Rules Actions:

Set an appropriate Drupal message (that the node limit for that term has been reached already).
Remove the term that was entered from the node_termreference field (which is the 2nd parameter used by this Rules Component); Which Rules Action to use for doing so depends on how that field is defined, e.g if it is a multi value field, then you should use "remove from list".

Step 3

Create a custom Rule like so:

Rules Events:

Before saving a new node (optionally limited to relevant content types).
Before updating an existing node (optionally limited to relevant content types).

Rules Conditions:

Entity has field, for the field that refers to your taxonomy term (to make this field available for further processing in your subsequent Rules conditions/actions). More specifically we'll need it (as a token) to specify a value for the node_termreference parameter to execute the Rules Component from Step 2 later on.

Rules Actions:

Fetch entity by ID, whereas you fetch the taxonomy term entered in the node being created or updated. By doing so, your 'Taxonomy with "limit" field' will become available as a token in subsequent Rules Actions. More specifically we'll need it (as a token) to specify a value for the node_limit parameter to execute the Rules Component from Step 2 later on.
Execute the Rules Component from Step 2, by passing that Rules Component the appropriate values for node_limit and node_termreference to actually perform its logic.

Done! .... only using (popular) contributed modules, with no custom code involved .... All you need is Rules, Views and Views Bulk Operations.

PS: the above is only a blueprint ... Mostly because your question has not sufficient details. E.g you didn't explain how those terms are defined in your content type).


After preview node is not saving the content. I added the data to node, after that i clicked on the preview button and it displaying preview of that node, but the problem is, node not saving the content. When i click the submit button it shows the error message

"The content on this page has either been modified by another user, or you have already submitted modifications using this form."

Please any one help me out.

This is an error that comes from the node module.

The error occurs when you submit the node form and the node has been changed by something since you loaded the form.

The change could be caused by another user editing the content, you editing it in a different tab/browser, some background task editing it, etc.

How it happens is:

You load the node edit form. The node object is pulled from the database at this time.
You make the changes.
You save the node.
The system checks the last changed date of the node object that was loaded when you loaded the edit form (in step 1) with the last changed date for that node directly in the database (the current last changed date).

It does this to stop two people changing a node at the same time, in which case one persons changes might accidentally override the other persons.

To get around the error, you have to refresh the node edit form and make your changes and save it again.

There is no way around it but there are ways to lessen the annoyance of getting to the end of an edit and being told you have to refresh.
One such way is the content locking module.

That module makes it so that when you load a node edit page it "locks" that node, so if someone else goes to the edit page while you have it locked it will give them a warning and won't let them make edits until you have finished editing and the node is unlocked.

This means you won't waste time on an edit that you won't be able to save.


How to generate a resume after an applicant submitted an online resume? I'm currently building a recruitment system using Drupal 7. In my system, an applicant who wants to apply for a job, needs to complete an online resume (one time only).

Question: Are there any modules that can generate a simple resume after the applicant finishes (saves) the online resume, similar to this Online resume example?

I would create a profile type using Profile2 module and call it something like 'Resume'. So that every user can create a Resume profile for themselves.

Then I would install Print module and enable Print PDF and set it to show up on Resume profile pages.

You must play with the permissions so that only the owner of the profile can access the profile page and the PDF version. You may have to write some custom code to make PDF version accessible only once. You may achieve this writing an access callback function for the PDF path.


How to show a different product variation other than the default one on page load ( ajax trigger ) I have a node display for more than one product variation. Normally the user has to select one of the variation options by selecting them from the drop-down list which rebuilds the node display via AJAX.
Now say for instance that I want to link one of the product variations from else where. If I simply link www.example.com/node/10 the default product variation will be displayed which might not be the one I would like to present to the user.

So I probably have to send a query parameter in the URL, for example www.example.com/node/10?product_id=15, and trigger the AJAX event programmatically in my custom module.

Please see Implement unique URLs for particular products on product displays.
It is an open feature request for Commerce, and it also links to a working sandbox with the implementation: http://drupal.org/sandbox/maciej.zgadzaj/1845182


Secure Pages Module or force HTTPS Across Whole Site? I understand that the Secure Pages module allows you to let some pages use http and force others to use https. Assuming that is correct, is there any reason for me to use Secure Pages if I'm already forcing all requests to my domain to use https?

More info below if you need it, some of which is platform specific for my host:

I'm getting ready to launch a production ubercart ecommerce site using the Pantheon hosting platform. I want to make sure to be secure and fully PCI compliant, so I was following these guidelines which state that I need to use secure pages.

However, before that, I followed these guidelines to force https across my entire site, for all environments including dev/test. I don't mind a slight performance hit because I would rather be as secure as possible.

To force https I have added some code to my settings.php file and I have also created a page rule on Cloudflare to force requests to my domain to use https.

It's overkill but I also used the recommended code in the Pantheon documentation link above in my settings.php file to redirect all traffic to https.

The documentation for installing secure pages also raises several red flags for me.

It involves applying core patches that have failed tests and suggests that you can do them by hand, which seems unreliable to me.
Some of the instructions lack explanation and seem somewhat unreliable. Not trying to be mean, but where this concerns security, it makes me worry. For example, they mention that you need to change the $base_url parameter in settings.php file, but then go on to say "This option may or may not be necessary. Some have reported that they need it, others have reported it breaks caching of their site." Similarly, after telling you to add the Cookie Domain they say: "Some have made comments that this is not necessary, or causes issues with their site. It's a recommended setting, but not explicitly required." Another unclear sentence in the documentation is that after applying the core patches: "If everything worked, you should see some output like "hunk succeeded" or something like that and you're good to go." The idea of changing core and then not explicitly knowing if I've done it correctly or not seems very worrying to me.
One of the instructions is "Adding the Cookie Domain" but  Pantheon documentation cited above also says that it "already handles the necessary environment settings to ensure that Drupal is aware the site is running under HTTPS and that user session cookies should be secured." So, there's no reason to worry about that step in the Secure Pages instructions, I believe.
Other instructions from Secure Pages involve changing .htaccess to force www or the bare domain, but I have already taken care of that by following the Pantheon documentation above and modifying my settings.php file. This seemed the more reliable way to go since Pantheon documentation says .htaccess is ignored by NGINX servers.

So since I am already forcing https across my entire site, and I correctly enabled credit card encryption by creating a folder outside of my document root, is that enough to be PCI compliant using the Ubercart Credit Card module without Secure Pages?

Frankly, I bypassed Secure Pages and just forced all traffic to be HTTPS via htaccess. I prefer all traffic to be forced HTTPS.

SecurePages generally works up front, but I have seen a lot of wacky behavior with it that I just don't bother anymore.


Remove Hashtag from url In a Drupal site, I've a hashtag appended to my url. Example:

www.myUrl.com/content/node#.UFnCybLN9Nu

I don't know where it comes from and I don't know how to remove it. Any ideas?

That is coming from the AddThis service (media sharing icons). You maybe copied a link from there or if you are using that module, you selected to track the shared links.

If it's your widget, you can disable it by removing a line in JS (there is something like "track = true" in the widget code).


read only access to prepopulated solr I'm new to apachesolr/solr/drupal so please be patient (:

I have running solr-4.10.3 inside tomcat 8 and have "successfully" connected to it from drupal 7 via apachesolr.

The solr core that I've set up is already populated with external data and I can search it successfully from the SOLR web interface. The population was not done through drupal/apachesolr indexing mechanism, but directly into solr.

How can I search my data?

I can see my fields when I go to

http://localhost:8080/site/#overlay=admin/reports/apachesolr/solr

but they are all listed as "NOT INDEXED"

I'd appreciate any help or advice.

Nat

I can recommend taking a look at Sarnia

  Sarnia allows a Drupal site to interact with and display data from Solr cores with arbitrary schemas, mainly by building views. This is useful for Solr cores that index large, external (ie, non-Drupal) datasets that either aren't practical to store in Drupal or that are already indexed in Solr.

I am using to search a solr index with emails imported with the dih


Why am I not able to pass a variable to my JavaScript code? I'm hoping someone can shed some light on this for me. I've been building my first Drupal 8 custom block via a custom module. It was all going well until I've tried to pass some values into javascript. I'm working on some morris.js graphs, and want to display data from a database.

I've tried numerous variations, but can never get the variable to work. BTW, I'm not great at Javascript, so that might be where the flaw lies.

Here is the library definition:

 morris:
  css:
    theme:
      /libraries/morris/morris.css: {}
  js:
    /libraries/morris/morris.min.js: {}
    /libraries/raphael-master/raphael.min.js: {}
    js/custom.js: {}
    dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Here is the relevant part of the block file:

 $build['#attached']['library'][] = 'module_machine_name/morris';
$build['#attached']['drupalSettings']['module_machine_name']['morris']['memGraph'] = $graph_total;

And here is the js file:

     var infoo;

    (function ($, Drupal, drupalSettings) {
      Drupal.behaviors.module_machine_name = {
        attach: function (context, settings) {

            infoo = drupalSettings.module_machine_name.morris.memGraph;

        Morris.Bar({
      element: 'graph',
      data: [
        {x: '2011 Q1', y: infoo, z: 2, a: 6},
        {x: '2011 Q2', y: 2, z: null, a: 1},
        {x: '2011 Q3', y: 0, z: 2, a: 4},
        {x: '2011 Q4', y: 2, z: 4, a: 3}
      ],
      xkey: 'x',
      ykeys: ['y', 'z', 'a'],
      labels: ['Y', 'Z', 'A']
    }).on('click', function(i, row){
      console.log(i, row);
    });

        }
      };

})(jQuery, Drupal, drupalSettings);

Can anybody help? Thanks

Have you try changing the order?

First load the drupalSettings attachment and after the library?

$build['#attached']['drupalSettings']['module_machine_name']['morris']['memGraph'] = $graph_total;
$build['#attached']['library'][] = 'module_machine_name/morris';


Sender name in "send HTML mail" rule I have a local site I am testing. I have PhPMailer installed which works fine to send plain text email with the Sender name populated properly.  However when I installed MimeMail and try to use the same rule, except using action send HTML mail, the Sender name no longer appears.  Any help would be great.
{ "rules_entityform_client_confirmation_email" : {
"LABEL" : "Entityform Client Confirmation Email",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

Try this variation of your rule (using the rules UI to import it in your site):

{ "rules_entityform_client_confirmation_email_pv" : {
"LABEL" : "Entityform Client Confirmation Email PV",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "from_mail" : "somebody@example.com",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

The only difference with your exported rule is the line with from_mail that is added (and a slightly different machine name of your rule). Adapt the eMail Id I used to fit your needs.


RSS feed without Styling I have a Drupal 7 webiste. I want RSS feed from a few views in my Drupal webiste.
I am able to get the feed but the .xml file has a lot of CSS styling in the description tag which is causing me some issues in the RSS reader.
I want to get rid of the CSS styling in the description tag.
Can anyone help ?

Thanks.

you can copy views-view-row-rss.tpl.php to your theme folder
and then

<description><?php print $description; ?></description>

replace with

<description><?php print preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $description); ?></description>

it will remove css

if you also have inline styles then you need this

<?php $description = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$description); ?>
<description><?php print preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $description); ?></description>


Set the site display language based on browser's default language I have my site in two languages i.e. English and French, I want that whenever a user visits the site, it must be displayed in the browser's default language. How to do it ?

Goto Admin -> Module -> Locale
Click on Configuration (Locale)
Enable Radio button as per you want to set default language.


Testing Modules with an External Database I'm writing an application that is using Drupal APIs to connect to an external database and doing a bunch of stuff with this data (reading/writing/deleting). I was wondering if there are any best practices for writing simpletests in Drupal 7 with this kind of application. I know simpletest basically installs a new instance of Drupal, then uses this sandbox environment to do testing. However none of the schema for this external database is defined in drupal.

Any tips on how I can test against this database, and not have a bunch of left over data when tests complete?

User the setUp and tearDown methods to setup and tear down your external db.

A typical thing would be to write code that first empties the db and then populates it with the test data.


Create an image slideshow with multiple image fields per node I'd like to create an image slideshow using views slideshow. I see a few ways of doing it, like this one create-an-easy-jquery-slideshow-in-drupal-7, but they all require a single image per node.

I would like to have a content type that accepts multiple images and still retains similar functionality. So there is a list of thumbnails at the bottom, as a pager, and a single image above that is activated by hovering the thumbnails below.

I'm sure there is a way to do this. possibly with a few more modules? I'd love to know.

EDIT: This is drupal 7

You can achieve this using Views Slide Show.... See this example I've done here http://www.cnngo.com/hong-kong/visit/hong-kongs-temporary-june-4-memorial-museum-568132 which is using Views Slideshow (ThumbnailHover) + Simply Scroll Jquery Plugin. See images below...


Webform what is format required to prepopulate datetime element Sending default date format (medium) from VIEW rewrite results link, URL adding
?apptdatet={{ field_apptdatet }}
This never fills the webform datetime field. The value is shown in the url as medium formatted date. day mm dd yyyy hh:mm:ss
On the webform the apptdatet field shows the correct format mm/dd/yyyy hh:mm:ss, the value is always blank however.
in the view apptdatet shows as Mon 05-14-2018 15:30
Does anyone know what Webform is looking for?

You need to use an ISO date.

?apptdate=2018-06-13T01:01:01-0400


Table creation in install module returns error I am trying to create a table using a custom module in the install file:

function leave_tracker_schema() {
  $schema = array();
  $schema['leave_balance'] = array(
    'description' => t('The base table for employee leave balance.'),
    'fields' => array(
      'lid' => array(
        'description' => 'The primary identifier for a row.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE),
      'eid' => array(
        'description' => 'The tocken got from employee data.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => 0),
      'casual' => array(
        'description' => 'The casual leave balanace of employee.',
        'type' => 'int',
        'not null' => TRUE,),
      'sick' => array(
        'description' => 'The sick leave balanace of employee.',
        'type' => 'int',
        'not null' => TRUE,),
      ),
    'indexes' => array(
      'node_changed'        => array('changed'),
      'node_created'        => array('created'),
      ),
    'primary key' => array('lid'),
    );
  return $schema;
}'

but this returns an error when I install the module

  'PDOException: SQLSTATE[42000]: Syntax error or access violation: 1072
  Key column 'changed' doesn't exist in table: CREATE TABLE
  {leave_balance} ( lid INT unsigned NOT NULL auto_increment COMMENT
  'The primary identifier for a row.', eid VARCHAR(255) NOT NULL
  DEFAULT 0 COMMENT 'The tocken got from employee data.', casual INT
  NOT NULL COMMENT 'The casual leave balanace of employee.', sick INT
  NOT NULL COMMENT 'The sick leave balanace of employee.', PRIMARY KEY
  (lid), INDEX node_changed (changed), INDEX node_created
  (created) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'The
  base table for employee leave balance.'; Array ( ) in
  db_create_table() (line 2720 of
  /var/www/html/cybpedia/includes/database/database.inc).'

In your indexes element you're specifying 2 columns, changed & created, that don't exist. You need to have these columns added to your fields element or remove the indexes.


How do I release a Drupal Distribution I have been developing a site and I feel that it would work really well as a Drupal distribution. I have no idea about how to create one, but I am familiar with drush make, install profiles etc. What is a Drupal distribution and how do I release one? What are the main benefits?

Take a look at Packaging a distribution on Drupal.org

Here are the steps:

Assemble the pre-requisites
Create a Drush Make file
Convert to a Drupal.org-specific Drush Make file
Build and verify it works
Commit your code to Git
Release your code on Drupal.org
Maintain your distribution

Another great tutorial How to Write a Drupal 7 Installation Profile

Also there is Profiler Builder module.

  Profiler Builder is a module for automating the creation of
  installation profiles and distributions. It has support for the
  Profiler installation profile simplifier library but is able to run
  independent of it (1.0-RC4+). This module creates a downloadable tar
  package that gives you a well made installation profile and associated
  drush make file based on the site its installed on.


how to block a user from publishing a node in drupal 7 Please tell me that the user creates a node and he or she cannot publish that node on website and administrator can review that node and then the administer publish that node....

There is workflow module which suits your requirement.

  The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.


How do I theme a link? In Drupal 7 this was possible.

$link = array(
  '#type'  => 'link',
  '#title' => t('My Title'),
  '#href'  => 'node/1',
);
drupal_render($link);

But I've tried this with Drupal 8, and it does not output anything.

$link = array(
  '#type' => 'link',
  '#title' => t('test'),
  '#url' => 'node/1',
);
drupal_render($link);

Is there a way I can render a link without having to call the Link plugin directly, or create my own theme function?

I'm theming a field group formatter, which must output a render array.
The use of drupal_render() is deprecated and should not be called directly; I'm using it here to make my example clearer.

I think the problem with your Drupal 8 code is that '#url' needs a URL object.

External URL

'#url' => Url::fromUri('https://www.drupal.org'),

Internal URL from a route

'#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),

In Drupal 8 you are not supposed to render yourself. When porting code from Drupal 7, remove all rendering and return only render arrays.


Create a view with mix of content and files Is there a way to create a view that will allow showing listing of two entity types, for example combine items from the Content and File Entity Files views?

Lets say we wish to show a listing of all content belonging to a user. We create a view for Content entity, then add user as a required relationship, but this does not show the file fields to be added to the view.

Thats tough to answer without a little more information.

It depends on whether or not they share anything in common. Views over on the right hand side of the UI has a menu for what are called relationships. You could for example setup a content type based view and then add a relationship to the user who created the content type node. After the relationship was created you'd then have access to information stored (fields) on the user as well as the fields from the content type itself. What these relationships are doing behind the scenes in views is setting up SQL joins between the various tables in your Drupal database.

Another thing you might want to look into is entity references and taxonomy tags. Both of those can be used to setup connecting points between pieces of content that can be rendered by a view much in the same way.


hide "Submitted by ADMIN on THU, xx/xx/xxxx - 00:00" in a view I created a view listing a type of content.

This list shows the title of the content, publication information, images, link...
I would like to get ride of the publishing information but I don't find the wright parameteres.
Thank's to any of you who could help

You don't change that in view.

To perform this step, make sure you are logged on as an administrator, choose the content type you would like to edit by going to » Administration » Structure » Content types.

and under display settings tab, uncheck the display author and date information. Once you are done, save the content type


Several same product with a customizable field I need a customizable field for a product in Drupal 8 drupal-commerce.
I succeeded to add such field through an order item type.
But if I want to add several same products on cart, this field stand uniq for all the products.

How can I have a line in cart by same product with the specific value of the customizable field for each one (I'd like to avoid the creation of a product variation by specific value. This specific value is customizable and so not in a finite set)  ?

Thank you very much for your help.

I think I found how to answer to my need :-)

The configuration is done throught the product settings (Commerce>products then select the product to configure and click to edit)

In "Manage display" tab, edit the configuration of the "Variations" Field which is in Format "Add to cart form". Uncheck box "Combine order items containing the same product variation."

Hope it helps !!


How do I import a csv-file into a table via Drupal? I would like to import a csv into a table via Drupal. I use Drupal 7.

I create a content type 'Import', which contains a File field to upload a file to the server (destination: sites / default / files / import / *)

When I validate my form content 'Import', I will wish to make a db_query ()

db_query ("
LOAD DATA INFILE '$ csv_filename' INTO TABLE $ temp_table
FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n'
IGNORE 1 LINES ");

$ csv_filename, I test the relative and absolute way, but drupal tells me it can not find the file. I even give the rights to the file to test 777 but it is not ca.

$ temp_table is my table, it already exists in the database.

You would know the procedure and a use case that works for this query?

I don't know if this quite what you're looking for, but the Feeds module can import CSV content into nodes. Perhaps it could help...

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from
import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files


Link a field in content types to the user profile I want to link the output of a field (e.g. "Written by:Name" or "Photographed by:name") in the content type (e.g. Article) to the user profile.

Can anyone help me with it?

First, you should make sure that the default author relationship isn't sufficient to satisfy your needs. Every content type has a creating user; this relationship can usually be used to create any necessary links between the content and the user in Views, Panels, or other modules.

However, sometimes you need to have multiple users associated with content. Your "photographed by:" example sounds like a good example of this use case. In that instance, I would use the User Relationships module to add a User Relationship field to the content type.


creating menu items with children (sub items) i want to have a menu option called Info in my 'main menu', which has children of Policies and Contact. how can i set it up so that when a user clicks on Info, it just shows the child options in the drop down underneath Info and doesnt display a node? I only seem to be able to achieve what I want by setting up a blank dummy node which Info is linked to. I'm using Superfish, but i dont think thats relevant.

How about installing Menu attributes. See if it's nofollow option works. If not, still use it by setting a class of 'no-follow' on this particular menu-item. Then add some jQuery to you pages wherein you target the anchor tag related to this class for its click event and disable the default action. I don't think there should be a conflict as Superfish opens up menus on hover, I think? But try. And also set up the menu so that it points to the first child so that Drupal menu UI will accept.

How to Disable/Inactivate Some of the Non-Leaf Menu-Items (but keep their children visible and enabled/active)


Css from zenbased theme not getting processed I have something weird going on. My font-style of my zen-based custom theme is arial, verdana, sans-serif but what's showing is a serif font type.

I checked all the following:

CSS compression turned off.
flushed caches
Activated a different theme and set it as default, then changed some css and it worked so now I know it has to do with the zenbased custom theme.
Went into the file manager of my host's cpanel directly and made changes to my stylesheets directly to see if changes would make any effect on the site but no success.
The site is run on hostgator
checked to see if stylesheets are mentioned in the info file in a
proper fashion

This is a good checklist for resolving css bugs - I would suggest two more that I've used when stuck on css bugs that may help you resolve this quicker next time.

Check the element in firebug or developer tools to confirm whether the CSS file you think should be loaded actually is and what css styles are actually being applied to it. In this case, you could have determined that the file was loaded but the styles weren't so you could isolate your debugging to the syntax of the statement.
Try using an external validator on your css file, like:

http://jigsaw.w3.org/css-validator/

Most of the feedback from this will be noise but it may highlight syntax errors in your file.


Image styles not generated during config import Situation:
Drupal 8.6.9 running DrupalVM with Ubuntu 16.04, Apache 2.4.18, Php 7.1.26
with default settings except for the location of the drupal site.

I am trying to do a migration of a Drupal 7 multilingual site to Drupal 8.

Plan is to setup the Drupal 8 site with as much settings and modules as possible so I can alter the content during the migration such as migrating a D7-field to a different D8-field.

I wiped the default DrupalVM drupal site so I can start from scratch.
So far I have done a drush site-install with standard profile, enabled some contrib modules that are also in the D7 site (pathauto, search404, etc.) and manually set the necessary settings.
One of them is adding the 'field_image' to the 'Basic Page' content type.
I've exported the settings (Config Synchronization) to the config sync directory.

To start from scratch I run a script that does:

drush si standard
drush en <various modules installed with composer>
drush cset "system.site" uuid <uuid set in system.site.yml>

When I stop here and manually create several page nodes through the UI I can successfully add images and the thumbnails are created accordingly.

When I go on and import the config settings with:

drush cim sync --partial

Everything is imported succesfully and everything looks fine.

However, when I add the same page nodes through the UI the images are uploaded successfully but the image styles are not created. The 'styles' directory stays empty and the Apache logs show:

[Sun Feb 10 20:03:18.426565 2019] [proxy_fcgi:error]
[pid 9432:tid 140423712450304]
(32)Broken pipe: [client 192.168.88.1:59863]
AH01075: Error dispatching request to :
(passing brigade to output filters), referer: http://www.drupalvm.test/node/add/page

(error broken in several lines to avoid scrolling)

No errors in php-fpm logs.

The error seems to point to a bug in Apache 2.4/mod_fcgi, but that has been fixed in 2016.

Also, because the problem occurs after reading in the config settings, not before, I suspect the problem is either related to the config settings or to Drupal itself.

Does anyone have any idea what to check to solve this problem? I'm on this for days now with no success.

I went through adding all the files one by one and finally found the problem:

image.settings.yml contained:

suppress_itok_output: true

Once it was changed to false the problem disappeared.


theme taxonomy term object I created a module that looks up some taxonomy terms using taxonomy_get_tree() does some stuff with it and then passes it to a template file.
In that template file i want to display them sorted according to some parameters.

The sorting stuff and all works fine but in the end i would just like to display the term using its standard template. But i can't get this to work, i have the entire term object and what i thought i had to do was something like:

theme('node', array('elements' => array('#view_mode' => 'teaser', '#node' => $term)));

but the array needs a lot more items then i can provide, so isn't there an easier way?

You are passing 'node' as the $hook value, although your data is for a taxonomy term rather than a node. Trying using the hook 'taxonomy_term' instead of 'node'. I'm not sure what the proper structure for the $variables array is, but if you have the full term object, I would try just passing $term as the second parameter.

documentation for theme()
http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7

documentation for theme_taxonomy_term()
http://api.drupal.org/api/drupal/developer--theme.php/function/theme_taxonomy_term/7


Solr ignoring NOT but works with "-" and "!" I have a apachesolr module which works well except in one case. I'm not sure what happens when NOT is entered in query, it behaves as OR. It even works for ! and - case.

For eg.

"apple" -"orange" //Results that only has "apple" but not "orange"
"apple" NOT "orange" //Results all the entities that has either "apple" or "oranges"

I have the a very similar installation on another site which seems to work without flaw. Any thoughts on what might be causing this?

Issue was with my implementation. Before the query was posted to Solr, I was doing following:

$query = strtolower($query);

This made the NOT to not hence it wasn't working as expected.


How to right align text in custom form textfield in Drupal 7? I have a custom form with a textfield that takes numeric values (temperature). I want to right-align the text typed in textfield. Should I use CSS or is there a Drupal attribute to do this?

Here's the present code:

$form['temperature'] = array(
            '#type' => 'textfield',
            '#title' => 'Answer',
            '#description' => 'Enter temperature in &deg; Fahrenheit',
            '#required' => TRUE,
            '#size' => 6,
            '#maxlength' => 6,
            '#field_suffix' => '&deg; Fahrenheit',
            '#element_validate' => array('_myform_temperature_validate'),
        );

Yes, add a custom class, or use an existing one. You can add custom CSS styles to your form using #attached.


Adding child elements to checkbox/radio form elements How can I add child elements to a checkbox/radio element? I have the following code.

$form['search_product'] = array(
    '#type' => 'radio',
    '#title' => t('Product'),
);

$form['search_product']['search_attributes'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'name' => t('by Name'),
        'model' => t('by Model'),
        'catalog_no' => t('by Catalogue No.'),
        'manufacturer' => t('by Manufacturer'),
        'description' => t('by Description'),
    ),
);

"search_attributes" checkboxes don't show up on the form, and I have only one radio.

I don't believe you can make a radio button a "parent".

Here's an example of using radios, checkboxes, and fieldsets.

http://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7

You might take a look at http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#container

Try removing search_attributes from search_product

$form['search_attributes'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'name' => t('by Name'),
        'model' => t('by Model'),
        'catalog_no' => t('by Catalogue No.'),
        'manufacturer' => t('by Manufacturer'),
        'description' => t('by Description'),
    ),
);


Drupal BIRT Integration I want to integrate BIRT reporting tool with Drupal 6.
Does anyone has an idea on how to do it? BIRT reporting tool basically runs on a Tomcat server.

Searching for "brit drupal" produced:

BIRT Open Source Engine integration as a Drupal module for dynamic, BIRT data-driven content pages. Allows multiple BIRT designs to be integrated as its own Drupal content type.
BIRT vs Custom Drupal Module
BIRT OS Drupal Module
BIRT Module for Drupal 6 (video)


How do I check if the user is watching the front page or the user is logged in? I like to have the same result in a template if the user is logged-in or is on the front page.

So if the user is not logged-in nor on the front page, it should be the same result as if the user is logged in and not on the front page.

I got

<?php if ($logged_in): ?>

Do something

  <?php else: ?>

Do Something Other

<?php endif; ?>

How to extend this to force drupal to do the same on front as for the logged in user if the user is not logged in but viewing the front page

In other words how to get if drupal_is_ _on_front OR  $logged_in

elseif

I am a php newbee

thank you for an explanation

I think you will want the following:

<?php if ($logged_in || $is_front_page): ?>
    Do something
<?php endif;?>


Language cookie module not working in Safari? I use language_cookie module to safe the users preferred language with a cookie. E.g. The default site language is English. But i am from Holland so i want always the Dutch version of the site: http://landberg.at/nl. But the cookie is not working on Safari MAC?

In Configuration » Regional and language » Languages i have:

URL (enabled)
Cookie (enabled)
User (enabled)

How can i make it work also for Safari?

(i use this module instead of IP redirect because with IP redirect you can not switch the language after you are redirected..? So the only solution in my opinion is to do it with a cookie. Or does somebody has another idea about this?).

I think you should further verify/tune your configuration at Configuration -> Languages -> detection and selection: the order you mentioned (= 'URL, Cookie, User') seems a bit strange to me. I.e. it'd be interesting to see what results you get by specifying "Cookie" BEFORE "URL" in your case.

Because with your current order, "Cookie" will only be used to select your preferred language if from the "URL" it's impossible to decide about which language should be shown. Though "User" is probably fine to leave it as the last one.


Is it possible to change the tab order of MENU_LOCAL_TASK items on a given page? I have created a couple MENU_LOCAL_TASK items for my advanced search page in Drupal 6, but they appear at the end of the tab list on the far right. I would like my new items to appear first in the list of tabs.

Is there an easy way to accomplish this? I tried setting the weight of my new task items to -99 but this appeared to do nothing.

An easy and correct way is to change the weight as you do. Did you clear menu cache?


About Drupal 7's permissons I'm new to drupal and when I looked at table {role_permission}, I found that permissions were stored as text string (e.g. "edit own page content"). But when I did a grep in drupal's folder, for some permissions they only appeared in *.test files (In those files, some users with those permissions are created). It seems that some permissions, like "edit own page content", are not used at all, otherwise they should appear somewhere else when they are checked.

Any insights on access control mechanism in drupal would be appreciated.

Thanks,
ZM

A straight grep for the full string may not find these, but they're used. For instance look in the modules/node/node.module, where you find calls such as:

if (user_access('edit any ' . $type . ' content', $account)
  || (user_access('edit own ' . $type . ' content', $account)
  && ($account->uid == $node->uid))) {

Note that the string is constructed on the fly, where the content type (e.g. page) is inserted into a template to form the string "edit own page content".

These strings are mostly used to call user_access, so to see where and how they're used, you may want to search for this function.


Alternative for the core statistics module that also includes pages created using Views? I want to make a block, which shows the title of 10 most visited contents of my site and then display those as an ordered list.

My pages are created using the Views module. I tried to get it done using the core Statistics module. But it lists only Articles, Basic pages, or Content types which we have created. But it doesn't list pages which are created by Views.

Is there any contributed module for this?

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

Top pages (table with columns Title, Path and nr of Hits). Here is an example of this report:

Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor). Here is an example of this report:

If you follow any of the "details" links in the example above, you'll get something that looks as in this example:

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. Any visits to a Views related path will be reported in the Recent hits module. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module,
I hope this does not violate the site's policy on self-promotion.


amazons3-7-x-2.0, Multiple upload to S3, #upload_location wrong URI I installed the brand new amazons3-7.x-2.0 published last week, and the process is not straightforward.

I finally managed to have it works, and I have the CCK file field, with a typical remote #upload location URI : s3://[bucketname]/[subdirectory].

On the node form, the first file I upload works fine. It monitored the file_managed_file_save_upload($element) function, which is called with the proper argument (remote URI):  $element['#upload_location']=s3://[bucketname]/[subdirectory] .

But when I click on "add new file" and select another file, the file_managed_file_save_upload function is called with a wrong #upload_location :
$element[#upload_location']= s3://[subdirectory]

The upload then failed with the following message : "The file could not be uploaded.".

In order to get amazons3 module to work with this long awaited new release, I had to patch a lot of files with contributed patches fixing the exact same issue of bucketname in the URI.

Is somebody facing the same problem and found a solution ? I will try the plupload module see if it fixes the issue.

ok, after spending a few hours debugging the code, I have finally identified  the problem and come out with a solution :

Amazons3 implements a amazons3_field_widget_form_alter that fixes the $element['#upload_location'] :

  function amazons3_field_widget_form_alter(&$element, &$form_state, $context) {

  $field = $context['field'];
    $instance = $context['instance'];
    $delta = $context['delta'];

  if (in_array($field['type'], amazons3_file_like_field())) {
      $element[$delta]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
    }
  }

The problem is that this function is only called once, on $delta=0. Thus, it only fixes the first delta instance of the field, correcting the first upload. But the second upload fails because the bucketname is not in the remote URI.

In order to fix this, I propose the wrote following function in my module :

  function mymodule_field_widget_form_alter(&$element, &$form_state, $context){
      // On essaie de corriger les settings upload_location
      if (!function_exists('amazons3_file_like_field')) {
          return;
      }
      $field = $context['field'];
      $instance = $context['instance'];
      $delta = $context['delta'];

if (in_array($field['type'], amazons3_file_like_field())) {
    foreach (array_keys($element) as $count => $key) {
        if (is_numeric($key) && isset($element[$key]['#upload_location']) && !(strpos($element[$key]['#upload_location'],'s3://')===FALSE)) {
            $element[$key]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
        }
    }
}
return;

  }

It works well, allowing multiple uploads in S3 with the new release of the library.
Next step would be to post a patch to the amazons3 module. Which I will do now.


How to set content-security-policy header? I want to set Content-Security-Policy header in my site.

I found a module to set CSP (I have not tried it yet). But I want to know is there any option available in drupal 8 core itself to set CSP.

I may be a bit biased in thinking that the Content Security Policy module is the best solution for adding a policy to your site, but here are some of the reasons for using the module:

Integration with the Libraries API to automatically generate script and style directives
An admin interface that validates your policy configuration
Provides a reporting endpoint to receive policy violations and add them to your site log, so you don't need to use an external service like Report-URI.com (but it also provides a plugin to use it, if you do).
The Reporting API module is still in beta, but it will have improvements over CSP's reporting handler, and has a plugin to integrate with CSP module.
Some optimizations to shorten your policy where possible (e.g. If a fetch directive like img-src that falls back to default-src has the same value, it is omitted)
In the future modules will be able to integrate with CSP module to alter the policy as needed (enabling additional directives, altering the policy per-page)

There are a couple alternatives to the CSP module, if you don't want all of these additional features:

The Security Kit module allows adding a CSP policy header, but it only allows either an enforced or report-only policy, and it does not have fields for many newer directives.
The HTTP Response Headers module allows you to configure a static value for any HTTP header you want
Set a static header in your own response event subscriber in a custom module.
You can set the header directly in Apache or nginx configuration


how to? if is_front = div class "front-content" else "content" I have a view that displays the latest articles on the front page and it links to the full article. I want to force a div class to the front page to 70% so I tried to add these lines to both block.tpl and page.tpl and it doesn't take into account the condition, it just sets to front-content on both displays.

Here is the code:

<?php if (!$is_front): ?>

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

    <?php else: ?>
<?php print render($page['content']); ?>

    <?php endif; ?>

Instead of adding a new class (and a div) you can simply target and override the layout for the front page in your style sheet with:

.front .content {
  width: 70%;
}

It's possibly you need to be more specific though, so you don't target all .content on the page. I don't know how you theme code looks, but it should be something like .front #main .content.

This assumes that your theme uses the default body classes in html.tpl.php for Drupal 7

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

Or page.tpl.php for Drupal 6.

<body class="<?php print $body_classes; ?>">

Cheers,


How to edit Team Members from Drupal site I have been tasked with updating my companies website done in Drupal and I can find dozens of ways and places to configure a block, I just cannot find where I can make a simple, basic edit to the content and remove a Team Member.

When I use the search toolbar in Drupal it directs me only to the instances/ mentions of the Team Member block and NOT the actual list of Team Members. I've found the Tiers that are used to place them in the block, but still no actual list of said Team Members.

I don't know if my attached screenshot is at all helpful, but any suggestions on where to find these Team Members would be appreciated. BTW, they are not a part of the 'People' admins of the site.

You can probably find what you need at /admin/content. What you are looking at is the views interface to build a list - the list doesn't exist anywhere but in your database, and it won't exist in the database as a list, it will just be separate rows in the database table, so don't bother looking there. The list is build from the database, using the interface that you have shown a screenshot of.

You should be able to find the various items you want at /admin/content. You may have to filter by a content type, depending on how much content is on your site.


field_info_instance returns empty in hook_uninstall In a custom module, I'm creating a new field and instance for a custom entity type like this:

function mymodule_install() {
  if (!field_info_field('mymodule_field')) {
    $field = array( .... );
    field_create_field($field);
  }
  if (!field_info_instance('mymodule_entity','mymodule_field', 'bundle1')) {
    $instance = array( .... );
    field_create_instance($instance);
  }
}

function mymodule_uninstall() {
  if ($instance = field_info_instance('mymodule_entity','mymodule_field', 'bundle1')) {
    field_delete_instance($instance);
  }
  if (field_info_field('mymodule_field')) {
    field_delete_field('mymodule_field');
  }
  field_purge_batch(100);
}

...and the field and instance gets created properly. However upon uninstalling the module, only the field tables are being deleted while the field instance is still there in the field_config_instance table still having deleted = 0.

Debugging the uninstall process reveals that field_info_instance (and field_read_instances) is returning NULL...

Anyone knows what I'm doing wrong? I'm on a fresh Drupal 7.23 install...

You don't need field_delete_instance separately, because field_delete_field has it inside.

According to deleted column in field_config (you can skip this value in field_config_instance if you're deleting whole field) debug field_delete_field function.


Where do I find the vocabulary ID ($vid)? In Drupal 6 I would go to the taxonomy section of my /admin and I'd be able to find the $vid (numerical) in the URL.

In Drupal 7 (no doubt due to the introduction of terms as entities) the URL is no longer as verbose (and some would say cleaner) as it now shows the machine name (bundle name?) of the vocabulary as it can be seen in admin/structure/taxonomy/my_vocabulary/edit.

My end-game is to use taxonomy_get_tree($vid, $parent, $max_depth, $load_entities) to load my vocabulary, and work with it in glorious and plentiful ways, but alas this function does not accept a machine_name but presumably prefers the numerical $vid.

I'll accept alternatives to load a full vocab tree (i.e. all terms and their relationships to each other), but I do think that this question should be answered directly for future generations to google.

Actually you can use:

$vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$vid = $vocab->vid;


Add template suggestions for location.tpl.php to use a different layout for addresses on specific content types? I have been trying to figure out a method to override the locations.tpl.php template on a per content type basis, but I can't find any good examples on doing this with module template files rather than core template files. Is there code that could be inserted into template.php so that location--blog.tpl.php could be used in the same way that node--blog.tpl.php can be used? Interested in the location module specifically, but would appreciate pointers for general methods of theming contrib modules.

@

Drupal 7 Template Suggestions
http://drupal.org/node/1089656

lists template suggestions in core.  It references,

Custom Template Suggestions

  Custom suggestions beyond the ones
  listed below can be created. See the
  page Working with template
  suggestions.
  http://drupal.org/node/223440#custom-suggestions

which provides examples for mod'ing template.php so that "All layers from core, modules, theme engines and themes can provide the suggestions."

which may provide a start for you.


Perform custom Ajax on Views My problem is quite complex here:

I have a view table with pager. However, I don't want the "items per page" to be a select list. I want it to look like links: 5 | 10 | 15 | all. My solution for now is edit the views template and add the links with href=?items_per_page=5"and it works fine. But I really don't like that I have to reload the page everytime the link is clicked.

That's why I was thinking if it's possible to bind an onclick event to these links that will change the value of the <select> and then send an ajax post submit to the views form. I tried to do some simple $('form').submit() but didn't get the expected result (can't remember what I got, but I think either no changes or got redirected to somewhere else). I could not figure out how to mimic an ajax sumbit that views perform on this form.

I believe you can utilize theme_pager to accomplish your goals.  Look for examples on how theme_pager is implemented.  But theme_pager is definitely what you want.


Adding $terms to the byline in node.tpl.php for Drupal 7 and Acquia Prosper & Fusion Framework I'm trying to add the taxonomy term for a blog post to node--blog.tpl.php for the Fusion Framework and the Acquia Prosper Theme, but I've run in to some trouble and I'm not sure why it's not working.

The goal is to have the authorship line look like this:

By Blog Author | Posted Thursday March 14, 2013 | Filed under [Category Taxonomy Term name]

Here is the code I've got in there currently:

<?php if ($display_submitted && isset($submitted) && $submitted): ?>

By <?php print $name; ?> | Posted <?php print format_date($node->created, 'custom', 'l F j, Y'); ?> <?php if $terms: ?> | Filed under <?php print $terms; ?><?php endif; ?>

<?php endif; ?>

I've tried several different things, but I can't get anything to work. I'm thinking it should a simple fix, but I've not been able to make it work.

The tpl.php file tells me that $terms should be available to me as a variable, but I've tried everything I can think of to no avail. I'd appreciate any help you can offer!

If you look at the Drupal 7 documentation for the variables available by default in the node.tpl file, $terms is not on the list: http://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

If you want to display additional variables in your template files (from what's already there by default), you should make sure that these additional variables are actually being set in your template.php file first.

So, go into your theme's directory and find the file called template.php.  Does it have one of the following preprocess functions, in which it adds additional variables for your template file:

THEME-NAME_preprocess_node() or
THEME-NAME_preprocess_node_blog() (assuming your content type's machine name is 'blog')

If either of those exist in your theme's template.php file, look to see if the $terms variable is being set in a statement that should start with

$variables['terms'] = ...

If that is not happening in the template.php file, then the variable is never being set and will be empty.

If your theme's preprocessing isn't somehow prepping that variable for you, however, you can still try printing out your tags this way:

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

Where you can substitute 'field_tags' with any field you have on that node. :-)


Need advice on how to setup a Drupal site on a given scenario I need ideas/help on how to setup a drupal website with following given scenario. I just come up with the scenario this is not real but if I get the answers then I think I can apply on real poject.

I have two content-type Movies & Celebrities.

Movies content type will list all the movies information like...
"Movie story overview", "movie review" and "movie cast"

Similarly I have Celebrities content type which will Celeb information like
Movies acted, Bio, awards etc.

Now what I want...

First Objective:

When I add a new celebrities node to site, how can I create/add multiple pages automatically
Example: I added a new celebrity named “kate winslet” by using “Add Content”->Celebrities content type. Now when I save it there should be 4 urls created in one go.

a.   Domain.com/celebrity/kate-winslet
   b.   Domain.com/celebrity/kate-winslet /movies-acted
   c.   Domain.com/celebrity/kate-winslet /bio
   d.   Domain.com/celebrity/kate-winslet /awards

Similarly while adding a Movies content type it should generate multiple pages like

a.   Domain.com/movies/titanic/overview
b.  Domain.com/movies/titanic/cast
c. And more like this.

Note: I don’t want to create pages manually. Only one main landing page for each type should be created manually and rest of the pages should be added itself.

Now...

Second Objective:

On the “domain.com/movies/titanic/cast” page, how can I have functionality to look-up all the celebrities page titles & url and link both, a movie with its casts or an actor/actress with movies.

Example: I added a new movie “titanic”, now the movies content type may have a custom filed (CCK) named as “movie cast” where I will be adding actor/actress full name like “kate winslet”, “leonardo dicaprio” etc.

Now what I want is these names should be link to their corresponding celebrity pages like

a.  “kate winslet” shoule be linked to Domain.com/celebrity/kate-winslet

b.  And “leonardo dicaprio” should be linked to Domain.com/celebrity/ Leonardo-dicaprio

Any idea or help is highly appreciated.

This is multiple questions, really, but here's a quick answer for you:

Part 1: Using Views, you can accomplish having multiple "pages" for a given node. You'll have all the data for those pages on the one "kate-winslet" node. Then you'll create a view that takes an argument from the URL. The path of the view will be entered something like this:
/celebrity/%1/movies-acted. You will need to add the fields you want to each view or view display. Then you'll add a contextual filter, using the node id. If this doesn't make sense to you, you just need to learn how to use Views, and particularly how to use contextual filters in Views.

Part 2: Yeah, you just need to view a tutorial on how to use Views. This is a simple View, but you'll need to use the views_attach module, too probably.


GMap Module - markers not showing up I can't seem to get my markers to come up in the Gmap module - I've changed permissions, I've checked the gmap_markers.js file, etc.

The map itself comes up, but I can't get any markers to appear.

What could cause this?

Could it be permission settings on my /default/files directory?

This question is obviously very old, but I spent the last few hours figuring out the same issue and figured this might help someone else who is Googling this problem.

The problem for me was this:

In Modules, "Location Entity" should NOT be enabled.  "Location CCK" (in the Fields section) should be.

Then, when modifying the Content Types, do NOT rely on the "Location" field that is there by default (machine name = locations).  You have to add your own, additional Location field (field type = Location; widget = Location Field).

This solved the problem for me.  I created a View (Page) for a Specific Content Type with Format = GMap and Data Source = Location.module.

Then it finally worked!  Hope this helps.


Unable to get variable facebook_publication_id, it is not defined I am using Facebook Autopost module for drupal 7.

Following the instructions in from here, I went up with rules scheduler to delay posting of nodes to facebook by few minutes but it is not posting to facebook and showing

My current rule definition is:

{ "rules_facebook_post_delay_post" : {
"LABEL" : "Facebook Post delay post",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_switch_user", "rules_scheduler" ],
"ON" : { "node_update--article" : { "bundle" : "article" } },
"IF" : [
  { "NOT data_is" : {
      "data" : [ "node:field-category:0" ],
      "op" : "IN",
      "value" : { "value" : {
          "17" : "17",
          "19" : "19",
          "26" : "26",
          "27" : "27",
          "20" : "20",
          "15" : "15",
          "18" : "18",
          "24" : "24",
          "23" : "23",
          "22" : "22",
          "16" : "16",
          "21" : "21",
          "14" : "14",
          "25" : "25"
        }
      }
    }
  },
  { "NOT data_is_empty" : { "data" : [ "node:field-media-new" ] } },
  { "node_is_published" : { "node" : [ "node" ] } }
],
"DO" : [
  { "rules_switch_user_action_switch_to" : { "account" : [ "node:author" ] } },
  { "schedule" : {
      "component" : "rules_post_to_facebook_rule",
      "date" : { "select" : "node:changed", "date_offset" : { "value" : 1 } },
      "param_fb_article_post_rule" : [ "node" ]
    }
  },
  { "rules_switch_user_action_switch_back" : [] }
]

}
}

And current rule component definition is:

{ "rules_post_to_facebook_rule" : {
"LABEL" : "Post to Facebook Rule",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules_switch_user", "rules", "fb_autopost_entity" ],
"USES VARIABLES" : { "fb_article_post_rule" : { "label" : "Post to Facebook Article compoent", "type" : "node" } },
"DO" : [
  { "rules_switch_user_action_switch_to" : { "account" : [ "fb-article-post-rule:author" ] } },
  { "entity_create" : {
      "USING" : {
        "type" : "facebook_publication",
        "param_type" : "link",
        "param_user" : [ "fb-article-post-rule:author" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-link" ],
      "value" : "[node:url_www]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-picture" ],
      "value" : "[node:mdm_facebook_picture]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-description" ],
      "value" : "[node:mdm_facebook_description]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-message" ],
      "value" : "[node:mdm_facebook_message]"
    }
  },
  { "variable_add" : {
      "USING" : { "type" : "integer", "value" : "105777439461526" },
      "PROVIDE" : { "variable_added" : { "fb_pub_id" : "FB Publication ID" } }
    }
  },
  { "publish_to_facebook" : {
      "USING" : { "publication" : [ "entity-created" ], "pages" : "105777439461526" },
      "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:facebook-id" ],
      "value" : [ "facebook-publication-id" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } },
  { "entity_fetch" : {
      "USING" : { "type" : "node", "id" : [ "fb-article-post-rule:nid" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "rules_switch_user_action_switch_back" : [] }
],
"PROVIDES VARIABLES" : [ "fb_article_post_rule" ]

}
}

I have also used rules switch user to switch users based on posted author so that this anonymous issue during cron run can go but not working for me as facebook publication id and facebook authentication is not working for me.

Ok the problem was I set value incorrectly in rules component. Instead of [node:url_www] it should had been [fb-article-post-rule:url_www] which was causing facebook authentication issue as there was no link to post to facebook what is defined in their facebook app.


Adding gmap markers programmatically with a module I've been researching how to add markers to a drupal 7 gmap for more hours than I feel comfortable admitting. The reason I have to do it through a module and not views is because of client specifications that I won't go into here. The code below is what I have so far, everything I've found seems to point in this direction and it looks right to me. But when I go to the page, no markers show on the map. Can anyone help me out here?

function rrs_custom_menu() {
$items = array();
$items['search-by-towns'] = array(
    'title' => 'Search by Towns',
    'page callback' => 'search_by_towns',
    'access arguments'  => array('access content'),
    'type'  => MENU_CALLBACK,
);

return $items;
}
function search_by_towns() {
$query = "SELECT node.title AS node_title, location.lid AS location_lid, location.latitude AS gmap_lat, location.longitude AS gmap_lon, location.name as loc_name, location.street, location.city, location.province, location.postal_code, gmap_taxonomy_node.marker AS gmap_node_marker, taxonomy_term_data.tid AS tid, taxonomy_term_data.vid AS vid, gmap_taxonomy_term.marker AS marker
    FROM
    {node} node
    LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
    LEFT JOIN {location} location ON location_instance.lid = location.lid
    LEFT JOIN {gmap_taxonomy_node} gmap_taxonomy_node ON node.vid = gmap_taxonomy_node.vid
    INNER JOIN {taxonomy_index} taxonomy_index ON node.nid = taxonomy_index.nid
    INNER JOIN {taxonomy_term_data} taxonomy_term_data ON taxonomy_index.tid = taxonomy_term_data.tid
    LEFT JOIN {gmap_taxonomy_term} gmap_taxonomy_term ON taxonomy_term_data.tid = gmap_taxonomy_term.tid
    WHERE (( (node.status = '1') AND (node.type IN  ('listing', 'town')) AND (taxonomy_term_data.vid = '3') ))
    ORDER BY tid desc";

    $result = db_query($query);
    $marker = array();

    foreach ($result as $res) {
        $text = '

 '.$res->loc_name.'
 '.$res->street.'
 '.$res->city.', '.$res->province.' '.$res->postal_code.'

See map: gmap_lat.'+'.$res->gmap_lon.'">Google Maps

';

        $marker[] = array(
            'latitude' => $res->gmap_lat,
            'longitude' => $res->gmap_lon,
            'markername' => $res->marker,
            'offset' => 0,
            'text' => $text,
            'opts' => array(
                'title' => '',
                'highlight' => 0,
                'highlightcolor' => '#FF0000'
            )
        );
    }

    $map_array = array(
        'id' => "auto1map",         // id attribute for the map
        'width' => "685px",        // map width in pixels or %
        'height' => "480px",      // map height in pixels
        'latitude' => '36.10237644873644',    // map center latitude
        'longitude' => '-80.8758544921875',  // map center longitude
        'zoom' => 8,              // zoom level
        'maptype' => "Map",       // baselayer type
        'controltype' => "Small"  // size of map controls
    );
    $map_array['markers'] = $marker;

  $output = theme('gmap', array(
      'element' => array(
        '#type' => 'gmap',
          '#gmap_settings' => $map_array,
          '#input'  => FALSE,
          '#theme'  => 'gmap',
          '#children'   => '',
          )
        )
    );

return $output;
}

I wouldn't even get that fancy. Just use drupal_add_js to send an array of markers to a page, then call drupal_add_js to call your basic javascript that instantiates your map. Gmap hasn't been updated for V3 of the Google Maps API (so you need to go get a key, and you need to update the key when you move sites) and I've found that it's easiest, especially if you only need it on one page, to just call your own stuff.

EDIT: Maybe an example will help.

I had to do something similar where I wanted custom markers based on a set of results. In my preprocess I did:

  foreach($variables['results'] as $key => $result) {
    $store = node_load($result);
    $markers[$key] = array(
        'latitude' => $store->field_lat[0]['value'],
        'longtitude' => $store->field_lon[0]['value'],
        'title' => $store->title,
    );
  }
  $settings['markers'] = $markers;

  /* Add in the settings first */
  drupal_add_js($settings, 'setting');
  /* Then add in the javascript to instantiate map */
  drupal_add_js($module_path . '/map.js');

Then in my map.js:

Drupal.behaviors.map = function(context) {

  var initialZoom = true;
  mapInit();
};

function mapInit() {
  /* Get the markers variable set in PHP */
  var markers = Drupal.settings.markers;

  var myOptions = {
    mapTypeId : google.maps.MapTypeId.ROADMAP,
    scrollwheel : false,
    draggable : false,
    disableDefaultUI : true
  };
  var mapElement = document.getElementById("map");
  var map = new google.maps.Map(mapElement, myOptions);
  /* Loop through my markers and add them to the map */
  $.each(markers, function(index, value) {
    var latlng = new google.maps.LatLng(value.latitude, value.longtitude);
    bounds.extend(latlng);
    var marker = new google.maps.Marker({
      position : latlng,
      map : map,
      title : value.title
    });
  });
}


I need to remove manually a display from a view While I was testing an organic groups view it caused a block display in the same view to come up with an error message every time I try to edit it.
I could re-created the block view but can't delete the old block view through the UI.
Is it safe to delete it manually from the views_display table?

You can always try, you could also try to delete the display from the 'views_display' table, in any case make sure to do a complete dump of your database so you may restore it if anything goes wrong=)


Show unique full content on front page How do you do this in Drupal 7?  I would like to place the following items that are unique to the home page:

A views_slideshow
A row of 3 large images
Some normal typed content
3 most recent Articles

I could manage this on a normal page, but I'm not sure how to put it on the home (front) page.

You may be interested in the Panels module.  You can create custom layouts, include views/custom content, and more.

From the project page:

  An Overview of Panels
  The Panels module allows a site administrator to
  create customized layouts for multiple uses. At its core it is a drag
  and drop content manager that lets you visually design a layout and
  place content within that layout. Integration with other systems
  allows you to create nodes that use this, landing pages that use this,
  and even override system pages such as taxonomy and the node page so
  that you can customize the layout of your site with very fine grained
  permissions.


Best way to redirect a page after javascript tracking code has executed I'm looking for the best way (and also simplest if different) to accomplish this in Drupal 7.

Users arriving at example.com/special-redirect should be redirected quickly to example.com/newpage
Nothing needs to be rendered, but before they are redirected to the new URL on our site, I need to make sure our JS tracking script is executed.
the tracking script is currently loaded into the header from the theme.info file, and needs to run on every page of the site.

I assume that the URL redirect module won't accomplish this (ie. never loads the page).

I'm thinking I have to rely on the javascript method of putting this somewhere:

   <script type="text/javascript">
        window.location = "http://www.yoururl.com";
   </script>

But I'm not sure where I should put this (or a modified one) on the site.
It's just for the one page, but would putting it in the html.tpl.php file with and if statement for the NodeID work?  I'm also open to moving the tracking script if it makes sense to.

thanks for any advice

You can do something like below:

Create a custom module, If not already created (read more).
In your custom module, define a custom callback using hook_menu, and add a page callback.
In page callback function simply 'echo "script file/code"'. This will prevent Drupal from rendering various template files in your callback. NOTE:* If you use return instead of echo, Drupal will start rendering template files.
In your .JS file/code, do required tracking and re-direct user to another page.

Sample Code:

MODULE_NAME.module

/**
 * Implements hook_menu().
 */
function [MODULE_NAME]_menu() {
  $items['custom_url'] = array(
    'title' => 'Test',
    'page callback' => '_[MODULE_NAME]_callback',
    // Check required access.
    'access callback' => TRUE,
  );

  return $items;
}

function _[MODULE_NAME]_callback() {
  $jquery = base_path() . 'misc/jquery.js';
  $script = drupal_get_path('module', 'MODULE_NAME') . '/[MODULE_NAME].js';
  echo '<script src="' . $jquery . '"></script>
    <script src="' . $script . '"></script>';
}

MODULE_NAME.js

(function() {
  $(document).ready(function() {
    // Do your tracking here.
    console.log("Test");
    window.location.href = "http://example.com";
  });
}(jQuery));

Edit :

No worries, if you've not created a module before, you can follow steps given in How to Make a Simple Module with a Form and Menu Link to try how it works. The documentation is regarding creating a module which will define a menu callback and form.

Here you can find a detailed guide regarding Creating custom modules.

The code snippet I've provided above includes all basic code as per your requirement, except the tracking code which you need to write inside MODULE_NAME.js file. See the comment saying // Do your tracking here.


Theming node for views page I created a new views page which lists specific content types(products). And i have specific node node--products.tpl template file which is being used in views. I want to be able to use specific node template for views. How do i do that?

In the Other section of the views edit form, there is a link "Theme: Information." Inside that link there is a list of the many ways to template the view output. As always when theming, you start by copying the base file (e.g., views-view-unformatted.tpl.php), and make your modifications to the copy. Follow the naming conventions given in the link exactly. It can sometimes be tricky to get the dashes correct. Double-dashes are used to separate sections within the filename but single dashes are used to replace single underscores in content names. For example, for a content type named article_ratings, the template file would be named views-view-unformatted--article-ratings--default.tpl.php.


Views pagination, jquery and ajax error I have emerged me a problem with a page view and maybe someone can help me solve.
Following this tutorial:
http://codekarate.com/daily-dose-of-drupal/multiple-views-part-3
I created a view showing a content in 2 ways (such as poster and poster with text). For this purpose uses a javascript file that is responsible for displaying two different ways the contents of the view.
Everything worked fine until add a pager and save the view with ajax enabled. Suddenly everything stopped working. It works only on the first page, if you press the Pager (with ajax) the next page and nothing works.
The script is as follows:

(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {
//Sets default class for course views and toggles class when changing view.
$('#content').once('course-view', function() {
  if ($(".view").hasClass("course-view")) {
    $(".view").addClass("grid-view"); // Sets .grid-view as default class on the view

    $(".list").click(function() {
      if ($(".view").hasClass("grid-view")) {
        $(".view").addClass("list-view"); // adds .list-view to the view class
        $(".view").removeClass("grid-view"); // removes .grid-view from the view class
      }
    });

    $(".table").click(function() {
      if ($(".view").hasClass("list-view")) {
        $(".view").addClass("grid-view"); // adds .grid-view to the view class
        $(".view").removeClass("list-view"); // removes .list-view from the view class
      }
    });
  }
});

  }

    };

})(jQuery, Drupal, this, this.document);

Can somebody help me? Why only works on the first page?

Views Ajax is same as the Drupal Ajax, ajax response also run the behaviors.

What you need to do is removing the once() because it will stop your event binding for the second time. For preventing the event bound twice due to the ajax, just remember to add context as scope when you search for the element with jQuery.

(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {

  attach: function(context, settings) {

    // Sets default class for course views and toggles class when changing view.
    // Context is important here for limiting the scope.
    var view = $(".view", context);

    if ( view.hasClass("course-view") ) {
      view.addClass("grid-view"); // Sets .grid-view as default class on the view

      $(".list", view).click(function() {
        if (view.hasClass("grid-view")) {
          view.addClass("list-view"); // adds .list-view to the view class
          view.removeClass("grid-view"); // removes .grid-view from the view class
        }
      });

      $(".table", view).click(function() {
        if (view.hasClass("list-view")) {
          view.addClass("grid-view"); // adds .grid-view to the view class
          view.removeClass("list-view"); // removes .list-view from the view class
        }
      });
    }
  }
};

})(jQuery, Drupal, this, this.document);


Entity reference field search by custom field In my setup, a user can own more entities of a specific content type but the ownership is stored in the entity. The user entity does not 'know' anything about this. I know without context it seems weird but in my case, it made more sense like this instead of having an entity reference field on the user.

Now I'm trying to build an Entity Reference Display for a view so that for certain autocomplete fields I can search for users by either their name or the title of the entities they own. I created a view before that showed all the users and all of their entities so I was hoping I can reuse that field here but it seems like if I set the entity reference field to search by this field as well it just adds this view field's id to the query as if it was a user's field and it gives (of course) column not found SQL exception.

I've also tried to add a join with a view query alter hook but I could not figure out how to get the text entered by the user as that seems to be neither in exposed_raw nor in args.

Any ideas?

Edit:

Here is how my relationship is set up:

Entity -> Field referencing a paragraph that describes the ownership -> field referencing a user

And here is what I tried based on @stevekeiretsu's comment:

I set up a relation to paragraphs that have that field referencing a
user
Then I added another relation to content that has that field referencing this paragraph.
Then I added the Title field of content to the view

The problem is that it still does not show anything. If I set the relations to required I have no results.

Ok, I found the issue:

SELECT
users_field_data.created AS users_field_data_created,
users_field_data.uid AS uid,
field_member_users_field_data.id AS field_member_users_field_data_id,
field_number_ownership_paragraphs_item_field_data.nid AS field_number_ownership_paragraphs_item_field_data_nid
FROM
    users_field_data as users_field_data
    LEFT JOIN paragraph__field_member as paragraph__field_member
        ON
        users_field_data.uid = paragraph__field_member.field_member_target_id AND
        paragraph__field_member.deleted = '0'

LEFT JOIN paragraphs_item_field_data as field_member_users_field_data
    ON
    paragraph__field_member.entity_id = field_member_users_field_data.id

LEFT JOIN node__field_number_ownership as field_member_users_field_data__node__field_number_ownership
    ON
    /** HERE **/
    field_member_users_field_data.id = field_member_users_field_data__node__field_number_ownership.field_number_ownership_target_revision_id AND
    field_member_users_field_data__node__field_number_ownership.deleted = '0'

LEFT JOIN node_field_data as field_number_ownership_paragraphs_item_field_data
    ON
    /** AND HERE **/
    field_member_users_field_data__node__field_number_ownership.entity_id = field_number_ownership_paragraphs_item_field_data.vid

INNER JOIN
    user__roles as user__roles ON users_field_data.uid = user__roles.entity_id   AND user__roles.deleted = '0'
WHERE (user__roles.roles_target_id = 'member')
ORDER BY users_field_data_created DESC
LIMIT 11 OFFSET 0

This is the SQL generated by the View. As you can see it is using entity_id against vid and id against target_revision_id in the joins. This may be a bug or my lack of some fundametal drupal stuff. Please let me know if that is the case: Until then, I came up wiht this query alter to solve this problem:

function aci_ssp_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // Ifs view id is what i'm looking for
    $tables = $query->getTableQueue();

    $tbl1 = 'field_member_users_field_data__node__field_number_ownership';
    $tables[$tbl1]['join']->leftField = 'revision_id';
    $tables[$tbl1]['join']->configuration['left_field'] = 'revision_id';

    $tbl2 = "field_number_ownership_paragraphs_item_field_data";
    $tables[$tbl2]['join']->field = 'nid';
    $tables[$tbl2]['join']->configuration['field'] = 'nid';
}


When entering taxonomy terms are new ones added with different pk even if term is already in the dictionary I was expecting taxonomy terms to only be added if they weren't already in the dictionary. However, it seems that I have multiple terms added with different tid's or pk which I wasn't expecting. What is happening here?

Drupal allows you to enter multiple terms with the same name. If you want to have unique term names, use the Taxonomy dupecheck module.

  Taxonomy dupecheck module prevents Drupal administrators from adding
  duplicate taxonomy vocabularies and/or terms.


How to increase the value of the field nid in the node table in database? I'm using Feeds to import nodes from another system. This system uses very long number for its node id, like: 17675272378. As you can see this number has 11 digits. The problem is that Drupal only allows a nid value up to 10 digits, then the import just fails.

I thought of changing the length value for nid for the node table directly in the database. But it is not that simple there are a lot of other tables which has this field like: the entity_id field for the field_data_body table.

Maybe I can get to change the values in the database if I export the table and then find and replace the value '10' for '15' and then after I replace the database which the new one. But my question is: will I get other problems if I do this?

How can I sort this out?

Here are my captures:

Forcing the import to use the ID of the other system will break the sequential nature of the drupal nid.  You should add a textfield on the receiving site to hold the old site id and let drupal assign new ones.


Changing CCK field value(s) by clicking URL - possible? Advisable? I'm trying to figure out if it's possible/advisable to create URLs that get sent out in user notification emails which, when clicked, carry out actions like changing a CCK field value.

So for example - say you have an issue tracking system. There's no activity on one issue for a week, so the system sends an email to the person who posted the issue asking if they consider the issue closed.  And if so, please click here to close the issue.

They click on the "close the issue" link in their email, the CCK status field for the issue is changed to "closed," and they're taken to some arbitrary page on the site.

Is something like that doable?

In Drupal 6?

It's feasible but not advisable. Drupal's standard for changing data via URLs:
1) Use _GET variables (or simple URL paths) to _access_data
2) Use _POST variables to change data

Along with using _POST, you would want to use Drupal's Form API so that tokens and fields are generated and validated.

Options you could do to change the data via URL (e.g. link) is to:
1) Add a token to URL to validate it's only used once (or other validation necessary)
2) Ensure user is logged in (and maybe ensure he is owner of that ticket, etc.)
Hope this helps.