How to detect the newness of messages created with the Message module? I have created messages to notify users that they have been tagged in a picture or that someone commented after them on a thread; pretty much like facebook-style notifications.

How could I detect if a message targeting a user is new to him?

I had two ideas:

compare the timestamp of when the message has been created and the
session timestamp. The session timestamp is refreshed every time a session requests a new
page so I don't know if I can catch the previous value of this timestamp?
catch the same event that triggers drupal_set_message().

Would there be any other method to do that?

A recent post "This is a New Message/You have 4 New Messages" has been submitted in the issue queue of the Message module but apparently, it doesn't contain any built-in function to see if the message is new.

I ended up using a custom module with a table containing two columns: uid and lastaccess and two simple functions.

function notifmger_views_post_render(&$view, &$output, &$cache){
    if ($view->name == "notification" && $view->current_display == "page_1"){
        global $user;
        $check = db_query("SELECT * FROM notifmger WHERE uid = :uid",
            array(':uid' => $user->uid))->fetchCol(1);
        if (!empty($check)){
            $update = db_query("UPDATE notifmger SET lastaccess = :time WHERE uid = :uid", array(":time" => time(), ":uid" => $user->uid));
        }
        else {
            $insert = db_insert('notifmger')
            ->fields(array(
              'uid' => $user->uid,
              'lastaccess' => time()
            ))->execute();
        }
    }
}

function notifmger_counter() {
    global $user;
    $msgs = db_query("SELECT count(*) FROM message LEFT JOIN notifmger ON notifmger.uid = message.uid WHERE message.uid = :uid AND message.timestamp > notifmger.lastaccess AND message.type != :type", array(
        ":uid" => $user->uid,
        ":type" => "user_tagged_self"))->fetchCol();
    if ($msgs[0] != 0){
        return $msgs[0];
    }
    return NULL;
}


Can node reference be altered to include views pages? I have a site where 'related pages' is a node reference CCK field for a node. Authors can add related pages (1 or more) to a node with the autocomplete functionality of node reference.

My question is the following: is it possible to extend the CCK node reference field to include non nodes, e.g. views pages, in this case?

You could use a separate viewfield for the related views, and theme it so that the nodereferences and viewfields appear in the same list.

You could also use a link and use a custom widget if you don't wanna type the full path every time.

On a couple of sites I ended up never (or very rarely) using a view's page display. Instead I attached the view to a node, and always referred to the view via its node. This was because my advert banner system was based on nodereferences. It's not the most extensible approach, but it worked for those sites.


How do I reset Drupal Commerce orders, profiles, carts etc? I have a heavily customized commerce site that I have just completed and I need to hand it over to the client. It has a ton of test orders, profiles etc. How can I reset all of the orders, profiles (revisions), carts auto increments etc so that it's scrubbed and can start over?

There is a similar question asked here, but it only covers orders. How to reset the id of the orders generated by Commerce module

On a side note, I would imaging this would make a great contrib module as I would imagine many other would require this.

Note: Uninstalling and reinstalling commerce is not an option as there are a ton of other configs and commerce contrib modules already set.

I don't recommend truncating database tables, because you also have to consider field data / revision tables - that can get nice and tricky if you've used the same field on entities that you want to delete and on those you want to keep. There also may be other contributed modules on the site that have stored data related to these entities. Without using the API to delete these entities properly, you'll end up with this stale data laying around that may or may not cause problems later.

If I had to do this I'd either do as the other answer recommended - go through each list and use the delete links - or in the case of large data sets, I'd add Views Bulk Operations to the Views so I could delete them en masse. VBO is one of Drupal's best kept secrets - great for automating routine tasks like this.

When deleting Commerce entities, I'd start with payment transactions then orders then products and customer profiles. You need to delete both complete orders and shopping cart orders, otherwise referenced products / customer profiles will not be deletable.


How to alter a form depending how it was accessed I would like to alter the login form depending how it was accessed. As an example, if the form was access from a particular link, it would display the standard login form. If it was accessed from a different link, then the login form would be modified (ie maybe display a different title and exhibit different behaviour (redirects based on role)).

I figure I need to use hook_form_alter() but I am not sure how to tell which link was clicked. Any ideas how one would go about accomplishing this? I am working with Drupal 6 by the way.

Thanks

Inside your form_alter() hook, you can always check what page a form is on by looking at $_GET['q'], eg:

if ($form_id=='user_login' && $_GET['q']=='different/link') {
  // do form alters here
}

so if you are at www.yourhost.com/different/link, it will do whatever you tell it to do.


Adding an HTML data attribute to rows in Views I've tried rewriting the row and also theming the Views row, but I'm not having any luck. Maybe I'm doing something wrong.

I have the format of my view as 'Unformatted View', and in the format settings there is an option to specify the 'Row Class', which is then added to each row. However, I need to add a data-attribute to my rows in addition to a class. The data-attribute needs to be one of the fields - the Taxonomy Term name field (in lower case).

For instance, my field is Taxonomy Term Name. Currently, the HTML markup of each row looks like this:

Term

However, I need it to look like this:

Term

I am finding this fairly difficult to accomplish, and can't find much about it online. Could anyone be of help?

The easiest way that I found to create unique attribute per views row is to override the template file to exclude the outer div and output each row using Global: Custom text in the view excluding from display all fields and including them in the custom text field.

Here is in more detail

go to your view and click Advanced > theme > information
in style output line the bolded file name is the currently used template (let assume views-view-unformatted.tpl.php)
get the name next to the bolded file name (could be something like this views-view-unformatted--VIEWNAME.tpl.php)
copy /all/modules/views/theme/views-view-unformatted.tpl.php to your THEMENAME/views-view-unformatted--VIEWNAME.tpl.php
edit it and modify so it does not output the outer row div. It could look like this for unformatted style

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
    <?php print $row; ?>
<?php endforeach; ?>

edit all view field and check Exclude from display
add Global: Custom text and add all fields in the content using replacement pattern
your outer div in Custom text could look like this

[field_FIELDNAME]

refresh the cache and make sure in steps 1,2, your new template is used


Best way to migrate text field to taxonomy reference field I want to migrate a text field to taxonomy reference field( the Tags one).

I've 1200 nodes having a field "Organization name". Those creating the content are making mistakes like misspelled company names. I'm using the company name in the views to find all related nodes.

This will help those entering can simply choose the company names or if someone has entered IBM for International Business Machines then I can merge those terms when using taxonomy reference field.

Should I go and create a vocabulary, add all existing values as terms in vocabulary then programmatically assign the text field values to the taxonomy reference field? Then delete the text field and change references in the views etc.

I would:

Go thorough all values, grouping them by their Levenshtein distance from each other.
For all set of similar names, I would choose canonical one, and put them in taxonomy as a term.
Using Computed Field or VBO I would choose the Levenshtein closest term for each node.

Details of implementation would need a bit of polishing, but that's my general approach. Apparently you can use Views Bulk Operations both to create taxonomy terms and to set field's value on node.


How would I hide a form and display thank you content in the same area - drupal 6 I've been trying to get to grips with the form api,
I'm currently trying to hide a form after it has been submitted and to display a thank you template in the same area as the form was in.

Hoping someone might have an answer.

Thanks

Or use $form_state['rebuild'] in the submit handler and check for submitted values in the form builder. That way you can display the form the first time the user hit's the page, and after submission you display your message. This is something like a multistep form, so you could take any of the numerous tutorials for multistep forms in drupal.
Also have look at the official example in form_example_tutorial.inc


How to re-add deleted articles using the same node ids? I am running a drupal 7 website with about 1800+ articles. There were about 40 articles deleted overtime from the website. What I want to do is add  those articles again using the same deleted NIDs. How should I go about it?

Is adding these articles manually through phpMYAdmin a good idea? Are there other database tables I have to consider other than the following:

(1) node

(2) field_data_body

It really depends on the amount of data you have at hand. If the missing nodes have simple structure with only default body field,title, none or just a few custom fields, then 40 is not that big number to sweat over the code, so I would do it via database UI as phpMyAdmin. Just note other involved tables like node_revision and custom field tables if nodes had ones.

However, if the missing nodes have multiple fields and too much data to enter manually, then I would create and upload data to 40 new nodes iterating:

$entity = entity_create('node', $values);
$service_wrapper = entity_metadata_wrapper('node', $entity);
$service_wrapper->title->set($product->title);
$service_wrapper->field_custom_field_1->set($data_1);
$service_wrapper->field_custom_field_2->set($data_2);
$service_wrapper->field_custom_field_N->set($data_N);
$service_wrapper->save();

Then I would replace nids either manually in nodes and node_revision tables or by saving the missing nids in form of $nids = array(0 => 'first nid', 1 => 'second nid, 2 => '2nd nid', n => 'so forth') and then iterating them through foreach loop in custom module's function.


How to make fields of a cloned node available in Rules I have a rule that clones a node once it's flagged. I can set certain parameters for this newly cloned node but not all. I read in other posts that you have to use a conditional rule to identify what the node type is of that cloned node and then you have access to all the fields. But again not to "all" fields.

I want to set the cloned node text field "student name" to the author's first name, a text field on the user's profile. Many fields from the flagging user's profile are available but not all.

The problem was that I had to fetch the entity by property [cloned-node:author:field-firstname] inside the conditional and set the data value [cloned-node:field-student-name:0] to [firstname-fetched:0:field-firstname]
I still don't understand the actual logic why [firstname-fetched:] has to be followed by [0:field-firstname] but that works. See screenshots.
Hope this helps someone else out too.

After @Pierre.Vriens helped out my component code is now:

    { "rules_update_the_cloned_course_with_values_for_the_student" : {
    "LABEL" : "Update the cloned Course with values for the Student",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "cloned node", "component", "course", "update" ],
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "node_author" : { "label" : "Node author", "type" : "user" }
    },
    "ACTION SET" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_is_of_bundle" : {
                "entity" : [ "node-to-update" ],
                "type" : "node",
                "bundle" : { "value" : { "course" : "course" } }
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "node-to-update:field-student-name:0" ],
                  "value" : [ "node-author:field-firstname" ]
                }
              },
              { "drupal_message" : { "message" : "Machine name of this Component was: \u0022rules_update_the_cloned_course_with_values_for_the_student\u0022" } },
              { "data_set" : { "data" : [ "node-to-update:field-status" ], "value" : "359" } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : {
                  "message" : "The field \u0022Student name\u0022 could not be set with the value of the Student\u0027s first name.\u003Cbr \/\u003E\r\nMachine name of this Component was: \u0022rules_update_the_cloned_course_with_values_for_the_student\u0022",
                  "type" : "warning"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Div around img tag in Drupal 7 I am using Drupal 7 with wysiwyg (7.x-2.0)module and CK editor 3.5.3.6655. I added an image in  a block with link and the CK editor code is

     [[{"type":"media","view_mode":"media_original","fid":"751","attributes":{"alt":"contact","class":"media-image","typeof":"foaf:Image"}}]]

But Drupal is adding some divs around the img tag and the resulting code is

Then I got the W3C error document type does not allow element "div" here; missing one of "button", "map", "object", "ins", "del", "noscript" start-tag as div is not allowed inside p and a. How can I solve this?

I added div instead of p but no use.

This is a field themeing issue.  The field.tpl.php API docs and linked source is a good place to start.  The comments on that page also have useful information for you.


How to know how many elements are processed in the finish callback? I followed Smack My Batch Up : Batch Processing In Drupal 8 article to create a batch job and all works fine. But in the finish callback I can't get the total number of processed elements.

This is my code:

$operations = [];
foreach ($lines as $line) {
/*
Here I have an array of operations and each element have the name of
the operation callback function and the line that should be processed.
Maybe this is the problem.
*/
  $operations[] = ['process_line_saint_du_jour', [$line]];
}

$batch = array(
  'title' => t('Migrating Saint of the Day'),
  'operations' => $operations,
  'finished' => 'process_line_saint_du_jour_batch_finished',
  'init_message' => t('Saint of the Day migration is starting.'),
  'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
  'error_message' => t('The migration process has encountered an error.'),
  'file' => drupal_get_path('module', 'diocese_migrate') . '/diocese_migrate.batch.inc',
);

batch_set($batch);

This is my finish callback function:

function process_line_saint_du_jour_batch_finished($success, $results, $operations) {
  // The 'success' parameter means no fatal PHP errors were detected. All
  // other error management should be handled using 'results'.
  if ($success) {
    $message = \Drupal::translation()->formatPlural(
      count($results),
      'One Saint of the Day processed.', '@count Saint of the Day processed.'
    );
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
}

The problem here is that I have only one element in the $results array and I have processed 366 elements, all works fine but at the end of the batch I have the following message:

  One Saint of the Day processed.

Reading the Batch Process in Drupal 8 and Drupal 8 Batch Example articles I found the answer.

The key is in the

//Message to show during each execution of the callback function
$context['message']
//Array with the total of processed items.
$context['results']

So, the solution is in the operations callback function, now the functions is like this and it works:

function process_line_saint_du_jour($line, &$context) {
  //Custom Code
  $info = str_getcsv($line, ";", '"');
  $context['results'][] = $info[3];
  $context['message'] = t('Migrating Saint du jour @day', array('@day' => $info[3]));
}


Drush make command error when unzipping superfish module / library I am moving a website from my local machine to the prod server. I intend to do this with drush sync, looks like the most straightforward way. So, I've created a makefile on my local website, when i issue drush make myfile.make, I get this error :

superfish-7.x-1.9 downloaded.                                                               [ok]
Found makefile: superfish.make                                                              [ok]
superfish downloaded from https://github.com/mehrpadin/Superfish-for-Drupal/zipball master. [ok]
Unable to unzip /tmp/make_tmp_1386076010_529dd76a9b232/master.                              [error]

Then in tried another download link, fail with same message.

superfish downloaded from https://github.com/mehrpadin/Superfish-for-Drupal/archive/1.x.zip. [ok]
Unable to unzip /tmp/make_tmp_1386076010_529dd76a9b232/1.x.zip.                              [error]

I guess all zip files are not corrupt, something must be wrong, may be on my local install, but the error message isn't very helpful so I am stuck.

so what to do then ? anyway to fix this ? I guess the superfish module will not be installed if I move my website with drush sync ? can I reinstall superfish  with admin GUI then ?

Unzipping files needs, simply, the unzip program. Check that you have unzip-package installed on your server.


The security danger of publicly exposing an upload field On older drupal 7 websites I once faced security patches for the webform module, because file upload fields were considered insecure. There was en exploit where people could end up uploading .html files (via ajax) to your files storage and started spamming to those links.

I'm currently working on a drupal 8 project where anonymous users can fill in a form and upload their resume in a file field. I chose to create a content type and a custom form mode. Now the form is shown in a custom controller on the site.

My questions:

How (un)safe is the public exposure of a file upload field?
Are you aware of any steps taken in drupal 8 to further secure this?
Any suggestions to do this even more securely?

Thanks in advance.

Drupal places an .htaccess file in the files directory to prevent files inside from being executed. Check the status report on your site to ensure that this is correctly configured.


New User OpenID identities in Drupal 7 Scenario:

Drupal 7 site recently migrated from Drupal 6. Using OpenID connect module. All users login with Google, using a Google account with a company domain name. (user@company.com). All users that were migrated can still log in. When a new user is created, he or she cannot log in, and the OpenID Identities tab for the new user is blank. The new user is directed back to the login page. The site is also using the Require Login module, which states that it works with OpenID.

How can I get Drupal to save the OpenID Identity to the user's account? So far my only idea is to give the user a one-time link so he can log in, then ask him to add the https://www.google.com/accounts/o8/id code into the "add identities" field.
Would that even work, since it's not actually google.com for the others? All the working users have IDs that state the company name (www.company.com/id=longstring).
How can I check to see if the site is using the new OpenID protocol and won't stop working on April 20th?

I am having trouble understanding how OpenId works with Drupal.

For anyone with a similar issue, here is how I solved it.

The problem: using openid signin with a site that shows a splash login page for all anonymous users. You cannot use any splash page configuration that uses redirects, because it interferes with the openid redirect.

Solution: I removed the require login module and enabled the front page module. Then I configured the front page to use an alias with the login page for unauthenticated users, NOT the redirect option. When new users sign in, it automatically uses the company domain to create an openid and then stores it in Drupal.

Sidenote: New users cannot already have an existing account in the Drupal site, even if there is no openid yet assigned. The account is created the first time they sign in . They will not be able to do so if there is already an account attached to their email.


Corresponding entity references: two way sync I have two content types containing a reference to each other. When I update the reference on the node of the first content type, I want the reference on the node of the second content type to be automatically updated. Is this possible?

I used the CNR module in Drupal 7, but that's no longer supported.

On the CNR module page, it has introduced the replacement....

  New development is done in the http://drupal.org/project/cer module. This expands the corresponding node reference functionality to enitities. Please focus all attention on getting a stable release of cer as soon as possible.

It can do the exactly same thing as CNR...


Ordering of referenced entity I have created one content type named "collection", where I will be grouping the related articles into collection. The content type itself has other fields like title, tags etc.

To add article into collection, I have created field of type referenced entity and is working fine. Also use can add multiple articles into collection.

Now I wanted to provide the user to manage order of the articles in the collection, so that article can be arranged in proper order.

So at the time of selecting article, user also decides its order/weight.

Is there any drupal module that helps in achieving this or how can I achieve it if no module is there.

-- Thanks for your time

If you are using Entity reference has the option to sort. I will give you three choices.

1. Manually:

Go to the /node/nodenumber/edit and you can specify the order that you want  Manually seems to be your best choice because it is your user who decides the order

2. Programatically

If want to order by descending (Ascending is the default). The only it worked for me was to use array_reverse:

$value -> field_reference_field_to_reference['und']=array_reverse($value -> field_reference_field_to_reference['und']);
$value -> field_reference_field_to_reference['und'][]['target_id'] = $node -> nid;
$value -> field_reference_field_to_reference['und']=array_reverse($value -> field_reference_field_to_reference['und']);
node_save($value);

3. Fields settigs in the entity reference

There is another option of sorting in your content type field settings:

/admin/structure/types/manage/volunteer-profile/fields/field_reference

and then you can tell it to sort by

However, to be honest the last method  number 3 has not worked for me for some reason. If you made it work. Please let me know your solution. I would love to know what am I doing wrong. :)


Drupal Services 3 Login and CSRF I'm working on a Phonegap app (JS) anndn I'm confused how to pass along the CSRF token with my requests. Would I need to call user/login.json first and then store the token? For future requests how do I pull the token?

$('#page_dashboard').live('pageshow',function(){
  try {
    // Obtain session token.
    $.ajax({
        url:"http://" + website + "/?q=my_services/user/token.json",
        type:"post",
        dataType:"text",
        error:function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function (token) {
        // Call system connect with session token.
        $.ajax({
      url:"http://" + website + "/?q=my_services/system/connect.json",
      type: "post",
      dataType: "json",
      beforeSend: function (request) {
        request.setRequestHeader("X-CSRF-Token", token);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
      },
      success: function (data) {
        var drupal_user = data.user;
        if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
            $('#button_login').show();
            $('#button_logout').hide();
            $('#button_create').hide();
        }
        else { // user is logged in, hide the login button, show the logout button
            document.getElementById("welcome").innerHTML = "Welcome " + drupal_user.name + "";
            $('#button_login').hide();
            $('#button_logout').show();
            $('#button_create').show();
        }
      }
    });
        }
    });
  }
 catch (error) { alert("page_dashboard - " + error); }
});

I've been surprised by the lack of documentation and general information about Drupal RESTful services.

The best resources out there are from Tyler Frankenstein, the creator and maintainer of Drupalgap. Much thanks goes to Tyler as I started with his article here. Unfortunately, the documentation is rather old and no longer works with the current version of Services.

I highly recommend Drupalgap to any newbies that are looking to put a simple site on an Android/IOS app. It's a great tool that is well-maintained and constantly growing.

That being said....Drupalgap is great but ultimately I want the ability to expand beyond a framework requirement (i.e. Drupal). Understanding how JavaScript interacts with RESTful services is key to that point. After much effort I finally scraped together data from different sources and came up with a solution. Keep in mind that this worked for me. I'm sure there are better ways to do this but I only know this one.

Creating a PhoneGap app that Connects with Drupal 7 & Services 3.5+

My Environment:

Ubuntu 14.04
Cordova 3.5
Android SDK Manager 23
Apache 2.4.7
Drupal 7.28
Services 7.x-3.7
JQuery 1.11.1
jQuery Mobile 1.4.3

1) Setup your environment

Install Apache, Drupal, Phonegap, etc. I installed drupal to a sub-directory (localhost/drupal). Remember to setup your Services endpoint and enable resources for it. I use cordova to build the scaffolding for my Phonegap app:

 cordova create MyApp
 cd MyApp
 cordova platform add android
 cordova build

I have a symbolic link from my phonegap www folder to my apache root so I can test my mobile app on a browser before deploying.

2) Enable CORS for testing

Testing locally is a big requirement as the JavaScript console gives a developer so much more insight into what is actually happening with the code. Enabling CoRS was a requirement to get testing working. Getting CORS to function proper was a pain. Keep in mind that I'm testing from a local server (localhost) and CORS is configured to match, update your configuration accordingly:

1. Enable mod-headers,mod-setenvif
2. Add:
    Header add Access-Control-Allow-Origin "*"
   to the Apache Directory Directives (example.conf)
3. Add:
    SetEnvIf Origin "^(https?://localhost|https://[a-z]+\.my\.base\.domain)$" ORIGIN_SUB_DOMAIN=$1
    Header set Access-Control-Allow-Origin: "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
    Header set Access-Control-Allow-Methods "GET, PUT, POST, OPTIONS"
    Header set Access-Control-Allow-Credentials "true"
    Header set Access-Control-Allow-Headers "Authorization, Origin, Content-Type, X-CSRF-Token"
   to the .htaccess file at the root of your Drupal installation
4. Reload/restart apache

3) Create jQuery Mobile app
I followed Tyler's initial instructions and used jQuery Mobile to develop my application. The JavaScript was taken from a post in the Services issue queue here. This is a VERY basic app - just takes a login and outputs your username...but once you understand how the token is passed you can extend this to do ANY request.

Here's my index.html file:

<!DOCTYPE html>

    <title>Hello World</title>

        <link rel="stylesheet" href="css/jquery.mobile.css" />

Home

Shopping List App

                My Name
                <input type="text" id="page_login_username" />

                Username
                <input type="text" id="page_login_name" />

                Password
                <input type="password" id="page_login_pass" />

            <input type="text" id="page_login_token" />
            <input type="hidden" id="page_login_session_ID" />
            <input type="hidden" id="page_login_session_name" />
            <fieldset>

<button type="button" data-theme="b" id="page_login_submit">Login</button>

            </fieldset>

Here's my script.js file:

$(document).ready(function(){

function setToken(){

// Get a Token from the site
$.ajax({
url: "http://localhost/drupal/my_services/user/token",
type: 'POST',
dataType: 'json',
//crossDomain: true,
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Error getting Token
console.log('Get Token Failed');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
// Set the Token Value in a textfield
$("#page_login_token").val( data.token );
}
}); // End Ajax
}

function doLogin( tokenid ){
var tokenValue = $(tokenid).val();
$.ajax({
url: "http://localhost/drupal/my_services/user/login",
type: 'POST',
dataType: 'json',
crossDomain: true,
data: {"username":$("#page_login_name").val(),"password":$("#page_login_pass").val()},

beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", tokenValue);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function( userdata ){
$("#page_login_session_ID").val( userdata.sessid );
$("#page_login_session_name").val( userdata.session_name );
$("#page_login_username").val("Welkom SUPER" + userdata.user.name +"You are my Hero!");

// Get and Set a new Token after Login!!!
setToken();

}
});
}

function doLogout( tokenid, session_id, session_name ){

$.ajax({
url: "http://localhost/drupal/my_services/user/logout",
type: 'POST',
dataType: 'json',
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", jQuery("#page_login_token").val());
},

error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_login_session_ID").val("");
$("#page_login_session_name").val("");
$("#page_login_username").html("");
$("#page_login_token").val("");
}

});

}

function testConnect( tokenid ){
var tokenValue = $(tokenid).val();
var gorge = tokenValue.substring(14);
$.ajax({
url: "http://localhost/drupal/my_services/system/connect",
type: 'POST',
dataType: 'json',
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", tokenValue);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//alert( 'Error with Connect.json' );
alert( gorge );
console.log( 'Error with Connect.json' );
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function( data ){
console.log( data );
alert( data );
}
});
}

$(document).on("click", "#page_login_submit", function () {
    //alert("Goodbye!");
    setToken();
    //testConnect( "#page_login_token" );
    doLogin( "#page_login_token" );
});

});// End document ready

4) Test with Poster and Chrome

Firefox was a bit of a disappointment in the testing arena; except for Poster. This allows you to test Drupal Services directly by using Get/Post. Very handy for testing. Chrome developer tools came in very handy - they were the first to tell me what was actually wrong with my CORS configuration.

I hope this helps you! Feel free to add any comments/advice. I can update this in time and make it better.


Strange error updating PHP code in a node I have a 'Basic Page' node that contains PHP code which returns the following error, when I edit and save it:

  Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.

I believe it is not the real error; if I edit anything but the code, I don't get any error.

What I do is changing <?php if (user_is_logged_in()): ?> to <?php if (user_is_logged_in() && (inarray('approved user', $GLOBALS['user']->roles)))): ?>.

I'm pretty positive the code is right; the PHP filter is enabled, and the administrator user is the only user who can use it. I'm not really sure what else could be the issue.

inarray() isn't a PHP function, you're probably looking for in_array() :)

The error you're getting is probably masking the internal Call to undefined function inarray() exception that would be thrown.

EDIT

You also have one too many closing parentheses at the moment, I'd recommend separating out your code to make it cleaner:

<?php

$has_required_role = in_array('approved user', $GLOBALS['user']->roles);
if (user_is_logged_in() && $has_required_role):
  // Do something
endif;

?>


How to get entityreference_backreference data programmatically The User profile for my site contains the Entity Reference field 'Parent' which points to another User.

I have the entityreference_backreference module enabled on my Drupal 7 site.
I need to programmatically access the values of the properties added to the user entity by the entityreference_backreference module, so that for User A, I can identify all other Users which point to A via the 'Parent' EntityReference field.

If I do the following

$wrapper = entity_metadata_wrapper("user",$some_user);
$wrapper->getPropertyInfo();

I can see that that an entry for the entityreference_backreference field field_parent_user_eb is available in the getPropertyInfo() output. So the property does exist.

However, if I do

$wrapper->get('field_parent_user_eb');

it comes back with "data = null".

Also if I just try to access $some_user->field_parent_user_eb that also gives a null result.

It looks like the property is never being set.

What am I doing wrong? I can see that there is a "getter callback" defined for the field_parent_user_eb property, which is set to entityreference_backreference_related_entities, but I can't see how I can use this.

Any help much appreciated!

OK this was my ignorance of how to use Entity Metadata Wrappers.
The way to get the value of the field_parent_user_eb field is

$wrapper = entity_metadata_wrapper("user",$some_user);
$value = $wrapper->field_parent_user_eb->value();

$value contains an array of entities which (back) reference the original $some_user.

I should have read https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers before posting.


Slideshow showing 3 slides (prev - active - next) I am trying to accomplish the following:

I have a content type that contains title, img and body.

i want to show the nodes in a slideshow, like for example flexslider.

Nothing special so far.

i now want to show 3 slides at once, the 3 slides cover 100% width, where the 1st slide is the previous slide, the middle one is the active slide and the 3rd one is the next slide.
(The 1st and 3rd slide have some opacity on them to mark the active slide)

i have tried to do this with flexslider, jcarousel and jquery cycle but without aky success.

I managed to show 3 slides at once, but then i cannot navigate through the slides.

Any suggestions on how you guys would approach this would be very welcome!

Thanks in advance!

Edit:

After some more research i created 3 flexsliders (each in their own content pane) that i put into one page manager page.
I then floated them next to each other.

I configred each flex slider to skip 0,1 and 2 slides accordingly.

I now still have the remaining issue of controlling the 3 slideshows through one next and previous buttons.

Any suggestions for this would be very welcome!

Edit2:

I found the solution by studying the flexslider module. You can manipulate sliders by #ID with the following commands:

(function ($) {
$(document).ready(function(){
$(".page-about-livio #flexslider-2 .flex-next").click(function() {
    $('#flexslider-1').flexslider("next");  //Go to next slide
    $('#flexslider-3').flexslider("next");
});
$(".page-about-livio #flexslider-2 .flex-prev").click(function() {
    $('#flexslider-1').flexslider("prev");  //Go to next slide
    $('#flexslider-3').flexslider("prev");
});
});
})(jQuery);


How can enable multiple contact form in drupal 8? I want multiple contact forms(different fields) in my drupal 8 site Like Webform module drupal 7.

I have tried to add multiple contact forms and i am able to number of contact forms with different different fields but at time only one form i can able to enable. Can i enable different contact form with different menu link?

Is there any alternatives to achieve this or i need to go for custom form?

Thank you

Each has their own URL. Check contact.routing.yml but pretty sure they are of the form contact/{contact_form} where contact form is the machine name. You can create menu links and aliases to these like any other path.


Feature automatically reverts on cache clear I have an issue with Features which contains a view.  If I update the feature and then clear the Drupal cache, the view will revert to the configuration in the updated feature.

My understanding was that a feature would not be reverted unless it is specifically made to (e.g. manually revert the feature).  Is this a wrong assumption?

Here is more information of what I have tried.  On server A, I modify a view which is contained in a feature.  I then update the feature so that it contains the modification to the view.  I then commit the updated feature to git.

Now, I log into the other server, and pull in the changes from git (e.g. bring in the updated feature).  If I go to the feature's admin page I can now see that it is overridden (so far so good).

I then clear the drupal cache (e.g. via performance page or drush cc all).  If I now check the feature status, it is set to default and the view has also been modified.

Why would the feature and the view change on cache clear if I haven't specifically reverted the feature?

UPDATE:
It seems the issue only occurs if the status of the feature on Server B was 'default' prior to deploying the updated feature. See following scenarios:

SCENARIO 1:
Feature on Server B is in 'default' state.  Updated feature from Server A is deployed to Server B.  The features admin page shows on Server B now shows the feature to be "Overridden" (expected given we have deployed updated feature).

If I now clear cache, the feature's status has now changed to 'default' and examination of the relevant view shows that the changes in the updated feature have been applied.

SCENARIO 2:

Feature on Server B is already in 'Overridden' state, due to a local change I made to the view.  The updated feature from Server A is deployed to Server B.  The features admin page shows feature on Server B to be "Overridden" (expected given we made local changes to relevant view).

If I now clear cache, the feature is still shown as "Overridden" and the relevant view has not been altered.

As you can see in SCENARIO 1 the updated feature is automatically reverted on cache clear, but in SCENARIO 2 it is not.

This is not supposed to happen, a cache clear should not have any effect on overridden features.

I'm just guessing here, but have you tried to uncheck the option 'Rebuild features on cache clear' on the features settings page (admin/structure/features/settings)?

Rebuild and revert are two different things where rebuild should leave the overridden features as they are, but who knows? It's worth the try.


Is it possible to alter the cacheability of a specific entity either programatically or via configuration I am writing a custom breadcrumb builder and discovered that the breakpoint I had set in it was not firing due to cache of the breadcrumb entity. When I inspect it after creation, I can see that it is created as permanently cacheable. Ideally, I'd be able to set something in the services.yml file to tell it to ignore that specific entity. Alternatively, if there were a setter that paralleled the getMaxCacheAge() method, that would work.

As it is, it seems like my only good option here to globally switch to the null cache provider.

FWIW, here's my current little snippet of test code:

  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('TESTING'), '<front>'));
    return $breadcrumb;
  }

I just came up with a solution, but I'm not sure it's the "right" way to do it.

Anything entity that implements RefinableCacheableDependencyTrait will allow you to introduce additional dependencies with a call to addCacheableDependency(). I sort of hoped there might be a predefined dependency that was hardcoded to no cache. I didn't find such a thing. What I did find is that if the argument to that method is not an object that implements CacheableDependencyInterface, then it makes it uncacheable. So, here's what I ended up with:

  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('TESTING'), '<front>'));
    $breadcrumb->addCacheableDependency(null);
    return $breadcrumb;
  }


Feeds Importer Xpath import where guid is at the top of the context Trying to import from an XML feed using Feeds Importer XPath XML. I have had an import working from this same feed before but with uniqueness based on a title field which is no longer apropriate.

I'm trying to alter the import so that I now use a guid. The problem is that the ID I need to use is only located within the top level element where the context starts.

XML looks like:

<vacancies>
  <vacancy id="111427">
    <uri>https://data.ox.ac.uk/id/vacancy/111427</uri>
    <url>https://data.ox.ac.uk/doc/vacancy/111427</url>
    <webpage>https://www.recruit.ox.ac.uk/pls/hrisliverecruit...</webpage>
    <label>Postdoctoral Scientist - Protein Biochemistry</label>
    <opens>2014-01-16T09:08:14+00:00</opens>
    <closes>2014-02-17T12:00:00+00:00</closes>
    ...

My context is
    /vacancies/vacancy
and I am mapping my guid to @id which I think is the correct syntax.

The import doesn't work correctly, I get no nodes and no errors. What am I doing wrong (if anything)? There is nothing I can do about the XML schema incidentally, if that is where the problem is.

I just did a quick test of this, with your sample data, and it works correctly.

In the debug options you can enable error reporting, as well as, show the outputs of various queries.


Drupal 7 EVA fields not rendered on unpublished nodes In a node type with 3 EVA fields, if I unpublish the node, the node view tab shows only the pink watermark "Unpublished" and the EVA fields are not rendered at all. The EVA related view does not have any publish filter nor any permission that prevents unpublished content to be rendered. All modules are updated to latest stable version. Any idea?

Solved using the View Unpublished module. This is not related to EVA module but it is related to the drupal unpublished nodes built in user permissions


Where and how should I use Composer and the drupal-composer/drupal-project scaffold to install the required libraries? I installed Drupal 8 using the drupal-composer/drupal-project scaffold. I also installed the Devel module, and enabled its Webprofiler submodule.

Drupal status reports that Webprofiler needs:

D3.js library
highlight.js library

There's no libraries path in my Drupal installation.

As I'm using composer, both D3 and highlight have packages.

https://packagist.org/packages/mbostock/d3
https://packagist.org/packages/components/highlightjs

That's a preferred option.

Where do the libraries need to actually go when using this scaffold?  What path?

How do I correctly use Composer on this install to put them there?

Although Where should I download libraries for modules through composer? talks about it, it's only for the case of Composer Manager, which I am NOT using.

I use https://github.com/oomphinc/composer-installers-extender in my projects. It provides an composer installer for any package type.


How could I check that the field's value has indeed been modified? Is there a hook which could be used to execute code when a specific field of a custom content type is updated? Is there a specific hook, or should I use hook_node_presave()? In that case, how could I check that the field's value has indeed been modified?

Using hook_entity_presave():

  You can get the original entity object from $entity->original when it is an update of the entity.

So something like this ought to work:

function foo_node_presave(\Drupal\node\NodeInterface $node) {
  if (!$node->isNew() && $node->get('field_bar')->getValue() != $node->original->get('field_bar')->getValue()) {
    // ...
  }
}


Show custom content in Main Page Summary I have a site using Ubercart that shows product summaries on the main page (I believe these are called teasers).  Each product has a voting widget provided by Vote Up/Down on its actual node/page.  I've copied page.tpl.php to page-front.tpl.php because I want to add a small block or box that shows the number of upvotes on the main page (but not actually allow voting here) and finally sort these teasers by popularity (number of votes).

I can see that print $content is outputting this page's content but I am not sure where this is being generated so I can either hook into it or modify directly.  I've coded themes and plugins in Wordpress but I don't know Drupal well enough yet.

Thanks in advance.

You can find node.tpl.php inside your sites/all/themes/yourtheme folder. $content is generated in that file.


How to get bundle in form alter? I want bundle in hook_form_alter. In Drupal7 we can get all these in hook_form_alter.

I tried like this in D7:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $bundle_type = $form['#bundle'];
}

Here I am getting bundle in D7.
Whereas in D8 I am not getting any bundle like article/page/tags etc.,

This is the final solution:

use Drupal\Core\Entity\ContentEntityForm;

$bundle = FALSE;
$form_object = $form_state->getFormObject();
if ($form_object instanceof ContentEntityForm) {
  $bundle = $form_object->getEntity()->bundle();
}


Add view with contextual filter to XML sitemap I setup a view with the following path www.example.com/profile/% (the user contextual filter i added is the username of the). These displays the profile of each user.

Please is there a way to add the view to the XML sitemap?

There is an XML Sitemap Custom submodule in the XML Sitemap module

You can use this to set Page Views' paths for inclusion in the XML Sitemap

You might also check this module out: https://www.drupal.org/project/xmlsitemap_aliases
From the project page:
"Anything with a path in the aliases table can now be included in your XMLsitemap by the click of a button! (This is particularly useful when you have too many to enter manually as custom links, for example: views with arguments!)"


Keep only the last revision of content with multi-version module We are using Drupal 8 with the multi-version module version 1.0.0-alpha12.

As part of our dev/test workflow, we SQL dump the production database and move it into dev and test environments. Recently this process has been becoming increasingly slow and after some investigation into the composition of the database, I notice we have ~8G of data in the node_revision__body table.

I would therefore like to prune content in the database to keep only the most recent revision when we are working in our dev and test environments.

How can I achieve this with Drupal 8 and the multi-version module? I have come across the Node Revision Delete module, but that has a version for Drupal 7.

Actually, now (March 30 2018) it has a 8.x version. So this is your module:

Node Revision Delete

  The Node Revision Delete module lets you to track and prune old
  revisions of content types.

  Features:

  Define the max amount of revisions to keep per content type.
  Run on Drush, cron run or on a different period (daily, weekly, etc).


jQuery not working in zen theme Ive put this code before the closing head tag in my html.tpl.php but nothing is happening. Im using the zen theme. Ive tried clearing my cache.

Im I somehow missing a syntax error or is this a Zen/ Drupal qwerk?

<script>
    $(document).ready(function() {
        alert('hi');
    });
</script>

</head>

It would be helpful to know what version of drupal you are using.

Modifying html.tpl.php to add Javascript like this is really a bad choice as it is a very brittle way of coding something.

Jquery in Drupal 7 is loaded using the noConflict mechanism. This avoids javascript namespace collisions:

  Many JavaScript libraries use $ as a function or variable name, just
  as jQuery does. In jQuery's case, $ is just an alias for jQuery, so
  all functionality is available without using $. If we need to use
  another JavaScript library alongside jQuery, we can return control of
  $ back to the other library with a call to $.noConflict():

If you wanted to use code like you've written you would write:

You're better off adding a scripts[] entry into your theme_name.info file and placing such code in its own javascript file in your theme directory. Drupal will load it into the HTML  for you and aggregate your javascript files for you if you have aggregation turned on.

# In YOURTHEME.info
scripts[]= js/example.js

/* Example /sites/all/themes/YOURTHEME/js/example.js */
jQuery(document).ready(function($) {
  $('nav ul.primary-menu').append('

');
});


Webform entity select submission displaying different result than element I have a webform in Drupal 8 with an entity select element. The element is populated from an entity reference view. I have a book content type with information about the book such as title and author. I also have a field collection in book containing more specific details such as ISBN and format. The entity reference view displays title-isbn-format. For example:

Dune - 9780441013593 - Paperback

Dune - 9780143111580 - Hardcover

I applied the view entity reference patch posted here. The form correctly displays the output of the view. How do I get the same display in the form submission? If I set the form display to value and select Dune paperback the result is "MyBookFieldCollection 0 of Dune (9)."

I tried using tokens but I can only get the field collection info, not the book info.

Here is the source for the element:

book_title:
  '#type': entity_select
  '#title': 'Book Title'
  '#select2': true
  '#format': custom
  '#format_html': '[webform_submission:values:book_title:node:title] - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#format_text': '[webform_submission:values:book_title:node:title] - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#target_type': field_collection_item
  '#selection_handler': views
  '#selection_settings':
    view:
      view_name: entity_reference_for_form
      display_name: entity_reference_1
      arguments: {  }

This correctly displays the ISBN and book format but not the book title.

I was able to get the desired result for the book title by using twig and string manipulation.

I noticed {{ item.label }} returns MyBookFieldCollection 0 of Dune. MyBookFieldCollection is the name of the field collection and 0 represents the selected item. There will not be more than five items in a given collection. I can remove the start of the string using {{ item.label[27:] }} and this returns a value of Dune.

Here is the modified element source:

book_title:
  '#type': entity_select
  '#title': 'Book Title'
  '#select2': true
  '#format': custom
  '#format_html': '{{ item.label[27:] }} - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#format_text': '{{ item.label[27:] }} - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#target_type': field_collection_item
  '#selection_handler': views
  '#selection_settings':
    view:
      view_name: entity_reference_for_form
      display_name: entity_reference_1
      arguments: {  }

This outputs Dune - 9780441013593 - Paperback in the form submission.


Get value from twig tweak without additional markup I am using the following code to set a variable "tab1visibility" from the twig tweak value for field_hidden based on a block id.  {% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

This works perfectly but returns the value with the expected markup.

When I try to use |striptags on this newly created value it returns nothing.

So

{% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

{{tab1visibility}}

returns true or false wrapped in my typical field div templating.

{% set tab1visibility =  drupal_field('field_hidden', 'block_content', 7)  %}

{{tab1visibility|striptags}}

returns nothing no markup or the raw value.

How do I get just the value without the surrounding markup?

A field formatter stores the field object inside of the render array for reference later, so that you can still access the raw values:

{% set field = drupal_field('field_example', 'block_content', 1) %}
{% set value = field['#items'].0.value %}
{{ value }}

This is the same for all field formatters.

Your approach might also work, if you |render the field first and then apply |striptags:

{{ tab1visibility|render|striptags }}

But not in a consistent way, because it depends on the specific field type and the configured field formatter.


How to add multiple fields Let's say, I have a text field which I use it as a phone number field. I set the number of values to unlimited, so people can enter more than one number.

However, I want to use another text field for the definition of that number. Such as:

Name    Number
====    ======
Home    123456
OFfice  234567
Mobile  456789

How can I combine these two fields and require the Name field to be filled when each time a number field is created?

the easiest way is field_collection:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

You can make a compound field in code as this Phase2 Blog Post describes .... maybe there's a module for a compound field, but its usually not worth the effort.


Why do all product display nodes with same referenced product (SKU) appear in 1 order view Each time an order is added to cart, the admin/commerce/orders/11/view, for example, shows all product display nodes ever created on the site for that SKU.

I suspect that this is not the normal behaviour I should see because if it were, over time, these order views on the administrative pages would grow endlessly long.

However, the Cart Form shows only 1 item and that appears to be correct. I suspect there is something incorrect with my Line Items view.  admin/structure/views/view/commerce_line_item_table/edit/default?destination=admin/commerce/orders/11/view

Please see my attached images.

It's a result of your relationships: you're connecting each order item to the product it represents and then each product to each node that references it. Because of the way that database query works, it returns a unique result for every combination and renders them into your View.

Judging by your View's configuration, this was the simplest way for it to include the course type, teacher, etc. fields from the node. You're going to have to filter the result set somehow ... unfortunately, the data you need to be able to do that (the add to cart context from the $line_item->data array) isn't exposed to Views.

To see how that array gets built, check out commerce_cart_field_attach_view_alter(). You have two basic options for that data: create a custom Views filter that will allow you to filter the result set of your Views based on the values in the $line_item->data['context']['entity'] array or else remove the relationship from the View and switch to rendering the line item using a custom view mode, loading the data you need from the related entities manually.

(Note: I was going to suggest that if you only have one active node selling each product at any given point in time (unclear from your question), you could just add a filter to your View that checks to ensure the node referencing the product is published. That would get rid of the duplication but screw up your historical orders who now appear to show the wrong content.)


Hierarchical Select with taxonomy in Views I have a generic content which can be differencied by a taxonomy term. Then i've created to views filtered by a taxonomy. I want to enable a second filter, exposed  , based on the taxonomy, depending on the first filter also bases on the taxonomy but not exposed.

For example:
I have the following taxonomy:
Type :

News

First
Second

Publication

Third
Fourth

My content is 'Article' and the Type is 'News > First'
In my View 'News', I can only see the content News ( First or Second), this part is easy. What I need is an exposed filter where i can only choose First or Second from News depending on the fact that I'v already done a previous filter based on the first level of this taxonomy.

How can I do that?

Thanks

You can achieve this by combining Simple Hierarchal Select and Views Dependent Filters. So you use SHS for selecting the taxonomy term, and then set a dependency that if a term is selected on the first taxonomy, show the second taxonomy.

Add your first/primary taxonomy that you will be using to determine the secondary options. Don't select any terms, expose filter.
Add your secondary taxonomy, expose filter.
Add a Global: Dependent Filter to your list of filters.
Your Controller Filter is the first taxonomy that will be deciding which second field/taxonomy will showing up.
The Controller Values are the values from the taxonomy selected for the Controller Filter. Pick the term which when selected will show the dependent taxonomy. The dependent filter is the secondary taxonomy that you want to show up.

There does need to be some specific ordering going on, like the dependent taxonomy needs to be above the Dependent Filter, but I can't remember exactly. I'm sure you can figure it out from there.


How to configure view filter to search on the basis of two conditions I have created a view for users which is having filters: Username,Email,Company and Country. I am also using views bulk operation with these filters.

I can search any record on the basis of above fields but the problem is to search the record on two conditions.

For Example: I want to search on the basis of email: I want the record of those users whose accounts are neither in gmail nor in yahoo.

You can add filters twice.  So, to avoid getting gmail or yahoo, you can first add a NOT gmail e-mail filter, and then add a second NOT yahoo filter.

This is not a great way to do it if you have an extremely large number of requirements, but if you only have a few, then it should be fine.


How to show available drush commands per module with a drush command? For example I would like to see all the commands provided by the features module, I know I can do

drush help | grep features

But I don't feel safe doing this with all modules present there (you never know when you miss a command). And it often looses important "second lines" such as the shortcut for features-revert-all.
Do you know any command / technique to make sure you get it all safely?

You can use the --filter feature of Drush. For example, you can use drush --filter=features to get all the commands available from the Features module, or drush --filter=views to get all the Drush commands available from the Views module.

You could then also pipe that output into a file if you wanted (e.g. drush --filter=views > views_drush_commands.txt).

You can find the docs on the Drush homepage.


Best way to set up data architecture I have a system where (to start) I have three types of data I need to store. I'm familiar with relational databases so I'm going to describe it in those terms. The Author table just has a couple columns like a primary key, and a few text fields (it's info about an author). Location has a similar structure to Author, but it's for different data (info about locations). Article is basically what links the two together. It has some regular text data, but also has foreign keys to both Author and Location (it's an Article written by Author about Location).

I've played with two ideas for how to represent this in Drupal. First with the Field API creating content types. The main problem here is that I'm not sure how to set it up so that Article has the proper relations to Author and Location.

The second approach I'm considering is using the Entity API module, but I'm not really very familiar with the module. However, I am very comfortable using hook_schema() to set up the tables and relationships. From there, I'm not sure if Entity API has much useful in the way of making the data manageable like a content type or if I'd have to write that all by hand to begin with.

Am I looking at this all wrong? What is the drupal way?

There are quite a few possibilities to deal with this.

To get an overview:

The advantage of custom entities is that they don't come with all the overhead that nodes have. They're especially well suited for storing and managing completely custom data that you might not even want to display and you have full control over them (their data structure, workflows, UI). The commerce project for example defines own entities for orders, products, line items and so on.
Nodes are still the main content pieces. They provide various features that you don't yet get for free with custom entities, like revisioning and comments. Various additional modules focus on nodes. In short, you get a ton of features, but have to live with the overhead that comes with them. Every additional data structure you need is a field, living in it's own table, and so on.
Entity API provides a lot of features for custom entities, for example CRUD and allows you to easily integrate with various important tools like Views and Rules. It's definitely worth to rely on it, see http://www.trellon.com/content/blog/creating-own-entities-entity-api for a nice introduction.
To connect entities (Hint: nodes are entities as well), you can for example use  Entity reference (simple, directed relationship) or Relation (flexible, unidirectional relation between entities which is an fieldable entity on it's own).

Some specific tips based on that:

Article sounds like a perfect use case to use nodes/a content type to me. People need an UI to create them, you might need revisions, maybe comments, they need to be displayed, probably want nice aliases (Pathauto) for them and so on.
Author; Here you have a bunch of options. Nodes have an author by default, the user that created them. Users can have fields as well and can have a public profile, so your authors could actually be users. Especially if your authors are going to be the uses which will create the articles on your site themself. If not, then this might not be a perfect match because changing the author of a node requires administrative permissions. If not, you could either use another content type if you think that makes sense or create a custom entity.
Location: The traditional answer are certainly taxonomies. They're still a good match to categorize content, provide a number of possibly useful features out of the box, like hierarchy (so you could do do Country > State > City), auto-create new locations from a autocomplete widget and a list of nodes attached to them. And, they're fieldable entities too (surprise!), so you can store additional information for them as well.

So, to me it sounds like the default entities provided by Drupal core are a pretty good match for your data.


How to use the Rules module to implement a custom redirect for an outdated URL? I used to show content from a catalog via the Views module, accessing an external database, so that all of the URLs would be something like /content?name=[name].

For various reasons, I've opted to import the content directly into Drupal as a unique content type. So now my URLs are /content/[name].

I need to implement a 301 redirect so that people going to the first URL (due to old bookmarks, links, etc.) are taken to the new URL.

Is it possible to set up a rule for the content type to accomplish this? The [name] field is the same so I feel like it should be a fairly straightforward thing to set up.

I did some searching around, and came up with RewriteRule ^/?content/([^/d]+)/?$ content?name=$1 [L,QSA]. I tried putting that in the .htaccess file after RewriteEngine on, and that didn't work. Am I following the proper .htaccess convention? I tried RewriteRule ^(.*)/content?name=(.*)$ $1/content/$2 [R,L] too, but it didn't work.

Why using .htaccess might not be an option

There are situations where setting up a redirect in your .htaccess file may not be an option, such as:

you are not allowed (= do not "have") edit access to your .htaccess file.
your provider does not allow specific directives in .htaccess files (which you'd want to use).
your Drupal site is running on IIS.
you don't have the required knowledge to correctly code the redirect in your .htaccess.
... (what else?).

These are all reasons for using an approach based on the Rules module, as further detailed below.

Use Rules with 'Drupal is initializing'

Using the Rules module to get this to work, you should be able to use the "Drupal is initializing" event. That will ensure that the rule gets triggered BEFORE the actual content is shown.

Use a Regular Expression

The link that you want to "intercept", should be formatted in some type of regular expression, which you then use as your rules "Condition". so that you have a rule that corresponds to "before showing the actual content of something that matches a specific path ...". After you get that part to work, your Rules "action" should specify the actual redirect to be performed.

Remark: in this case you can also use "contains /content?name=" (instead of the regular expression) to get the text match working.

Sample rule

Refer to the "option 1" part of my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains this rule in export format:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Here are some suggested tunings of the above sample, to make it work for your case also:

machine name and label.
replace the node/* by your path (in the "label", and the regular expression).
replace the path in the action part of the rule by your target path (more details below), and check if you do want some type of error message to be shown (if not remove that part of the action).

Use the value of the [name] variable in the redirect

To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

PS: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.


Drupal Google Translate Module - Must be represented in the url I have a Wordpress site which I'm planning on porting to Drupal to leverage more advanced functionality.

One plugin I use on the Wordpress site is for Google Translate. Most Wordpress plugins don't represent the language in the url (i.e. they use AJAX or Google Translate direct). I use a decent one which specifies the country code in the URL, and that allows me to use http://petfoodratings.org/ko/, or http://www.petfoodratings.org/de/.

Before undertaking a port to Drupal I want to know if any of the Google Translate Drupal modules do this in the same way?

The only module I know of with a Drupal 7 version is GTranslate.

  GTranslate uses Google power to translate your web page. With 58 available languages your site will be available to more than 98% of internet users.

  Hides "Suggest better translation" pop-up
  Hides Google top frame after translation
  Mouse over effect
  Analytics feature
  Flags combined in one file to load faster
  Option to open translated page in new window
  Available styles Dropdown/Flags/flags with dropdown
  Valid XHTML
  Google Translate Element on your site (Google Default translation method)
  Ability to use SEF URLs and edit translations with Pro version

The module is used from 2250 sites, and 1216 of those are using Drupal 7.

As for the comment written by monymirza, The Google TOS once contained the following paragraph:

  5.3 You agree not to access (or attempt to access) any of the Services by any means other than through the interface that is provided by Google, unless you have been specifically allowed to do so in a separate agreement with Google. You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers) and shall ensure that you comply with the instructions set out in any robots.txt file present on the Services.

The actual version of the Google TOS says:

  Don't misuse our Services. For example, don't interfere with our Services or try to access them using a method other than the interface and the instructions that we provide. You may use our Services only as permitted by law, including applicable export and re-export control laws and regulations. We may suspend or stop providing our Services to you if you do not comply with our terms or policies or if we are investigating suspected misconduct.

I am not sure what they mean by interface. It could mean you can only access the service through the user interface provided by the browser.


How can I toggle required field? Using Drupal 7.

I'm trying to toggle required field based on the click of a radio button.

I already tried the proposed solution in this post but it did not work.

Here is my code:

        $(context).find('.field-name-field-stop-displaying-after').hide();
        $(context).find('.field-name-field-stop-displaying-after').removeClass('required');
        $(context).find("input[name='field_status[und]']").click(function() {
          var radioSelect = $(this).val();
          if (radioSelect == 0) {
            $(context).find('.field-name-field-stop-displaying-after').hide();
            $(context).find('.field-name-field-stop-displaying-after').removeClass('required');
          } else {
            $(context).find('.field-name-field-stop-displaying-after').show();
            $(context).find('.field-name-field-stop-displaying-after').addClass('required');
          }
        });

Note that the hide/show toggle works properly.

For the required class, I am targeting the element that the system targets when I set it as required in configuration. The required class is toggled on the element, but does not actually toggle the requirement. In other words, if the field is hidden, it should not be required, but it remains required. The only difference I can see with the system setting is that it adds a legend element that describes the field as required.

What am I missing here? How can I toggle the requirement of the field?

In my case, I actually didn't need server-side validation; I just needed validation to serve as a reminder to fill out an exposed field. Instead, I added field-level validation with required.

$(context).find('.field-name-field-stop-displaying-after').hide();
$(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',false);
$(context).find("input[name='field_status[und]']").click(function() {
    var radioSelect = $(this).val();
    if (radioSelect == 0) {
        $(context).find('.field-name-field-stop-displaying-after').hide();
        $(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',false);
    } else {
        $(context).find('.field-name-field-stop-displaying-after').show();
        $(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',true);
    }
});


Search Drupal source/plaintext? I'm looking for a simple way to search thru the plaintext/source of hundreds of nodes. I need to find-replace all the color settings for a certain font awesome icon (fa-check), but can't find any good way to check our source for which pages are using that icon. New Drupal admin here, haven't really done any dev work, so answer that doesn't require installing new modules would be great.

We're using Solr for search, incidentally.

You want to use the Scanner module:

  Versions 5.x-2, 6.x, and 7.x of Search and Replace Scanner can do
  plain text search-and-replace, or regular expression
  search-and-replace, against the title, body and text content fields on
  all nodes in your system. This is useful for finding html strings that
  Drupal's normal search will ignore. The module is very handy if you
  are fixing typos in a lot of content, changing the name of your
  company, or are changing the URL of a link included multiple times in
  multiple nodes, among other things.


Migrate Drupal locator content to Wordpress site I use the migrate module to populate locator data to other Drupal sites. We have a main site that allows members to update their locations. Each location can also be flagged so that if its checked as an "A" location, when Cron runs it populates on the "A" site and the same for the "B" site. This keeps the content updated on the other sites when any changes are made and allows us to only have to update on one site. All the sites are running on Drupal 7.

Now if we added a WordPress site and wanted to route the "A" locations content to that site instead, can this be done the same way?

Thanks!

also saw your email...

The migrate module is very Drupal-centric. It runs on a Drupal site, and the primary (99.99%) use-case is to pull data into that Drupal site - all destination plugins I know of write to the local Drupal database. That being said, it would be entirely possible to write a destination plugin that pushed to an external destination - like, say, a WordPress database or a web service for creating content.

Personally, my only experience with WordPress is in importing content from WordPress exports (XML files) into Drupal, so I don't know how challenging pushing content to WordPress would be.


db_update query does not work properly I work with views bulk operations and I wanna change status of selected items in a view. I applied db_update query, but something went wrong. I was debugging my code following:

  $status=$context['status'];

foreach($context['rows'] as $order) {

    db_update('orders')
        ->fields(array(
            'status' => $status
        ))
        ->condition('oid',$order->oid,'=')
        ->execute();
}

foreach($context['rows'] as $order) {
    $result = db_select('orders','status')
        ->fields('status')
        ->condition('oid',$order->oid)
        ->execute()
        ->fetchAssoc();
    if($result) {
        drupal_set_message($result['status']);
        drupal_set_message($result['oid']);
    }
}

So first is db_update and after that I did db_select and printed it out.The result of this db_select behaves like status would be updated. But in the node is status still the same. Also in database it stayed unchanged. I have no idea what's wrong. It behaves like it was updated and then immediately got back.I would be very helpful for any help. Sorry for my english. Thanks.

My first inclination is that this is a caching issue.

Other possibilities:

Is the node actually stored in the orders table?  Do you do the appropriate updates for the nodes table as well?
Is this in an incomplete transaction?  (db_transaction)
Have you checked the return value of the ->execute() to see if it is returning the right number of rows?

Without a full description of what the variable $context and the table orders contains, it is hard to give any better answers.


Taxonomy search block - Search for e.g. "mac" -> Go to URL /tags/mac I just want a simple "search" block for the tags taxonomy. It should work like I wrote in the title:

If you search for the tag "x", it should automatically go to the URL /tags/x.

I'm aware that it may result in "Page not found", but that's ok.

It's more like a "go to URL" block rather than a search.

You can use Custom Search module. This module allows you to manipulate search functionality.

It has sub module called custom search Taxonomy which allows you to search according to taxonomy terms.

This allows you to configure path also.

If you want to use custom search paths, enter them here in the form path|label,
one per line (if only one path is specified, the selector will be hidden).

The [key] token will be replaced by what is entered in the search box, and the [terms] token will be replaced by the selected taxonomy term id(s).

Ie: mysearch/[key]/[terms]|My custom search label.


How to access current menu level/depth when overriding THEMENAME_menu_tree__MENU($variables)? I'm creating a custom menu for a project built in Drupal 7 and I want to add some custom HTML before every UL in the main menu.

By adding the THEMENAME_menu_tree__main_menu($variables) function to my template.php I can output my custom HTML:

return '
My custom HTML

' . $variables['tree'] . '
';

The function is called for every level in the menu and the HTML printed in front of every UL. But now I also want to customize this HTML in different ways for each level, but I cannot find any information regarding the current menu level in the $variables parameter.

Is it at all possible to access information about current menu level in the body of the function? If so, how?

Looks like this question is way past its expiry date, but who knows this might help someone :)

I must confess, I have never used this hook function before (THEMENAME_menu_tree__main_menu).  I had a quick look by implementing it in my current project, and you are only getting back HTML.  I think you are going to have a tough time styling individual items in the HTML you are getting back.

In my current project I render my menu a region template file (region--header.tpl.php to be exact).  Obviously this means I have a 'header' region defined in my mytheme.info file.

So in page.tpl.php I have

<?php
  if (isset($page['header'])) {
    print render($page['header']);
  }
?>

which basically defers rendering to region--header.tpl.php In this file I:

$menu = menu_tree_all_data('main-menu');
foreach ($menu as $menuItem) {
  // Extract info I want and render
  // $markup = ......
}

$print $markup

Basically I build my own HTML that will render the menu.

I have a couple of 'utility functions' to get the data out of $menuItem - let me know if you are interested.

As a side note - if you just want to figure out what level you are on - you could always call menu_get_active_trail().  You should be able to figure out what 'level' you are on with the info in that array.

Hope this helps.


Submission hook: What am I doing wrong? EDIT: Still need some help with this. It seems the value of "$form_id" is nothing related to "webform_client...". When I echo the value of $form_id in the mywebform_extra_form_alter() function it outputs a value of: "search_form_block".. nothing indicating a webform.

Can I ask for some more assistance with this?

I've created a module for a webform submission hook to open and modify a CSV with the submitted values:

function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
    // Add validation for a particular Webform node:
    if ($form_id == 'webform_client_form_213') {
    // Add the submit handler after the existing Webform submit handler,
    // but before the second Webform handler. Pop off the first one and add
// ours second.
    $first = array_shift($form['#submit']);
    array_unshift($form['#submit'], $first, 'mywebform_extra_submit_213');
  }
}

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

    global $user;

    // Changes can be made to the Webform node settings by modifying this variable:
    $form['#node']->webform;

    $name = $form_state['values']['your_name'];
    $email = $form_state['values']['your_e_mail_address'];
    $zip_code = $form_state['values']['zip_code'];
    $date = date('m/d/Y');

    $handle = fopen("pledge_submissions.csv", "a");
    $line = array($name,$email,$zip_code,$date);
    fputcsv($handle, $line);
    fclose($handle);

}

It seems these functions are firing but when I open the CSV, no data has been added.

Is $form_state['values']['field_name_here'] the correct way to target the webform field values? When I try to alert things inside that function the form errors out after submission.

Two things:

Check your argument to fopen for validity, and two, the $form_state in Webform is missing a key. Example:

  $data = array(
    'full_name' => $form_state['values']['submitted']['full_name'],
    'company' => $form_state['values']['submitted']['company'],
    'phone' => $form_state['values']['submitted']['phone'],
    'email_address' => $form_state['values']['submitted']['email_address'],
    'areas_of_interest' => array(),
    'comments' => $form_state['values']['submitted']['comments'],
  );

You are missing ['submitted'].


How to theme maintenance page for omega subtheme? Drupal's "Theming the Drupal maintenance page" gives a good overview for theming the maintenance page for 'normal' themes:

Copy modules/system/maintenance-page.tpl.php to your theme's templates directory
In the settings.php file, enable the $conf['maintenance_theme'] variable
Copy you page.tpl.php contents into maintenance-page.tpl.php and edit as necessary

But my site uses an Omega subtheme, so I don't have a page.tpl.php (well, it's not quite the same as these instructions are anticipating).  I'm a little lost among all the omega templates & regions.

How do I theme my omega subtheme's maintence page to look like the rest of my site?

There's always a parent template, even if you don't see it in your base_theme.

The inheritance will go:

omega_subtheme template of NAME
then omega template of NAME
then drupal core template of name

So you'll need to copy the drupal core templates. They can be found in

DRUPALROOT/modules/system

You can find page.tpl, maintenance-page.tpl.php and all the base templates.


How do I write a behat test to go to user/UID/somewhere when I only know the username? I'm trying to write Behat tests to verify my Drupal Commerce store.
My test creates some users, so I know the usernames but not the UIDs (the UIDs are assigned by Drupal in the test, so they will be different each time).
So, I want to get the UID based on the username, and then redirect to the payment method page for that user with a step like When I go to the payment method page for username ABC.
Here's my code:
  /**
   * @Then I go to the payment method page for username :username
   */
  public function iGoToThePaymentMethodPageForUsername($username) {
    $user_object = $this->userManager->getUser($username);
    $uid = $user_object->id;
    if (!(is_int($uid))) {
      throw new Exception("UID is not a number ('$uid')");
    }
    $this->visitPath("user/$uid/payment-methods");
  }

However, this code fails with the following error message:
  No user with ABC name is registered with the driver.

When I checked this->userManager->getUsers(), I found that it only has the users generated by the Drupal extension in the current scenario; I cannot access the users who have been registered in other scenarios or users who have already registered outside of Behat.
What's the correct way to get the user object for such a user?

You could use Sub-pathauto which will allow you to use /user/username/somewhere instead.


When theming a view there are two approaches, in a template file or rewriting field output, what are the advantages and disadvantages of each? When configuring a field in a view such as the node title, there are options to add or remove formatting to the view by either excluding the field from view, wrapping the field in a certain type of tag such as div, span or h3 or rewriting the output of the field which in conjunction with replacement tokens can yield quite complex structures.

The default views row template, for example, just loops through each field and prints it to the template. However, it is possible to print each field's variable in a particular place by rewriting the template. The templates are good because logic can be added to the template, for example, testing for number of comments to determine the plurality of the word comment that is prefixing the number of comments. The template is also useful for using the drupal_add_js() function to add javascript files that are only loaded even when the Drupal javascript caching is enabled during that particular page load.

There is third place to add logic to theming a view which is in the hook_views_pre_render() function.

With the several different ways to control the markup and output logic of a view are there  best practice? Are there different techniques that are appropriate for different situations?

You would want to use a template suggestion as they are called for small modifications to the design or DOM output adjustments.  You will use this %90 of the time.

rewriting field output should be handled by hooks EXAMPLE: if you are taking a value and turning it into an image for rating display....

Use pre-processing hooks when you are applying logic to output values.
Use theme suggestions when making adjustments to layout structure.


Filter by end date if it exists, if not then filter by start date I have a view of events, which has a start date and an end date (2 separate fields as the end date was added later). The end date is optional. I want to show events that are either in the future or are currently ongoing. So somehow I need to check if the node has an end date - and if so apply the filter on that, but if not then use the start date instead.

Is there any way to achieve this? Maybe I'm looking at in the wrong way.

Either you make end date field mandatory or use hook_views_query_alter to get  ongoing  or future events.

If you go with field mandatory option, you simply need to add two view filters with OR condition.

Start date >= Today OR
End date >=Today


How to I place the create form for content type on a page that can save the user's id? I'm new to Drupal. I've created a content type and I've created a view (using the Views module) to display the data.

I can add data from Content > Add Content > Item, which gives you a Drupal admin form.

How do I place this form on a page that can save the user's id?

First, to get rid of the "modal window", go to admin/modules and disable the Overlay module.

Second, if you want your logged in users to be able to create articles:

Go to admin/people/permissions and scroll down to the Node section.
There you will find different options to grant them Create, Edit, Delete, etc. permissions. For example, you can check Article: Create new content under the Authenticated User column to allow them to add new items in the Article content type.

Now your logged-in users can go to node/add/article page to find the form.


entityfieldquery execution error I'm learning entityfieldquery api

I wrote a simple module

function demo_menu() {
  $items = array();
  $items['demo'] = array(
    'page callback' => 'demo_list',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function demo_list() {
  $query=  new EntityFieldQuery();

  $result = $query->entityCondition('entity_type ', 'node')
    ->execute();

  print_r($result);
}

I got this error

EntityFieldQueryException: For this query an entity type must be specified. in EntityFieldQuery->propertyQuery() (line 1195 of C:\openserver\domains\drupal7.localhost\includes\entity.inc).

I read many articles. This is the most simplest query but it is not working.

Just got the error. remove space from "entity_type "
from this line
$result = $query->entityCondition('entity_type ', 'node') ->execute();


How to load all information Currency properties by currency code? I used module Currency version 8.x-3.1 . I had currency Code so I looking up function to load all properties currency by currency code , What API or function do it ?

Thanks

As a currency is just an entity you can do the following:

$currency_code = 'AUD';
$entity_type_manager = \Drupal::service('entity_type.manager');
$currency = $entity_type_manager->getStorage('currency')->load($currency_code);
ksm($currency); //check out what's available

//eg get sign
$sign = $currency->get('sign');

Good Luck


add css class to row with specified field value in views I have a View, and when a certain field in the result has a specific value, I want to add a CSS class to that row.

How I can add css class to the matching row in views result in table result mode directly in views pages, without template files?

You can do this in views.
The class in views supports tokens. So if you use the value of a field [field_value] and put that in the class, then you can style it by using .field_value in your css.

This way every field will get a class, but only the ones you style in css will affect how they look.


How do I view the maintenance page without putting the site in maintenance mode? I've just been asked by the stakeholder of a site I'm working on how he can view the maintenance page of his site so he can test links on it without putting the site in maintenance mode.

I'm going to suggest that we do this in a lower environment, since the info is the same but is there any way to do this?

By default there is no route to access the maintenance page via url. You can create a menu item and the corresponding page callback in your module :

// Access maintenance page regardless of the maintenance mode.
$items['maintenance'] = array(
  'title' => 'Maintenance',
  'page callback' => 'yourmodule_maintenance_page',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK
);

yourmodule_maintenance_page () {
  // Just use the internal status code to make Drupal load the apropriate theme and template.
  return MENU_SITE_OFFLINE;
}

And that's all, go to /maintenance to see the page.

You may also want to override the 'maintenance_page' theme, have a look at :

the base preprocess function in includes/theme.maintenance.inc
base template file in modules\system\maintenance-page.tpl.php


dynamically fill a field with the value of a field in another node referenced with an entity reference field Referencing entities is a great capability of Drupal but gives me headaches.

I have three content types: Client, Contact and Job ticket.

Clients are companies with whom I conduct business. Contacts are contact persons within these companies. The Contact content type has a reference field referencing their company's node. Job tickets are tickets for jobs these companies hire me to do for them. In this content type I have two reference fields: one for the Client and one for the Contact.

This is my problem: In the Job Ticket I have a select list field that needs to be populated with the address (or addresses, since there can be multiple values for the Address field in the Client content type) of the client when I select the client in the reference field select list. How can I do this automatically.

I tried the Field Reference module but I can't get it to work, and it would give me ALL the addresses from ALL the client nodes. I only need the one(s) from the previously selected client.

Thanks in advance.

You don't state much about your setup, so I am gonna presume you are using drupal 7. In that case I highly recommend using entityreferences. It replaces the former nodereference and userreference modules IMO. You can reference any entity with it. Also your custom CTs (Client, Contact, Job.)

When you create a reference field you have to option to use a 'simple' selection which indeed gives you ALL content of a certain type. But you can also choose to use a custom made view for the selection.

Using a contextual filter (which you can pass along in the entityreference field settings) you can filter the view down to exactly what you want.
It's brilliant, try it!


How to manage a views term filter at run-time? I have a D7 View for which i need to pass filters at runtime and cannot use exposed filters.
I use

$filter = $view_search_works->get_item($display_id, 'filter', 'filter_name_tid');
$filter['value'] = VALUE;
$view_search_works->set_item($display_id, 'filter', 'filter_name_tid', $filter);

for the filter i have defined for a taxonomy term.

If i define the filter with the "Is one of" and select all the taxonomy listed terms,when i pass one of the listed value, it runs fine.

The (big) problem is that if i define a new term (and it can happen) and pass it to the view, the term is not recognized and the view does not work.

Is there a way to say "all the taxonomy terms" for the filter? If i don't select a term when i define the filter, i get "No valid values found on filter:name".

Is it necessary to use a "Filter"? If you can use a "Contextual filter" instead, then this should work without you needing to specify which terms are allowed.

Another, much more complicated option, would be to implement hook_entity_insert and update the Views configuration on new terms.


How to clear already rendered "drupal messages" after successful ajax submit? Possible Duplicate:
  Remove tabledrag statuses on Ajax submit and display status message after Ajax submit

I have a custom form which saves "weights" of nodes to a custom table. The form has an Ajax submit handler. The form is rendered in a table using theme('table') and it has draggable handles added using drupal_add_dragtable.

Because the form gets submitted via Ajax, the messages such as "Changes made in this table will not be saved until the form is submitted" and any other messages in the "message region" don't get cleared even if the form is submitted and the values are saved.

How do I clear this message area? Or is there a way to hook into the "success" function of the Ajax? Or is it at all possible to run a custom javascript function after the form is submitted via Ajax? Any one of these possibilities will do for me. Please advise.

I've partially succeeded in solving this by returning an array of ajax commands from my callback function.

In particular I return the following commands:

$commands = array();
$commands[] = ajax_command_html('#page-banners-status', theme('status_messages'));
$commands[] = ajax_command_remove('.tabledrag-changed');
$commands[] = ajax_command_remove('.tabledrag-changed-warning');

but I've run into a new problem where now, even though the "Changes made in this table will not be saved until the form is submitted" message is removed after the save, it doesn't come back if the table is further modified after the save. I've tried to grab the form again and pass it back using an ajax command:

// my form function receives additional parameters
$form = drupal_get_form('my_custom_form', $path, $tid);
$commands[] = ajax_command_html('.table-container', drupal_render($form));

But whenever I call drupal_get_form from the callback function, it seems to break the function.

You can do it in two ways,

First One,

function hook_preprocess_page(&$vars) {
  //if(CHECK FOR THE FORM PAGE)
  $vars['show_messages'] = 0;
  $_SESSION['messages'] = '';
  // END IF
}

Second One is

at the end of the form submit callback write the code like below

unset($_SESSION['messages'])

or

$_SESSION['messages'] = '';