Can't login - no entry fields showing I have a local site which i'm working on. But somehow I got logged out and now when I want to login on localhost/user I have a login page without the login fields showing. So I can't login anymore. The weird thing is that I on the same page i can navigate to 'new account' or 'new password' and on those parts the entry fiels are showing, but at the login page they are not.
Somebody helpt get back into my site?

It's probably a layout/theming issue. See if you can find the fields with Chrome Inspector or Firebug.

If you can't, you can try this (very, very, very) dirty workaround:

Open to the /modules/system/system.module file in an editor and find the system_init() function.

Inside the function put:

global $user;
$user = user_load(1);

Every visitor will now be user 1.

Go to appearance and change your theme to Bartik.

Remove the 2 lines from the system_init().

DO NOT EVER DO THIS ONLINE! :)


How do I use page_callback or pageshow to display an existing article, view, page, block, or a slide show? can someone give me these examples to show an article or a block, page that already existing in a drupal website using pageshow or page_callback?

I currently can only successfully showing a link of the article, and then it lead me to the node. Here is my custom js code:

/**
 * Implements hook_menu()
 */
function intro_menu() {
  var items = {};
  items['intro'] = {
    title:'Introduction',
    page_callback: 'intro_page',
    pageshow: 'intro_page_pageshow'
  };
  return items;
}

function intro_page() {

 try{
  var content = {};
  content['my_stuff'] = {
    //markup: '
Nice stuff!
'
    theme: 'link',
    text: 'SlideShow',
    path: 'node/12'
  };
  return content;
 }
 catch (error) { console.log('intro_page - ' + error); }
}

function intro_page_pageshow() {
 // drupalgap_alert('My pageshow event has been called!');
}

After some trying, I can now do it with the following code:

    //page_callback
function intro_page() {
  return '

';
}

function intro_page_pageshow() {
 // drupalgap_alert('My pageshow event has been called!');
 try{
        var nid = 3;
        node_load(nid, {
        success:function(node){
         var content = node.content;
         $('#' + 'my_node_' + nid).html(content).trigger('create');
          }
        });
  }
  catch (error) { console.log('intro_page_pageshow - ' + error); }
}

But it's just the content, not the whole node.

I am still trying to display a page of slide show... The problem is I cannot find the node id from a "page". I tried the "path", but it does not work.

If you want your app's front page to show a node, then you can just set the front page to that node, in settings.js:

drupalgap.settings.front = 'node/12';

Under the hood DrupalGap already has a page_callback (and pageshow) that can load and render all core entity types. As you noticed with nodes, you simply linke to node/[nid] to view a node.

As for blocks, DrupalGap does not interface with blocks stored in Drupal, instead DrupalGap can create its own blocks for display in the app: http://docs.drupalgap.org/7/Blocks


How to programmatically add image from external URL using media module? I want to programmatically add an image from an external URL and have the module store and display a local copy of the image. How can I do that? Normally, I would click the "select media" button while creating a new node but I want to do it through code.

Make sure your php.ini allows allow_url_fopen. Then you can use something like this in your module:

$image = file_get_contents('http://drupal.org/files/issues/druplicon_2.png'); // string
$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_REPLACE);

Use php's file_get_contents() function

http://www.php.net/manual/en/function.file-get-contents.php

and then use Drupal API's file_save_data()

http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_data/7

Then you should be able to call it using and save it to a node etc ..

$node = new stdClass;
$node->type = 'node_type';
node_object_prepare($node);
$node->field_image[LANGUAGE_NONE]['0']['fid'] = $file->fid;
node_save($node);

Edit:

As pointed out in the comments, you can use function system_retrieve_file
See: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_retrieve_file/7


How do I place thumbnails from videos in a views slideshow? If the user doesn't give a thumbnail for the video in the slide show, I would like to generate a thumbnail from the video. I looked through questions and couldn't quite find what I was looking for. I am using Drupal 7. I am using the views slideshow module.

I found out that a few boxes were unchecked that I didn't know about.  This link shows a good tutorial on this: http://webwash.net/tutorials/display-video-thumbnails-media-module


Cannot run composer update after going from 8.3 to 8.5 Upon trying to run composer update drupal/core --with-dependencies, I get this error:

➜  docroot git:(core-upgrade) ✗ composer update --with-dependencies
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested PHP extension ext-gd * is missing from your system. Install or enable PHP's gd extension.

I've never had this error before, why is ext-gd required at all?

Edit:

I am currently doing this:

phpbrew install 7.1.15 +default+iconv+gd

php -m did not show gd as an installed extension. I've been fine for months until now, so, I am not sure if there was some change between 8.3 to 8.5 or possibly Symfony packages that suddenly requires this.

Edit 2:

This looks like it is also related to updating Homebrew/Xcode, as I had to take these additional steps in order to build a new version of PHP:

https://github.com/Homebrew/homebrew-php/issues/4590#issuecomment-346977512

Still does not explain why I suddenly need the gd extension to install or update a module with Composer for Drupal.

As of 8.5 core now explicitly requires several PHP extensions in composer.json, including gd:

...
"require": {
  "ext-date": "*",
  "ext-dom": "*",
  "ext-filter": "*",
  "ext-gd": "*",
  ...

The requirements match the required extension list in system_requirements, which would theoretically have to have been met for the original installation, and they were the same all the way back to 8.0.x, so it seems likely you did have gd installed when Drupal was installed.

Without gd installed you should also see an error message in the status report telling you it's missing; if you don't see that error, perhaps you have a different php.ini for FPM and CLI, and gd is only enabled for FPM, so it works in web but not the command line.

The relevant issue on drupal.org is here for reference.


How do I output XML schema? I have set the REST server with the Services module.

Also I've installed the Services Views module, created a new view that outputs the desired fields into XML.

That's working fine.

How can I add XML schema to that output, so the XML will look like:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
.....

You'll need to hook into the rest server module's formatters. This is untested but I think it'll work:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['xml']['formatter class'] = 'MyServicesXMLFormatter';
}

...

class MyServicesXMLFormatter extends ServicesXMLFormatter {

  public function render($data) {
    // This is the default code from ServicesXMLFormatter::render(),
    // manipulate this to add your schema and return the saved doc as normal
    $doc = new DOMDocument('1.0', 'utf-8');
    $root = $doc->createElement('result');
    $doc->appendChild($root);
    $this->xml_recursive($doc, $root, $data);
    return $doc->saveXML();
  }

}


How can you load redirects for a node to delete them? (redirect api) I'm trying to create a module which creates a redirect when a node is unpublished and removes it if the node is published again.

The redirect module API, has functions for doing both redirect_save and redirect_delete.

However I can't work out how to load all the redirects for a specific node in order to delete them, I think you might be able to use redirect_load_by_source but I can't work out how to get it to function correctly.

Has anyone tackled this sort of problem before?


Error while creating a node with file attachment through custom PHP code I need to programmaticly create  a node in Drupal 7 i followed availible tutorials and came up with this code:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$md5 = md5(strtotime("now"));

$field_customer_name = 'NAthtn';
$field_customer_email = "something@gmail.com";
$field_downloads_count_left = '11';

$filename = 'file123.zip';
$filepath = 'sites/default/files/private/file123.zip';

// Create managed File object and associate with file field.
$file = new StdClass();
$file->uid = 1;
$file->uri = $filepath;
$file->filename = $filename;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;
$file = file_copy($file, 'public://', FILE_EXISTS_REPLACE);

$node = new stdClass();
$node->type = 'download';
node_object_prepare($node);

$node->title    = $md5;
$node->language = LANGUAGE_NONE;

$node->field_customer_name[$node->language][0]['value'] = $field_customer_name;
$node->field_customer_email[$node->language][0]['value'] = $field_customer_email;
$node->field_downloads_count_left[$node->language][0]['value'] = $field_downloads_count_left;
$node->field_file[$node->language][0]['value'] = (array)$file;

$path = $md5;
$node->path = array('alias' => $path);

node_save($node);

I am getting the following error in the log:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 51 [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 664 of /home/content/16/5470416/html/download/includes/file.inc).

replace

$node->field_file[$node->language][0]['value'] = (array)$file;

with

$node->field_file[$node->language][] = (array)$file;

Also, add $node->validated = TRUE; before node_save($node);


Parameter comment must be on the next line at position 1 I review my module code with http://pareview.sh and it returns an error:

Line #94 - ERROR | Parameter comment must be on the next line at position 1

/**
 * Fetch node object properties. //<---  THIS IS LINE #94
 *
 * @param object $node contains information about campaign.
 *
 * @return array
 *   Webform properties.
*/

http://pareview.sh/pareview/httpgitdrupalorgprojectbounceconvertgit

If I add the comment on next line, it says: it requires a blank newline after it.
How to fix this error?

As it clearly says Parameter comment must be on the next line at position 1...

Correct way of documenting your function is..

/**
 * Fetch node object properties.
 *
 * @param object $node
 *   contains information about campaign.
 *
 * @return array
 *   Webform properties.
 */

For more information on commenting standards check Drupal Coding Standards Documentation in D.O


Views exposed filter auto submit loses focus I have setup a view with ajax enabled. I have also added an exposed filter with autosubmit on so that as the user types in the text field the view will automatically update. The problem is that when the form autosubmits, the text box loses focus.

I have read that I need to separate the exposed form into a separate block, however this option is not available as my view is a block itself.

Any help would be appreciated, as it is a real pain having to keep clicking in the text box to keep typing.

Also a workaround for the core problem, but including this js in my theme solved this problem for me.


how to debug drupal_http_request I'm working on a module that takes a form submission and posts it to a rest api, using the webform validator module's hooks.  I'm trying to debug what's going wrong, and I have the following code, which correctly displays $data and $url but nothing for $result (I'm assuming it's null?).

I'm new to drupal and I wonder what I'm doing wrong, with the http_request that it comes back null, or what else I can do to debug.

      $options = array( data => $data,
                        method => 'POST');
      //verify $data
      $errors['item_2'] = $data;
      $errors['item_3'] = $url

      $result = drupal_http_request($url, $options);

      // display the returned JSON result as a form error
      $errors['item_1'] = json_decode($result);

drupal_http_request doesn't just return the response data, it returns an object.

Return value

object An object that can have one or more of the following components:

request: A string containing the request body that was sent.
code: An integer containing the response status code, or the error code if an error occurred.
protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
status_message: The status message from the response, if a response was received.
redirect_code: If redirected, an integer containing the initial response status code.
redirect_url: If redirected, a string containing the URL of the redirect target.
error: If an error occurred, the error message. Otherwise not set.
headers: An array containing the response headers as name/value pairs. HTTP header names are case-insensitive (RFC 2616, section 4.2), so for easy access the array keys are returned in lower case.
data: A string containing the response body that was received.

For example, you can check

// This is the actual response data.
drupal_set_message($result->data);
// if there's an error, it'll  be in here
drupal_set_message($result->error);

or, if using the devel module

dpm($result);

In your case, you might just need:

if (empty($result->error) {
  $errors['item_1'] = json_decode($result->data);
}else{
  // An error occurred, log, show msg etc...
}


Using Rules to send an email to all Simplenews subscribers On a Drupal 8 site I'm working on, we are using Simplenews to allow users to subscribe to a mailing list for blog posts. The client would like us to set up a rule to automatically send an email to everyone on this specific blog post subscriber list whenever a new blog post is published.

I have gotten to the point where Rules will send out an email to a specific email every time a new node of type Blog Post is published, but I can't figure out how to reference a specific list of Simplenews subscribers through Rules' data selector. Does anyone know how to create that? Or maybe a work around for this?

Assuming your question is about D7, and looking at the available integration of Simplenews with Rules, there is no out-of-the-box solution (at least not that I'm aware of). So as per your "... maybe a workaround for this?", below is a blueprint of how to get it to work anyhow ...

Create a custom rule in which you use Rules Event "A user has been subscribed", with a Rules Action to flag such user, using the Flag module, and by using a global flag. Label the flag something like "Subscribe to Blog posts Newsletter".
Create a similar custom rule in which you use Rules Event "A user has been unsubscribed", with a Rules Action to unflag such user (for the same flag as described above).
Use the Views module to create a list of all users flagged by the flag described above.
Use the Views Rules module to create an additional Views display in the view described above, of type "Rules".
Improve your existing rule by adding a Rules Action to load the list of all users included in the Rules display created as described above. That should be the list you're asking about in your "specific list of Simplenews subscribers".

True, 3 extra modules (Flag, Views and Views Rules) needed to get this to work. But zero custom code required ... (together with 2 extra rules, and a refinement of your existing rule).


Post or upload file to specific user I am new to Drupal, I wonder how can I post file(s) that should be viewable to specific user? for example upload a pdf invoice to a specified user? Thank you!

If you want to send private message with file, use Privatemsg module. It used to have issues with attachment privacy, but it is Closed (fixed) - should work for you.


What causes 'You are not authorized to access this page' during create/edit of any menu? I got a very odd error for "new" admin user on Drupal 7. There are a few admin users in this site but only the "new" one that is unable to create, edit or list links on any menu. The error message is like so:

  You are not authorized to access this page

But this new admin user has the same role as other admins.

Does anyone know what can causing this?

Make sure you flush caches and rebuild permissions (from status page) and run cron.
If these fail check if any custom module implements hook_node_access
A rogue Rule could also be the culprit


How to access twig object values? I have an object called 'attributes' available to me in a twig template. Given that the following:

{{ dump(attributes) }}
{{ dump(attributes.storage) }}
{{ dump(attributes.storage['data-quickedit-field-id']) }}

dumps this:

how do I access the value property:?

'paragraph/3/field_section_title/en/default'

I've tried the obvious:

{{ dump(attributes.storage['data-quickedit-field-id'].value) }}

The following methods are available to me:

You can pipe it to render:

{{ attributes.storage['data-quickedit-field-id']|render }}


how to hide view block when other view block not giving any search result? I have created a view(ABC) in which search criteria: "country type content" and other filter is "promoted to front page"."Promoted to front page" filtering content using cck boolen field(yes/no).

Another view(XYZ) has search criteria:  "country type content" only.

When  promoted to front page cck field is empty or null my first view(ABC) will hide
same as I want to hide second view(XYZ) If first view is hidden.

Both the views i placed at same region "Header".

How to hide (XYZ) view, if (ABC)view has no content or hidden?

For such cases, when visiblity of one view need to be dependent on another view, we may alter the view, or we can use hook_views_pre_render or hook_views_pre_render to control the view through custom code.

Here as you are using block, so you can also use block configuration "Show block on specific pages" instead of coding in some custom module.

Then you can select option "Pages on which this PHP code returns TRUE" there.

After doing so, you can use the following code in the textarea:

<?php

$view = "<Your dependee view's machine name on which other view is dependent>";

$display = "<Your dependee view's display ID>";

$all_row = views_get_view_result($view, $display);

if(count($all_row)>0) {
  return TRUE;
}
?>


Drupal's version of Wordpress' wp_insert_post()? I just started playing with Drupal and I'd like the user to be able to add a custom node(or content) outside the admin by providing a form and then add that to Drupal's database once submitted. How do I do this programmatically and securely? Wordpress has a wp_insert_post() function for this functionality, what's the Drupal version?

Are you sure you want to do it programmatically?
You can just create the Content Type and use Permissions to control which user's roles can add/edit/delete that type of content.


Rollback entire server but keep content Until recently I've only been doing mainly superficial support on a website.
But now the question has been asked to revert the server the website runs on, to a few months ago.
The website is Drupal, but runs in IIS with a Microsoft SQL database instead of MySQL.
Now, I've never done a backup/restore procedure from a website, nor do I know what the risks are or what needs to be done.
I was looking at https://www.drupal.org/node/22281, but I still don't feel wise/secure enough to know what I'll be doing.
The main problem for me is; I need to keep the content of the website as it is now, but I don't know for certain where this is located/stored. The database?
Changes in files haven't been done to the website as far as I'm aware, so I hope this won't amount to a problem.

Basically what I'm asking is; is there a way to be certain that a rollback of an entire server and then a restore of content wouldn't amount to any difficulties?

Any general (or specific) information would be much appreciated,
Thanks

You can find the database information in your settings.php file.

A simple export of that database should allow you to capture the site as it exists currently, then when you get the server reconfigured you can simply import the exported database.


How do I use the #autocomplete_route_name property? I created a custom form and I want add a "users" reference field.

I see here I must use the property autocomplete_route_name, but what value must I set?

$form['project']['users'] = array(
  '#type' => 'textfield',
  '#title' => t('choose users'),
  '#autocomplete_route_name' => 'user.autocomplete',
);

With the previous code, I get the following error:

  Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "user.autocomplete" does not exist." at /var/www/drupal8/core/lib/Drupal/Core/Routing/RouteProvider.php

What is the correct code I should use?

Users are entities so they're treated generically. The route is system.entity_autocomplete, with some parameters, but you don't need to get your hands that dirty. You can use the "entity autocomplete" form element type instead, which should be as simple as:

$form['project']['users'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => t('choose users'),
  '#target_type' => 'user',
);

It's derived from a TextField, so you can use all the usual properties. Examples do seem to be a little hard to find other than in the core files (it's early days), but you can see all the available properties the entity_complete adds in EntityAutocomplete::getInfo(), and how they're used within other methods of the class.


Link for switch language How do I make a link to switch the language, without using any modules? When users click on a language I want to switch language and redirect them to the same page not to front page.

I assume you are already using the Internationalization (i18n) module. i18n provides the Language Switcher block, which contains links to switch among all enabled languages. When the user chooses one of the links in it, he is redirected to the corresponding page rendered in the newly-selected language.

Note that the block is only shown if at least two languages are enabled and language negotiation is set to something other than None.


Add the date of the order after the ID how do I add the order date after the order ID ?

Here is the contents of my file "commerce_order--commerce_order--pdf.tpl.php" :

<?php

/**
 * @file
 * Template for invoiced orders.
 */

?>

<?php
//The code to get payment type

$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}
?>

    <img src="<?php print $content['invoice_logo']['#value']; ?>"/>

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

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

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

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

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

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

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

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

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

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

  <?php print("Mode de règlement : " .$payment_method); ?>

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

Well, since you already loaded the order, I guess you could do:

<div class="order-id">
  <?php print render($content['order_id']); ?>
  <?php print format_date($order->created, 'custom', 'd-m-Y'); ?>
</div>


Custom field displayed based on author node I have a website for ads. In addition the user will have opportunity to make his ad as a VIP ad.

When the user creates a new ad, down bellow will be displayed a field "Make your ad VIP" and after clicking on that button it will popup a description.
This field is created as custom field with Display suite, but I want to make visible only on node author.

The idea is only user that is author of the node can see that field "Make your ad VIP".

The module "Field permissions" cannot control this custom field.

EDIT:

The field name is "adding_make_vip", the custom module is "custom_alter" and this is the code that I've tried:

<?php

function custom_alter_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && $field['field_name'] == 'adding_make_vip') {

   // $entity will be the node,so check node author with current user.
   if($entity->uid == $user->uid) {
      return TRUE;
    }
   else {
    return FALSE;
    }
  }
}

Unfortunately it didn't hide the field for anonymous users and users that aren't authors of the node.

How about implementing hook_field_access() in your custom module.

This hook takes operation edit/view as parameters and returns access to the user for the operations.As a sample code

function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && $field['field_name'] == 'your_field_name') {

   // $entity will be the node,so check node author with current user.
   if($entity->uid == $user->uid) {
      return TRUE;
    }
   else {
    return FALSE;
    }
  }
}


How do I setup Drupal with EC2 scaling? I want to scale my Drupal site and I was wondering how to approach it with Drupal and Amazon EC2. This is a bit related to How to use Drupal in the cloud with on demand instances.

With Amazon, I can monitor my server and if certain metrics are hit then it can launch a new instance that is load-balanced. My questions are then:

Does Drupal create specific files as users do stuff? Is everything on the database? (I have a separate database server that all my nodes point to.)
Are sessions local or is it on the database as well? I'm thinking of situations where user connects to server A and then gets moved to server B. Would the user lose anything?

If it helps, I'm using Drupal 6.

Drupal core code creates files only when a user uploads a file. With third-party modules, files could be created in other cases. For example, if you are using Apache Solr Search Integration some files could be created; if you are using a module that implements an alternative caching system, some files could be created as well.
sess_write() saves the session ID in the "{sessions}" table, together the value of $user->cache, the IP address used by the user to connect, and the current timestamp.

db_query("UPDATE {sessions} SET uid = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '%s'", $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time(), $key);
if (db_affected_rows()) {
  // Last access time is updated no more frequently than once every 180 seconds.
  // This reduces contention in the users table.
  if ($user->uid && time() - $user->access > variable_get('session_write_interval', 180)) {
    db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid);
  }
}


Redirection after certain node type creating So far i have this code in mymodule.module:

function mymodule_form_alter(&$form, $form_state, $form_id) {
    //drupal_set_message($form_id);
    switch ($form_id) {

        case 'anons_node_form':
          //dpm($form);
          $form['#submit'][] = 'sex_custom_submit';

          break;
    }
}

//Custom submit handler
function sex_custom_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form_state['redirect'] = '/video';
}

In a short i want this thing - when a user creates a node type 'anons' after succesfull creation of that node -> user should be redirected to a /video page. Code above doesn't works for me.. What i am doing wrong?

Try putting your destination as GET destination parameter, i:e $_GET['destination']. The GET destination parameter gets the highest preference


When managing fields for a content type, fields of type "list (integer)" can't be shared? In the drop-down for "add existing field" not all fields are available for reuse. Specifically I would like to reuse a field of type "list (integer)" because I will be adding 300 of them to my content type with exactly the same settings (just different labels and machine names). Doing  the manually is going to take me over eight hours since it takes about 1.5 min to add a field and configure it's settings. Is it possible to reuse fields of type "list (integer)"?

Thanks!!

ps: if you are unsure what I mean by reusing a field see here: Documentation for Field-UI and look at the section titled, "Reusing Fields".

Here's the answer to this question:

I cannot use the same field within one content type. Only one instance of a field may be used within each content type. This is why the field which I have created is not showing up in the drop-down for "add existing field" - it is not available.


Performance and javascript issue in a drupal 7 website I have a drupal 7 website. Currently its performance is not good and takes much time to render the web pages. For performance, I checked out in YSlow and came up with some results like move all js files at bottom, compress them and images too etc.

As far as I know its drupal structure to render js first at the head and then it loads the body content. So, Is there any way to move all js files at bottom of the web page in drupal???

I tried to aggregate javascript and css files with the admin panel in drupal but that is breaking some features of the website, say for example, some jquery and ajax codes are not working. Please suggest something for these problems as how can I approach for it.

You could try advagg, but shoving cloudflare at the problem is usually easier, let them deal with the js complexity by converting it to rocketscript for you for free!

Or you could mention which modules you have, how many scripts you are attempting to load, whether they are asynchronous/deferred etc, what version of jQuery, perhaps even a link to the site itself so we can have a look?


if title available print $title if disabled print somthing else I use advanced forum but it uses default Drupal title method.

I know there is a module called Comment subjects for this purpose but I need to do it in this way.

I would be grateful if anyone could help me.

 if $title >avalible print $title
 if $title disabled print
<a href="#<?php echo $comment->cid; ?>"> Re: <?php print $node->title ?>

OR

 if > node print $node->title
 elseif comment $print
<a href="#<?php echo $comment->cid; ?>"> Re: <?php print $node->title ?>

Found the Solution.

Go to -> (advanced_forum/styles/naked/advanced-forum.naked.post.tpl.php)

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

      <?php print $title ?>

  <?php endif; ?>

Then replace it with:

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

        <?php print $title; ?>

<?php else: ?>

<a href="#comment-<?php print $comment->cid; ?>"> Re : <?php print $node->title ?>

<? endif; ?>


z-index Drupal 7 Skeleton Boilerplate discriminating roles? I'm building a website using Drupal 7 for the first time. I have always built them on Drupal 6 using the basic theme to build my own custom themes from. This time I decided to change, because I thought it was time to move onto Drupal 7 and I wanted responsive design for this project.

I have a custom front---page template, and on that front page I have views slideshow (cycle) and wanted to place text on it. So i made a block with such text, and gave it a z-index 999 and an absolute position, when the slider has a z-index -999. Everything looks just as I want it and expect it to, until.... I log out! Is it possible that the css is discriminating roles?

How can it possibly be that logged in as admin I see the slider on the bottom and the block on top as expected, and as an anonymous user the text block is hidden underneath the slider? (And I know it is because when I resize, I can partially see it, as it moves down.... ) I'm lost.

Edit for more info: this is happening in IE9, Chrome, Safari mac, Safari Win, and Firefox is displacing the Slider onto the right....GRRRR. HELP!
Thank you in advance for your help.

I was too quick to post the question and I apologize, since the answer is all over the internet, and for those going through the same issue:

YOU MUST add position relative or absolute to all items involved in the z-indexing. Ot the z-index won't work.

Also why was Firefox not rendering things right? I had added a skeleton class to the search box template, but had not added a clear right after.

As to why it was rendering things right when i was logged in as an admin, but not when I was anonymous, remains a mystery.

Hope this is useful for those having identical issues.


Optimal route on creating landing pages So, time and again I've come across the requirement to create a "custom" or "landing" page which pretty much narrows down to this:

The co-existance of manageable text/content along with predefined views and/or blocks

For example:

-----------
|[managed |
|    text]|
|- - - - -|
|[View    |
|    pane]|
|- - - - -|
|[HTML    |
|   block]|
|_________|

Page Manager seems to be the way to go, but apart from using a block to accomodate my Managed Text (in this example), and thus creating a block for "non-blocky" purposes, and using it as an HTML containing entity, I cannot think of a better way.

So, tl;dr version:

Which is the optimal/Drupal way of having predifined and managed content bundled up together in a single page?

Yes, as you mentioned, you can do that reasonably easily with Panels / Page Manager

Enable the "Custom content panes" module to add arbitrary HTML content to Panels regions.

Note, when using Views in your Panels content try Views Content Pane type displays, which are designed for embedding into Panels and provide some useful settings in the View.


Drupal 7: Database select query FROM cache_bootstrap brings server down The below query occasionally takes up to 24 sec and consumes the complete server resources.

SELECT cid, data, created, expire, serialized
FROM cache_bootstrap
WHERE cid IN ('variables');

I was informed today by my web hoster (I am on a shared server) that above select query brings down the whole node.

I have caching enable (with block caching disabled). JS- and CSS files are aggregated and cached pages are compressed. The site is running ok with no issues.

Any ideas how to track down the problem?

If you can get memcache properly installed, that will help the most as it will shift queries from the cache tables in the db to your memcache server.

Try these 3 things (in order of importance):
Set the transaction isolation level to Read Committed - https://drupal.org/comment/8437127#comment-8437127 (look in your settings.php for the insertion point; it will be after the $databases variable has been set with the database credentials). This is helpful even if using memcache.

$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

Change your semaphore table to memory - https://drupal.org/comment/8469889#comment-8469889 (use the first code block "Have the name value be a primary key"). Note that this might not work if you are using MySQL 5.0 or lower due to BTREE indexes not working in Memory tables. Also noted that if you are using the memcache version of lock.inc this will not help.

ALTER TABLE semaphore ENGINE = MEMORY;
ALTER TABLE semaphore DROP PRIMARY KEY;
ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE;
ALTER TABLE semaphore ADD UNIQUE name (name) USING BTREE;
ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;
ALTER TABLE semaphore DROP INDEX expire;
ALTER TABLE semaphore ADD INDEX expire (expire) USING BTREE;

Apply this core patch - https://drupal.org/node/2193149 This will help to reduce database deadlocks from occurring only after the above 2 have been done. If using memcache this core patch will not help as this fixes an issue when using the database as a cache backend.


Webform page wizard and submission data - no reference to which page the element was on I am creating a multi-page webform questionaire using the Page wizard.

I have also created a custom handler so I can manipulate the data from the form when completed.

My issue is that when using $webform_submission->getData in the method 'submitForm' in my webform handler class to gather the data, there is no reference to which page the element is from, the array simply contains the element key and value pair.

What would be a proper way of figuring out which page each element is from?

My solution for this in the end was to use a method on the webform object called getPagesWithElements.

// Get webform object
$webform_obj = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
// Get page/element structure
$model = $this->getPagesWithElements($webform_obj);


How to submit a user profile form through ajax? I want to submit the user profile form through ajax.

I see the ajax_register module but it does not support the user profile form. Is there any contrib module which I can use?

Or this can done custom. But with custom approach I have to look for the form validation also?

Below module will help you

Modal forms (with ctools)

  Modal forms make use of the modal feature in the ctools module to open
  some common forms in a modal window.

Log in (modal_forms/nojs/login)
Request new password (modal_forms/nojs/password)
Create new account (modal_forms/nojs/register)
Contact (modal_forms/nojs/contact)
Comment (modal_forms/nojs/comment/reply/%node)
Webform (modal_forms/nojs/webform/%node)

  Function that rewrite normal links to modal forms links (except for
  webforms) can be activated on the modules configuration page


Tabular data in Drupal: create a field with multiple attributes Hello again

What I want to do is simply like creating tabular form, that the user can edit attributes of each row.

In detail, I have a content type lets call it Website, this content type should contain predefined Stages and Processes. For each Stage/Process the user should be able to check as done, or enter a reference or notes, or any another related operations.

As an Examples

Feed the cat ---- (checkbox) ---- Reference ---- Notes

So, how could I represent this tabular form in Drupal 7?

Is there any module specially made for this purpose?

Hope you can help guys

Best and peace

You should look at the Field Collection module, which allows you to make groups of fields and reuse them in a content type like a single field. So in your case, each collection might contain the fields "stage," "completed" (checkbox), "reference," and "notes," and then you could use that field collection multiple times throughout your content type.


Exclude fields from a node-add form (but keep them on the node-edit form) by excluding (to save load time) not hiding? Drupal 7 The site I am building is for a parts database and parts are related to each other - eg a circuit board can have a bunch of screws and relays that are sub parts and the board itself can be a sub-part of a module.

When you are registering a circuit board (node-add) you don't need to associate it with parent parts or sub parts. But you may want to do that when you edit it (node-edit).

The parts are associated by entity reference fields and the entity select views take a bit of time to load. I want to save that load time for the node-add by excluding those fields from the node-add form completely (not just hiding them) but I want them to load as normal for the node-edit form.

Thanks very much and have a great Friday!

Okay I got it to work. On new nodes there is no NID on existing nodes there is. This code works.

function custom_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'custom_node_form') {
    if (empty($form['nid']['#value'])) {
    unset($form['field_remove_this_field_name']);
    }

}

Unfortunately I still have a slow load time and I suspect that even though I'm unsetting the form fields that involve entity references (and therefore views queries to populate selection lists) that the queries are still getting run.

It's only really slow on the first form load after clearing caches. The second form load is much faster.

If anyone has any ideas to speed up the initial form load, I'd love to hear them.

It may be that I need to create a custom form from scratch using module code and only load the essential fields.


How do I get low level data from the Flag module? Is it possible to get the following raw, low level data from the Flag Module and/or it's services?

Flagging count as integer
URL to flag/unflag as a string
Current user's flagging status as boolean

I already know that I can do this:
$flag_link = \Drupal::service('flag.link_builder')->build('node',$nid,'bookmark');

But it will output the full blown markup with Ajax and everything.
I've done this:
$flag_service = Drupal::service('flag.count');
$counts = $flag_service->getEntityFlagCounts($node);

But I can't actually figure out what exactly $counts contains, I definitely can't output it as an integer on my template, I get an error.

To get the total flagging count:
$count_service = \Drupal::service('flag.count');
$flag_counts = $count_service->getEntityFlagCounts($node);
$count = $flag_counts['my_flag'];

To get the current user's flagging status:
$flag_service = \Drupal::service('flag');
$my_flag = $flag_service->getFlagById('my_flag');
$user = \Drupal::currentUser();
$is_flagged= $my_flag->isFlagged($node,$user);

to toggle the flagging status:
if(!$is_flagged){
    $flag_service->flag($my_flag , $node);
}

or
if($is_flagged){
    $flag_service->unflag($my_flag , $node);
}

Best to wrap all of this into an if clause
if( $user->isAuthenticated() ){ ... }

It's probably easiest to just build my own URL / route to take care of the toggling to fit my needs.


How can a node appear in different places? This is the kind of planning-stage question that I tie myself up in knots with...

A film site has main nav headings for Comedy, Fantasy, Kids etc. Each menu item displays a listing View of content type 'Film' tagged with the relevant taxonomy terms.

For example, 'Harry Potter' film is tagged as Fantasy and Kids, and appears on both listing pages.

If the user goes to the Fantasy section and clicks on 'Harry Potter' to view the full node, it needs to appear within the Fantasy section.

To achieve this, I am thinking of using another View to display the node content in the correct section (so the user never gets to the actual node). Or maybe I can do something with Panels. Or perhaps some kind of dynamic menu management?

I just have that familiar feeling that there has to be a cleaner way with Drupal?

You can do this pretty easily with views...just build a view with different page or block displays that filters nodes by the different tags (a.k.a. Taxonomy Terms). You can manually build a menu that provides links to the different pages that correspond to each tag.


When using the workbench core module, how can one assign a node to a new author and it show up in their list of content? I'm using workbench core, which so far is providing the workflow that I need (well, almost).

The workflow is:

Primary editor writes a new node, and leaves it unpublished.
When the Primary editor is finished, he edits the node and changes the 'author' field to the new editor who will continue editing.
The New editor accesses his workbench page to (should be able to) see the unpublished node in his article list, where he continues to edit.
The New editor publishes the node after he has finished.

The problem is that the article never shows up in the New editor's article list on his Workbench page. However, when viewing the Content list, the article shows correctly and shows that he is indeed the owner / author.  There is something wrong with Workbench that doesn't recognize new ownership of nodes (via the author field).

Is this a bug? Configuration setting?  All I want to do is change the author of this node and it show up in his workbench.  I am hoping I can do this without having to add any more workbench related modules.

To me it feels strongly like a configuration issue with the view that was supplied by the Workbench core module, but no amount of fiddling with it has proved productive.  I think I'm just missing something. Plus, I'd prefer not to have to hack a module.

Here is a Drupal.org thread about it, however, no one has looked at the issue for months.

https://drupal.org/node/1921798

Workbench uses Views to render it's data. The trick - whilst new user is now considered author of a node, last edit was not his. So it will not be seen in "my edits".

Go to http://example.com/admin/structure/views/view/workbench_edited/edit.
You will see:

This filters by revision's author. Not what you want. What you need is to filter by node's user.  But this view does not have a relationship to content author:

Add missing relationship:

Filter is still using wrong relationship:

Make it use proper one:

Done. Repeat for other views as needed.


How can I have a new dropdown for each entity reference added? I have a content type with an entity reference to another content type that has over a hundred items. I want to use a dropdown menu to select the entity, since the user won't always know the titles of those entities. However, with so many entities, scrolling through and selecting multiple entities using the Select List widget is not the desired user experience.
Is there a way to make a new field appear per reference, like the autocomplete widget, but with dropdowns?

I would look into the Chosen and/or Select 2 modules. They both work to improve UX for select fields.
I've used the Chosen module multiple times in the past, so that's where I'd lean here. The module improves the UX for users managing multiple selections on a select field. The chosen library alters the UI to allow users to easily select multiple options - it even provides autocomplete functionality to limit the results of the select field.


Correct way to display a custom field in a custom content type page template I'm using Drupal 7 with a custom content type called "lesson". In this custom content type I have a custom field named "field_lesson_objective". I'd like to be able to wrap this in a custom div, so I thought it would be pretty simple to open up my custom page template "page--lesson.tpl.php", remove "", and replace that with something that would display the field, but I'm having no luck finding a solution.

Perhaps I'm going about this all wrong.

Ok, figured this out. I copied node.tpl.php to my templates directory in my theme, and then duplicated that with the name of of custom content type:

node--lesson.tpl.php

I was then able to display my custom field with this:

<?php
   echo render($content['field_lesson_objective']);
?>


Node theme template override isn't working I'm using the paid theme md-alpine and I added a content type called webinars, and a node template for webinars node--webinars.tpl.php

The only thing I put in the page is  and I only get an HTML page with no CSS.  Am I supposed to add a call to the node--webinars.tpl.php page somewhere?

EDIT: I changed dpm to print_r and the rest of the theme printed.  Put it back to dpm and it doesn't load.

This is the raw output of the page:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>

Home

About

Gallery

Staff

Testimonials

Donations

Blog

Contact

Members

                Posted by admin

Test

                21 June 2014

Primary tabs

View(active tab)

Edit

Devel got disabled somehow breaking the page when calling dpm.
Re-enabling fixed all.


How to display the value of a report parameter in a Forena Report and in a CSV export of it? Using Forena Reports I'm wondering if it's possible to include in a report the PARAMETERS passed by the URL?

I'd just like to output those parameters once in the report; probably at the top. Something like this:

You selected 'item a, item b, and item c'. (where items a,b, and c are the parameters passed).

Extra question: When I run the sample report with state=VA and then click 'CSV', the CSV download will not say which parameters were selected. Anyway to have the CSV download also include the parameters (+ their values) that were specified?

Display the value of a report parameter in the report

A sample of showing the values of the specified parameters can be found in reports/sample.user_distribution_simple.

If you execute that report with a parm like (eg) state=VA, or you just use an URL like /reports/sample.user_distribution_simple?state=VA, the report will contain a phrase like "This report lists all users in cities assigned to a state with code = VA.".

Line 26 in the .frx source of this sample that creates that phrase looks like This report lists all users in cities assigned to a state with code = {parm.state}.

So in this specific case, try something like this:

You selected 'item {parm.a}, item {parm.b}, and item {parm.c}'.

That is: preceed the parameter(s) with {parm. and have them followed by a }. Some more details about this:

The { and } are an indication you want to include something in your report about the report "context" (= Forena terminology).
The parm. part of it is to indicate "one of the report parameter values".
The a is to actually name the exact parameter (like 'a').

This technique (syntax) is also used to create "linked" reports (drill down reports, etc).

Here is a sample of one of my "custom" reports where I do something similar:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (the "8" within "... statistics within 8 most recent log messages ..." was the value of one of the parameters).

Include the value of a report parameter in the exported CSV file

The file saved via the CSV export feature, will actually include all the report data shown in the report as "tabular" format (which is compliant also with the csv tag description ...). So to get the report parameter (and the specified value) included in the CSV export file, you'd have to somehow include that in the appropriate area of your report.

As a sample, consider the reports/sample.user_distribution_simple again. You could enhance (customize) this report (which is specified using xHTML ...), by adding these extra HTML lines before the
 tag:

    &nbsp;
    &nbsp;

    Report parameters
    Parameter values

    state
    {parm.state}

In doing so, and by rerunning the report again with report parameter (say) state = VA, you should get a CSV export file that looks like so:

city,users
Amesbury,"3,991"
Catskill,"3,123"
Ketchikan,"6,107"
Michigan City,"1,741"
Selma,"1,833"
Vineland,"1,825"
 ,
Report parameters,Parameter values
state,VA

One could argue about the layout/format of the CSV output file (like the 3rd line from the bottom that only has a ","), but the keypoint is that you can use the full power of xHTML to enhance the layout to fit your needs. E.g. replace the &nbsp; (twice) with something more appropriate, or move those tfoot rows somewhere above the thead rows (to have the parms and values shown at the top of the CSV file.


View filter on date "Less than or equal" AND NULL(empty) I just made a view with some filters (date), I wonder how can I choose the operator to mix the options "Less than or equal" and NULL, in just one request? I can't do that with "Grouped filters", Should I hook the code? If that's so, where?

Thanks so much

Well I could figured out this for myself, if anyone need it here is what you need to do:

Go to sites/all/modules/views/handlers/views_handler_filter_numeric.inc
In there:

a. Inside the function operators()->$operators = array(

b.

'custom' => array(
'title' => t('Title you want for your operator'),
    'method' => 'op_custom',
    'short' => t('<='),
    'values' => 1,
 )

c. Then around line 255 or so create a new function:

function op_custom($field) {
  $or = db_or()
  ->condition($field, $this->value['value'], 'IS NULL')
  ->condition($field, $this->value['value'], '<=');
  $this->query->add_where($this->options['group'],$or);
}

And you can choose that operator now in your Data Filter.

I hope this helps, any questions let me know as PM or comments, take care


How to create a node with mulitple field-collection items? I've a content type having filed collection item (3 fields of 5 sets). Created a custom module form, when user submits that form, it should create a node with all 5 set field collection items.

So far tried the following code. it's working for 1st set but not for all.

$values = array(
  'type' => 'ct_machine_name', // Content Type machine name
  'uid' => $uid,
  'status' => 1,
  'promote' => 0,
  'title' => 'xxxx',
);
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->save();
$node = node_load($entity->nid);

$fc_val= entity_create('field_collection_item', array('field_name' => 'field_fc_mcnename'));
// Attach to the node
$fc_val->setHostEntity('node', $node);
$fc_val->field_field1[LANGUAGE_NONE][0]['value'] = $val1;
$fc_val->field_field2[LANGUAGE_NONE][0]['value'] = $val2;
$fc_val->field_field3[LANGUAGE_NONE][0]['value'] = $val3;

// Save field-collection item.
$fc_val->save();

The above code working. But I need to loop through it and save all field collection items in an user submitted order.

I tired as follows, but doesn't work. (example)

for ($i=0; $i<=4; $i++) {
$fc_val->field_field1[LANGUAGE_NONE][$i]['value'] = $val1;
$fc_val->field_field2[LANGUAGE_NONE][$i]['value'] = $val2;
$fc_val->field_field3[LANGUAGE_NONE][$i]['value'] = $val3;
}
$fc_val->save();

Also tried

for ($i=0; $i<=4; $i++) {
$fc_val->field_field1[LANGUAGE_NONE][0]['value'] = $val1;
$fc_val->field_field2[LANGUAGE_NONE][0]['value'] = $val2;
$fc_val->field_field3[LANGUAGE_NONE][0]['value'] = $val3;
$fc_val->save();
}

Any inputs or suggestions would be much appreciated.

Try This:
Example for field1 and repeat it with other fields.

$entity_fc_val = entity_metadata_wrapper('field_collection_item', $fc_val);
$entity_fc_val->field_field1->set(array('value' => $val1));


Render Array Javascript with Variables I'm creating a custom block and I'd like to add some Javascript to it.
I'm using a Render Array to add the Javascript to the page, which works fine, I'm then trying to add some variables to the Render Array for the Javascript to use.
This is what my Render Array looks like
$content = array(
  '#slides' => $slides,
  '#theme' => 'slider_block',
  '#attached' => array(
    'js' =>
      array(
        drupal_get_path('module', 'single_slider') . '/js/test.js' => array(
          'type' => 'file',
        ),
      )
  )
);

$content['#attached']['js'][] = array(
  'data' => array('word' => 'world'),
  'type' => 'setting'
);

return $content;

I'm then trying to access the variable in the Javascript (test.js) file using the following.
console.log(Drupal.settings);

At the moment this just returns with an empty object. If someone could point me in the right direction I'd appreciate it very much.
Thanks in advanced.

Ok I've managed to solve it myself.

For anyone that is interested my Render Array now looks like this.

    return array(
        '#slides' => $slides,
        '#theme' => 'slider_block',
        '#attached' => array(
            'js' => array(
                array('data' => array('word' => 'world'), 'type' => 'setting'),
                drupal_get_path('module', 'single_slider') . '/js/tes.js'
            ),
        )
    );

And my Javascript file (test.js) now looks like this.

(function($)
{
    //console.log(Drupal.settings.word) //This won't work and will return with undefined.
    $(function()
    {
        alert('Hello ' + Drupal.settings.word);
    });
}(jQuery));


Text field will not save after moving it from commerce billing profile to account fieldset in checkout I am having difficulty moving a text field from the commerce billing profile entity to the account fieldset on the checkout page. No matter what I do the text field is not saved after moving it back in the custom validate function. Is there something that I'm missing?

/**
 * Implements hook_form_alter() from checkout page.
 */
function example_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {

  // Move phone number field from billing profile to account fieldset
  $form['account']['phone_number'] = $form['customer_profile_billing']['field_customer_phone_number'];
  unset($form['customer_profile_billing']['field_customer_phone_number']);

  // Declare custom validate and submit functions
  $form['buttons']['continue']['#validate'][] = 'example_checkout_form_validate';
  $form['buttons']['continue']['#submit'][] = 'example_checkout_form_submit';
}

/**
 * Custom checkout form validate function
 * @param type $form
 * @param type $form_state
 */
function example_checkout_form_validate($form, &$form_state) {

  // Move field back to billing profile
  $form_state['values']['customer_profile_billing']['field_customer_phone_number'] = $form_state['values']['account']['phone_number'];
  unset($form_state['values']['account']['phone_number']);
}

EDIT: I tried moving the text field back to commerce profile in a custom submit handler as shown below, but I still can't get it it work.

/**
 * Custom checkout form submit function
 * @param type $form
 * @param type $form_state
 */
function example_checkout_form_submit($form, &$form_state) {

  // Move field back to billing profile
  $form_state['values']['customer_profile_billing']['field_customer_phone_number'] = $form_state['values']['account']['phone_number'];
  unset($form_state['values']['account']['phone_number']);
}

I want to move this field, which is for the customer's phone number, on the checkout page for aesthetic purposes. In the current workflow the shipping address is shown first followed by the billing address. Since the phone number field is attached to the billing profile, it looks strange when "My Billing information is the same as my Shipping information." is check as shown below.

This is the last part of the checkout page redesign. I am so close to finishing it. Any help would be much appreciated.

Thanks
Paul

EDIT

I was finally able to figure this out with the help of Ryan Szrama and http://www.drupalcommerce.org/questions/3711/saving-customer-profile-field. Thank you guys.

function example_checkout_form_submit($form, &$form_state) {
  $order = $form_state['order'];
  $phone = $form_state['values']['account']['phone_number'][LANGUAGE_NONE][0]['value'];
  $po = $form_state['values']['account']['po_number'][LANGUAGE_NONE][0]['value'];

  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // get profile id
  $profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

  // load customer profile
  $profile = commerce_customer_profile_load($profile_id);
  if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {
    // set the value of the field and save the profile
    $profile_wrapper->field_customer_phone_number->set($phone);
    $profile_wrapper->field_customer_po_number->set($po);
    $profile_wrapper->save();
  }
  unset($form['account']['phone_number']);
  unset($form['account']['po_number']);
}

Unfortunately, you can't move this and have it continue working as normal. Entity form submission depends on a specific "tree" hierarchy in the submitted field values, and moving it like this disrupts that. Thus when the customer profile information is saving, your custom textfield is just invisible.

If you really need to move this, then you should add a custom submit handler that populates the customer profile as before.


How to Install two version of Drush? I installed in my PC drush 8 for develop on Drupal 8, but I need drush 7 for connect with my sites on remote servers.
I download manually drush 7 but when I try to open said me:

  Unable to load autoload.php. Drush now requires Composer in order to
  install its dependencies and autoload classes. Please see README.md

Then, How I install two versions of Drush in my PC?

Drush 8 should work just fine with remote sites running Drush 7.

To get around the error message you are seeing, run composer install from the Drush directory.

If you want to install multiple versions of Drush to run locally, the easiest way to do it is to manage your Drupal site with Composer, and add a 'require drush' line in your composer.json.  If your global Drush is at least version 7, then you will find that Drush automatically dispatches to the site-local Drush whenever you target it.

One really good use-case for doing this would be to run Drush 7 stable as your global Drush, but use Drush 8 with any Drupal 8 site.

See also:

https://github.com/drupal-composer/drupal-project
https://github.com/pantheon-systems/example-drupal7-composer


Views: URL Alias as a field How do I get the URL alias of a node in views.

Here is a previous question, Get a url alias as a field value?
However, the Content: Link field outputs something along the lines of

view

I want to wrap the link around another field using rewrite results and tokens.  Something like

[product:image]

I was able to do this with

[product:image]

However, I would rather have it show the node alias than the node ID.

If you click on Content: Path it will give you the a field that repesents the path of the node.


routing.yml file doesn't work I'm working on an existing Drupal 8 site. I'm changing anything in routing.yml.

In a routing.yml file I have the following.

user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

I want to change the controller's method to
\Drupal\user_profile\Controller\ProfileUpdateController::updateUser123(), but after editing the route definition, the ProfileUpdateController class is still using the updateUser() method.

I removed all the cache tables from the database with the following SQL, but the controller is still not using the updateUser123() method.

TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;

How can I fix the issue?

You're saying that you have this in your routing.yml file:

user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

You're still calling updateUser and not updateUser123

Your controller should be looking like this:

class ProfileUpdateController extends ControllerBase {

  public function updateUser123() {
  //your code here
  }

}

And now you'll need to call the method:

user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser123'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

Also I recommend clearing your cache with Drush.
This will empty all caches and rebuild the data required for Drupal to execute the page request


How to remove Quicktabs cookie on certain page? I found a useful snippet here to make Quicktabs remember which tab was open if the user leaves the page and then comes back again. My problem is that I want to remove the history (the cookie) after the user has payed a visit to a certain page. In that case I want the default tab to be opened when the user comes back again. In the Quicktabs settings I have set the wanted default tab.

I have a script.js in my theme with this snippet:

  Drupal.behaviors.quicktabsHistory = {
    attach: function(context, settings) {
        var id = $(this).attr('id');
        var tab = $.cookie(id);

        // enable quicktabs memory
        $('.quicktabs-wrapper', context).each(function() {
            if (tab != '') {
              $(this).find('ul.quicktabs-tabs a#' + tab).click();
            }
            $(this).find('ul.quicktabs-tabs a').click(function() {
                $.cookie(id, $(this).attr('id'));
            });
        });

        $('.view-taxonomy-term', context).each(function() {
            if (tab != '') {
              $.removeCookie('id');
            }
        });
    }
};

Everything works fine, except for the part where I want to loose the history. How can I remove the cookie if the user visits the page with the wrapper class ".views-taxonomy-term"?

EDITED: I tried changing the removeCookie row to insteaed force the tab I want to be the default one:

    $('.view-taxonomy-term', context).each(function() {
        if (tab != '') {
          tab = 'quicktabs-tab-instrument_flikar-0';
        }
    });

But that did not do the trick. I have checked though with a breaking point in the script that the tab variable actually is set to the new value, but the previous tab is still activated after return to the page with the tabs. There is something about Drupal.behaviors.quicktabsHistory that I don't understand, obviuosly. :-(

Finally solved it. In case anyone is stuck with the same problem, this code now works for me. I learned that it's important to always set the path, to be able to retrieve the same cookie on different pages. I never got $.removeCookie() to work, so instead I used a default value. Also it did not work to use true, false and undefined as values, but it worked to use them as text inside quotes, 'true', 'false' and 'undefined'. Slowly getting there :-).

      Drupal.behaviors.quicktabsHistory = {
        attach: function(context, settings) {

        var default_tab = 'quicktabs-tab-instrument_flikar-0';
        if($.cookie('id', {path:'/'}) == 'undefined'){
            var id = $(this).attr('id');
        }else{
            var id = $.cookie('id', {path:'/'});
        }
        var tab = id;
        var flagga = $.cookie('flagga', {path:'/'});

        if($("body").is(".page-taxonomy")) {
            $.cookie('flagga', true, {path:'/'});
            $.cookie('id', default_tab, {path:'/'});
        }

        $('.quicktabs-wrapper', context).each(function() {
            if (tab != '' && flagga === 'false') {
              $(this).find('ul.quicktabs-tabs a#' + tab).click();
            }
            else {
              $.cookie('flagga', false, {path:'/'});
              $(this).find('ul.quicktabs-tabs a#' + default_tab).click();
            }

            $(this).find('ul.quicktabs-tabs a').click(function() {
                $.cookie('id', $(this).attr('id'), {path:'/'});
            });
        });
    };


multistep module to create multistep registration form I need to use the multistep module to create a multistep registration form in Drupal 6.

In the multistep module you can easily create a multistep form for a content type but I need to use it instead of Drupal normal registration page.  How can I do this?

From my experience, CTools works great for multistep forms using the CTools form wizard. I've already used it successfully but never tried with user registration.

You can follow a nice tutorial for that case here:
Multistep registration form in Drupal 6

Another tutorial:
Intro to Drupal 6 Multistep Form Domination Using Chaos Tools

Happy coding :)


Is there a way to see what parts are not in a feature? I am working on a site where I have content types with fields coming from several different feature modules. I've added organic groups with groups on most of those content types, and also added some content types and fields.

Now I need to package things up, update the features modules, and make new ones. I am going over things looking for overridden features, and adding fields that are missing. While I can see what is overridden, it can be easy to overlook new fields that I need to add, especially when I have to cross-reference different modules.

Is there a way I can see what featureable parts are not in a feature? Since I'm dealing with several different features, I can't just look at one 'recreate' page and see what I need to add. I would like to see a master list of what part is in what feature and what is still in the database.

2 options:

Using Drush, the following command will show you all the Features Components which aren't already claimed by a Feature:

drush features-components % --not-exported

You can install the Features Orphans module, which provides a list of unclaimed Features Components using Drupal's web interface.


Does views load all nodes in a result or just the ones in each page of results? I am trying to determine if I am going to see a performance impact. I have a view that can possibly return thousands of results but only displays 50 per page. Each node in the result determines it's proximity to the current user using geofield. I want to know if it's going to try and do it for every node in the result, or just the ones in the current page.

So, does Drupal load all of the nodes in the results or just the ones in the current page?

When you display a certain number of records per page it does not load and hide the extra records, it simply never pulls them from the database. So you'd certainly be helping performance by limiting the number that are displayed per page.

In fact, if you look at the SQL query generated by the view, it'll say the following if you're showing 20 items per page, for example:

...
LIMIT 20 OFFSET 0
...

====================== EDIT ====================

What this means for performance

As @Clive and I were discussing above in the comments, A LIMITed query will inevitably be faster than one with no LIMIT, but overall performance will also inevitably decrease as the number of nodes you are searching through increases.

Limiting the number of returned records has performance savings on the Drupal side too, though.  That's because Drupal wouldn't be running the additional processing on the Drupal side to do things like access checks, pre-processing and other display-related functions for the records that aren't returned by the query.

==============================================

p.s.  You can configure whether you want Views to show you the sql query it's generating by going to /admin/structure/views/settings and checking the 'Show the SQL query' checkbox in the 'Live Preview Settings' section.


Allowing users to create multiple "notebooks" of nodes I'm trying to add some functionality to a site that I'm building that would allow users to create multiple "notebooks" that themselves contain links to nodes on the site, and metadata that the user can edit: a little like Evernote, but restricted to one site.

What's the best way to go about building this? I was thinking of using either Entity Reference or Flag, and would be interested on hearing thoughts regarding both of these options, and also any other ways to implement this functionality.

We did the on a Drupal 6 site a few years ago.

If you want a single notebook, or have a fixed number of notebooks, then you can use Flags.

Our client wanted an unlimited number of notebooks, so we went the node references.

Basically, we created a "notebook" content type, with a few fields on it.  One of the fields held the noderefs of everything that was saved.  We may have also had some metadata for each saved item.  It's a mostly straightforward approach, but it involves a decent of plumbing to add/remove things (the unlimited number of notebooks complicates some scenarios), and you also need to consider all of the use cases you want with regards to how notebooks will be managed.

If we had to do this again with Drupal 7, then I would likely still go with nodes and entity references, potentially using field collections to bundle the entityref with metadata for a saved item.


What does views_ensure_table() do? I see it often, $this->ensure_my_table() and I'm not sure what it does and why it is important when building Views handlers.

Taken from the API page:

views_handler::ensure_my_table

  Ensure the main table for this handler is in the query. This is used a
  lot.

It's just to make sure that the base table (node or user for example) that your handler needs is referenced in the query/actually exists.


Cannot post new content after installing varnish Our drupal 7 site was running so slow it was almost unresponsive, so I had to install varnish 2.1.5 this weekend. I got it up and running, and everything is now lightning fast, users can login and everything else is good... except that none of our authors can post new content.

When new content is posted, whether it's from the admin overlay or the actual node/add/news path, the URL just reloads and nothing happens. The form data is all in the Request Payload, the SESSION cookie is set, Varnish supposedly isn't caching... and yet nothing happens. I even installed the varnish module for drupal, but that only seems to handle reporting, and not actually doing anything.

Here's my default.vcl file.

I'm not seeing anything suspect in the vcl, but it certainly seems to be screwing something up.

Edit: I should point out that I don't have any issues changing settings in admin, or doing anything else, other than posting content, so it's not like all forms are broken. It might have something to do with ckeditor which is only present on the new content pages, but that seems like a stretch to me.

Edit 2: Realized I can create new blocks as admin, which uses the ckeditor which means that doesn't have anything to do with it. No new entries are getting put inserted into the node table and there's nothing suspicious in the watchdog logs.

I finally found a solution. Inside my default.vcl file I added the following block at the top of sub vcl_recv:

sub vcl_recv {

  # forward request directly to Apache if SESSION cookie is set.
  if (req.http.Cookie ~ "(SESS[a-zA-Z0-9]*)=") {
    return (pass);
  }

  ... # whatever else you need to do in vcl_recv
}

Basically I'm just checking to see if my session cookie is set (anyone else reading this might have one formatted differently) and if so, forwarding it to Apache. This seems to have fixed the problems as new content can be posted again. Not really sure why the elaborate cookie filtering I had in place (and which was working in every other case except posting new node content) didn't work, but this seems to be the solution, even if it feels a little heavy handed.


How to theme Profile 2 fields for anonymous? I bring this question because I am not able to find the answer in anywhere, my apologies if it is a repeated one.

I have a Profile 2 type "curriculum_vitae", that I use to gather jobseekers CV.

I have all the Jobseeker's CVs  available for anonymous users which is working fine. My question how to theme the jobseeker's CV page "The page that will display to anonymous user once they click at the jobseeker profile".

I have a page named "profile2--curriculum_vitae.tpl.php" located at "\templates\profile2--curriculum_vitae.tpl.php".

I want to theme every single field of curriculum_vitae profile.

For example :

Email:
Here I want to print jobseeker's email in here, the filed machine name is "field_cv_email_address"

You can create a View of page display of type Profile types

Then in this View add curriculum_vitae as Relationships, It causes the fields of  curriculum_vitae profile be added to the Fields.

Now create a Contextual Filter of any field you want (it might be name, ID, ...).

So you can easily theme this View to display the information of the selected user.  If the View name be profile, Then using views-view-fields--profile--page.tpl.php you can theme the output.


Is it possible to call response()->setStatusCode() within hook_theme_suggestions_page_alter? We set up a custom error page theme by creating a block with the error text and then used the following code within a hook_theme_suggestions_page_alter implementation to determine when to override the template and show that "Page Not Found" block:
// error page template suggestions
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
  $status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
  $suggestions[] = 'page__error';
}

Now it turns out that due to some hosting constraints we need to be able to serve up a version of the "Page Not Found" page with an HTTP status code of 200. So, is it possible to use response()->setStatusCode() within hook_theme_suggestions_page_alter? I was hoping to just override the status code for a single arbitrary route, but so far my attempts to call it from there have been unsuccessful.
Admittedly, it would be a hack to call it there even if I can, but I wanted to check before reverting a bunch of theming code.

You don't need this code by the way, it is in core since D8.8.x, see https://www.drupal.org/node/2960810.
If you want to change the status code then do this in an event subscriber. If you want Drupal to build a normal 404 page and only change the status code of the already built error page then use a response event subscriber and set the status code:
$response->setStatusCode(200);

See this answer for the scaffolding https://drupal.stackexchange.com/a/201297/47547


How to get the Route object from an URI? If I have a Url object, or even a simple string representation of path such as /node/2, how can I get the full Route object?

You can retrieve this information from the Symfony router. This can be accessed in Drupal through the router.no_access_checks service.

If you have a simple path (note that the path has a leading slash):

$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');

If you have a Url object:

$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());

This will return an array that includes the route object, as well as other useful information such as the route name and route parameters, the controller, the title callback and even the entity object represented by the URL.


How can I debug an AJAX error in VBO? (PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri' I have a view that lists all the user accounts on my site.  With VBO, I have a rules component, Resave user account (action set, action: save entity (user), no force saving immediately).

Recently, when I attempt to re-save all user accounts, I got an error on id=4037:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging
  information follows. Path: /en/batch?id=4037&op=do StatusText: Service
  unavailable (with message) ResponseText: PDOException:
  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '' for key 'uri': INSERT INTO {file_managed} (filesize, status,
  timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0
  [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] =>
  1375690632 ) in drupal_write_record() (line 7153 of
  /Volumes/Bullfrog/om/includes/common.inc).

And when I attempted to save all accounts again, the error occurred on id=4039:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging
  information follows. Path: /en/batch?id=4039&op=do StatusText: Service
  unavailable (with message) ResponseText: PDOException:
  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '' for key 'uri': INSERT INTO {file_managed} (filesize, status,
  timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0
  [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] =>
  1375691655 ) in drupal_write_record() (line 7153 of
  /Volumes/Bullfrog/om/includes/common.inc).

So, if I simply continue to re-save again and again, eventually all the accounts will get re-saved, but to execute this bulk operation takes about 20 minutes each time, so I will waste several hours this way.  How can I analyze what is the cause of this error?

Duplicate entry '' for key 'uri' actually says a little more than AlexK realizes, it says both that there's a file without a uri, hence the '', and that you have more than one of these, hence the Duplicate entry.

I'm guessing there's a filefield on your users, and some of these have lost part of their data for reasons I don't understand. (The same thing happened to me once during a faulty export-from-one-site-and-import-to-another).

Why the process can be "forced" by repetition I don't understand, but close inspection of the user entity and any fields that could have a 'uri' key, both through devel and the raw data in the DB, should reveal what the source of the problem is.


Select list of node titles for a view exposed filter I want to create an exposed filter based on the title of a node. How do I do this? I would prefer this filter be a select list - that is, all of the node names are listed based on the criteria I list.

So let's say you have three titles for events:

A Trip to the Woods

Go to the Beach

Off to the Farm

I would like the exposed filter to be a select list of these three nodes.

Look into the Finder module in addition to creating a View Page.

From the Finder module project description:

  Typically Finder is used for these purposes:

  As a search tool to find a group of nodes or users.
  As a way to navigate to a specific node or user page that matches criteria.
  As an alternative to exposed filters for a Views module display.

  Specific example uses of Finder:

  An autocomplete search on node titles in order to find a node.
  A select list of all the possible values for a particular content field
  in order to get a list of corresponding nodes.
  Multiple groups of radio buttons and checkboxes with taxonomy terms to find nodes that match all the selected terms.
  An autocomplete search on usernames in order to go to a user profile.
  A multi-step wizard form to whittle down a pool of potential results by asking questions on one step that will reduce the possible answers on the next step.

Finder should be able to pick and choice, or filter, what shows up in the that Select list.


Conditional Fields is not working I m using Conditional Fields for Drupal 7 to create country state relational dropdown in my Field Collection module, but it is not working properly.

I created Country US and Canada and, depending upon those, US States and Canadian States; I created the relation, but in the front end all the drop-downs are shown.

Can anyone suggest me what I am doing wrong? If this module does not work, how do I create a country state relational dropdown in my Field Collection?

The other option to try is a custom form alter and add the #states key to those fields. This is a code only, no ui approach, but it should work just as well for what you are looking to accomplish.

Here is an article that describes how to use #states. http://randyfay.com/states


How to change "Add new node" button label? I have created two content types "A" and "B".
I have included content type "B" in content type "A".
So when I am adding a content of type "A" that time it shows me a button "Add new node".
I want to change this label with another label.
Also when I click on this button it display form with fields of content type "B". This also shows a button with label "Create Node" and a title "ADD NEW NODE". I also want to replace with another string.
I have used form_alter() hook.

Can any one guide me how can do this?

I suggest you take a small form_alter sample module code and start changing in it. Pl also see this video.

You can also do it easily using String Overrides module.


Token replacement pattern for triggered rules on node creation I am currently using triggered rules to send notifications whenever a certain node type is created (by anonymous, unauthenticated users). In the email notification sent I would like to include some of the content submitted in the form but I cannot find any of the replacements tokens when editing the ruleset for the event.

Right now, the token replacement patters for Form and for Form State are listed as empty.

How can I get hold of the relevant replacement tokens for the Form content?

Is there any modules that are capable of sending similar notifications (with node/Form content) upon node creation?

I am using Drupal 6.20, Rules 6.x-1.4, Token 6.x-1.15, CCK 6x.2.9

This should be possible with the the above modules.

You do not need to get data from the form/form_state.

I'm assuming the data you want is from a cck field because you're sending the email when a new node is created.

Rules has the "Replacement patterns for saved content" field set for pattens.

In there there's going to be cck specific token replacements. You can use those cck tokens to get the data you want.

These replacement tokens will look like [node:field_name_of_your_field-formatted]

Also make sure you're using the "After saving new content" event.


How to create a form on a new page? I'm new to Drupal. What I'd like to do is create a form on a new page, having full control over the css/html of the form, and post the form to PHP for processing. The PHP should do some custom things to the form data, dump some stuff to the DB, return some stuff from the DB, and either redirect to a new page or return an error. No need to go into details about the PHP/DB stuff - just need to figure out how to go about creating a new page, and where to post the form to for processing. Should be able to figure everything else out from there!

To create a form on a page you need to use Drupal's Form API. It seems a bit complex at the first sight, but it isn't as it seems.

The steps you need to follow:

Create a custom module
Implement hook_menu() in your module and set a path for your page which should render the form.
A form builder function that builds a form using the Form API.

An Example for hook_menu() implementation:

function YOURMODULE_menu() {
  $items['some/path'] = array(
    'title' => 'My page title',
    'description' => 'An example page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_example_form'),
  );
  return $items;
}

This code registers a paths as http://example.com/some/path and calls drupal_get_form() function, which gets a form with the given id, which in this example is YOURMODULE_example_form.

An example for the form builder function:

function YOURMODULE_example_form($form, &$form_state) {
  $form['some_text_field'] = array(
    '#title' => t('Enter some text'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send form'),
  );

  return $form;
}


Use Display Suite token field in custom block type template I have a custom block type, which uses its own theme template.
I have a display suite token field link_card_edit_block
It just uses HTML and tokens to create a link.
I want to use that field in my block type template.
Without the custom template, the field shows up.
If I add {{ content }} in the custom block template, the field shows.
But I can't figure out how show that field individually.

Here is what I have tried:

{{ content['#block_content'].field_link_card_edit_block.value }}
{{ content['#block_content'].field_link_card_edit_block[0] }}
{{ content['#block_content'].field_link_card_edit_block }}
{{ content.field_link_card_edit_block.value }}
{{ content.field_link_card_edit_block[0] }}
{{ content.field_link_card_edit_block }}

All of them produce nothing.

My teammate figured this out:

{{ content['dynamic_token_field:block_content-link_card_edit_block'] }}


How to inculde 3d parrty libraries into your module? I am using the 3d party php library, and I do not know how to connect. The file structure of my project looks like following:

-my_project
--src
---Plugin
----Action
-----MyAction.php
---libs
----mylibs
-----src
------ClassWhichINeed.php

--my_project.info.yml

So I need to connect ClassWhichINeed.php to MyAction.php.
In ClassWhichINeed.php I specified namespace as Drupal\my_project\mylibs;

And in MyAction.php i use Drupal\my_project\mylibs;

But when I create
$object = new ClassWhichINeed;

I get an error "Undefiened class"

suggestion:

in MyAction.php add:

require_once DRUPAL_ROOT . '/modules/my_project/src/libs/mylibs/src/ClassWhichINeed.php';


How do I setup multiple sites with one database in Drupal 7 My hosting provider limits the number of databases.  I would like to setup several small sites with their own theme, modules, etc.  The scripting for setting up drupal sites from my host provider uses simplescripts.com but when I go to do an install, only Drupal 5 has the table prefix option.  Drupal 6 and 7 installs do not allow the table prefix.

I found this good reference, but it wasn't explicit as to whether or not the Drupal version mattered.  How do I get Drupal to use table prefixes so I can install multiple drupal installations in the same database schema?

I guess I don't see how to add the table prefixes to a particular install after the simplescripts.com has made the initial installation.

Is it even possible to setup multiple sites in Drupal 7 using one database? If so, is it a matter of using the simplescripts.com to install the files and then moving the installed files to the location I need them to be in? or must I install Drupal 7 manually for each site?

Yes it is possible to setup a multiple sites in Drupal 7 using one database.

All though its not optimale. compared to the other option to run it in different databases.

Drupal multiple sites tutorial

Complete tutorial on setting up sites in Drupal 7

Hope it helps :)


Read time value of node in view I am using Read time module for calculating the read time for each node. Value is getting inserted in the database table correctly. But I didn't get an idea about how can I get this value in view. Because I want to show this in a article list view. ie each article's read time in its card.

How can I achieve this?

You need a patch that hasn't been merged yet.

Issue is here - https://www.drupal.org/project/read_time/issues/2819071

The patch was created here -  https://www.drupal.org/project/read_time/issues/2819071#comment-13416093
You need anther module, so read that ^

In case you haven't applied a patch before, here's the link to the documentation on drupal.org about it. https://www.drupal.org/patch/apply

--

Another option, change your view from Fields to Content. Add a view mode to your content type if you need to with only the fields you need.


User defined domains how can I create a user defined domain?
E.g. user one will select for his shop the domain "shop1.example.com".
User two will select "shop2.example.com" etc.
How can I do this?I was thinking of Domain Access module but I am not sure which submodule to use.
thanks

Drupal can handle multiple sites very well. In a raw way without any modules you can use the multisite features of drupal. This can be done by creating submodules under sites for each of the sites.

When it comes to modules there are couple of them that deals with subdomains and multiple sites.

Virtual Sites
This kind of automates the Multisite configuration for drupal. You can create additional domains and subdomains.
Subdomain
This one is mainly used to create a subdomain and place contents under that subdomains. For example all contents of a group can be placed under the groups subdomain.
Domain Access
Domain access is used in scenarios where you want to share contents between your domains and subdomains. You can assign contents specific to a domain or have the same content appear in multiple domains. Assign admins per domain etc. This is used for affiliates sites. A use case would be a main rental site with subdomains for each city.
Aegir
This is not a module. This is a complete hosting solution build for drupal. This is a hosting profile. You would install it on a dedicated or virtual servers. You can create multiple sites from with in Aegir some thing similar to what you do on a reseller control panel. If you want to restrict the subdomains to a single domain then you can use the module Hosting Subdomains

So it ultimately depends on your use case.


Different view page based on taxonomy depth? I'm wondering if there is a way to show a different view (or view part) based on the current depth of the term level?

Example I have a bunch of categories and subcategories. For the categories I want to show a page that is just the name of the category, once I go in to the next level (subcategories) I want the name and the image and description or whatever you have.

Is there anyway to do this? I have a page view that is mapped to category/% so we would get category/% ** CATEGORY */% * SUB CATEGORY **

if you know the depth of the category in advance you could create different view page for each depth of the category.

For example for the main category the path would be category/%
and for the subcategory the path would be category/%/%

this way when there is 1 argument after category the view page for the main category would be displayed. If there are two arguments the view page for the sub category would be displayed.


How to add a join to hook_query_alter I want to use hook_query_TAG_alter() for search system so I use mymodule_search_query_search_node_alter(QueryAlterableInterface $query).

What I want to essentially do is make sure that when a calendar_item, node type, is one of the results, to make sure that it's field field_date_value2 (this is the field that determines how long a calendar event or calendar item is valid, each calendar event starts at a certain date - field_date_value and ends at a particular date - field_date_value2) is greater than the current date.

So I imagine it would look something like:

function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'the_date');
    $query->fields('field_data_field_date', 'field_date_value2');
}

Now I am not adding a $query->condition(...); because this causes issues alone! I just need to know how to get in there and add the field to the query, then add a condition to that field's value!

Anyone able to steer me in the right direction? Please and thank you!

EDIT #1:
You got me to where I needed to be! Thank you very much!! I have one more follow up question, if you do not mind.

The system search will find any node that has "Training" in it. This is great, but the nodes that are of type calendar_item, I want to make sure the aformentioned TO field (field_date_value2) has a date older than current. I have modified my code above.

function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
     $u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
     $query->fields('fd', array('field_date_value2'));
     $query->condition("{fd}.field_date_value2", '2016-02-17T21:30:00', '>=');
}

My issue with my code above makes it so that it applies to all results, so I only grab calendar_items, I still want to grab everything, just if it is a calendar_item, to do the exclusion. I must need an outer Join?

Your query is a bit different compared to a regular query. A regular query is constructed like this (source):

$query = db_select('users', 'u');
$query->join('domain_editor', 'de', 'u.uid = de.uid');
$query->fields('u', array('name'))
  ->condition('u.name', '%' . db_like('john') . '%', 'LIKE')
  ->condition('de.domain_id', 25, '=')
  ->range(0, 20);
$result = $query->execute();

You have the base query:

$query = db_select('users', 'u');
$query = db_select($table, $alias);

Then the join:

$query->join('domain_editor', 'de', 'u.uid = de.uid');
$query->join($table, $alias, $condistion);

The fields to select:

$query->fields('u', array('name'))
$query->fields($table, array $fields)

And the conditions:

  ->condition('u.name', '%' . db_like('john') . '%', 'LIKE')
  ->condition($field, $value, $operator)

In your code it seems you did not take the table aliases into account. So you might want to try something like:

function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'fd', 'search.date = fd.field_date_value'); // No idea what the field is called, assuming 'search.date'.
    $query->fields('fd', array('field_date_value2'));
}

(You'll need to figure out what the name is of the field you want to join with, and substitute 'search.date' with that value.)


System emails translation I wanted to translate emails sent to users after signing up using different language than English. I know there is a way to translate the system emails from the account settings translate tab, so I added the translations as you can see in this picture.

This didn't work. Maybe this is not enough. I tested it (registering a new account using Arabic) and it is not working: The system emails are still sent in English.

Does Drupal send emails according to user's preferred language? If yes, how can Drupal send registration email in a language that is not English?

Here is the steps to get user email in your language (describing all the steps in case you missed any)

Default installation of Drupal 8

Enable translation module (core modules)

Configuration Translation
Content Translation
Interface Translation
Language

add your language visiting

/admin/config/regional/language
in my example added Greek with Language code el

translate emails visiting

admin/config/people/accounts/translate
and pressing edit on your language
which in my example would be take me to this page
admin/config/people/accounts/translate/el/edit

add language switcher block (optional)

so you can switch to appropriate language

visit registration form for your language

in my case /el/user/register
and fill out the form

The email should come in the registration language

It came in Greek in my test.