Passing an object to hook_menu I am trying to pass an object from a function to the menu item (Not sure if drupal allows that), I get the following error 'Recoverable fatal error:Object of class stdClass could not be converted to string'. The following is my function and the menu item.

function add2basket_link($val) {
  $build = array();
  $build['add2basket_link'] = array(
  '#type' => 'link',
  '#title' => t('Bucket'),
   '#href' => 'basket/add/'.$val. '/nojs/',
  );
  return render($build);
  }

 function bucket_menu(){
   $items['basket/add/%'] = array(
   'page callback' => 'data_add2basket',
   'page arguments' => array(2),
   'access arguments' => array('use basket'),
   'type' => MENU_CALLBACK,
   'file' => 'data.inc',
   );
  return $items;
 }

The error points to the line of " '#href' => 'basket/add/'.$val. '/nojs/', " from the add2basket_link function

You could concat only string with strings, It's php :)
What you can do is to use hook_load() something like this:

function add2basket_link($val) {
  $build = array();
  $build['add2basket_link'] = array(
    '#type' => 'link',
    '#title' => t('Bucket'),
    '#href' => 'basket/add/'. $val->lid . '/nojs/',
  );
  return render($build);
}

/**
 * Implements hook_menu().
 */
function bucket_menu(){
  $items['basket/add/%bucket_link_id'] = array(
    'page callback' => 'data_add2basket',
    'page arguments' => array(2),
    'access arguments' => array('use basket'),
    'type' => MENU_CALLBACK,
    'file' => 'data.inc',
  );
  return $items;
}

/**
 * Implements hook_load().
 */
function bucket_link_id_load($lid) {
  // 'bucket_link_id' is from hook_menu() from $items['basket/add/%bucket_link_id'].
  // lid is id that was passed from add2basket_link() to the #href.
  // link_load() is function to load your object.
  return link_load($lid);
}


Change the expiry time for welcome user notification message Is there any way to change the expiry time for the welcome message sent after an administrator user created a new account for a user? By default, the login link included in the email is valid for a day, and I would like it to last seven days.

In Drupal 7:
Set user_password_reset_timeout variable (i.e. in settings.php, or strongarm):
i.e. in settings.php:

$conf['user_password_reset_timeout'] = '604800';

source : https://www.drupal.org/node/246029


Is it okay to use drupal_goto() from within a node? I implemented a node that automatically adds a product to a cart using this function uc_cart_add_item(33);

but I want it to then redirect the visitor to the check out page.  I saw that drupal has a drupal_goto() function however this is essentially just a php Header(location: http://mysite.com/cart/checkout)  which usually shouldn't work if it is not done so before any content is spit out.

Now I got this to work and everything but I never liked the idea of just getting it to work, I'd like to get it right.  I thought of a script outside of the drupal environment but wasnt sure if I could use the ubercarts functions.  Does anyone have any ideas on a better way or is the using drupal_goto() within a node okay?

Just to say and I saw someone else who had a similar problem was that this did work, however the cron job time exceeded the time limit after I implemented this.  SO maybe not a good option like i thought.

It is a bad idea and I wouldn't recommend doing it.  The cron error you see is most likely due to the Search module. During cron while the Search module is trying to index content, if it reaches a node containing a drupal_goto() it will hang and cron will error which could lead to more problems


Set a date programmatically Once a page is saved I want to put the current time (I know I can do it by the form, but I need to do it programmatically). My code:

function mymodule_node_presave(EntityInterface $entity) {
    $node_type = $entity->bundle();
    if ($node_type === 'page') {
            $date = date('Y-m-d 00:00:00', time());
            $entity->field_mydate->value = $date;
            $entity->body = $date;
       }
}

It changes the body correctly but not the date field.
I tried all those, none works. I can't understand where is the problem.

Solved the issue.
In my case, after debugging the value, I guessed the right code could be:

$date = date('Y-m-d\T00:00:00', time());

And it is. I'm not sure what the date format depends on. For sure it doesn't depends on the form display format since in the I'm using the Italian one (d/m/Y).


create a custom field schema When I create a new field programmatically, drupal create a default schema for my being added and for each new field added is create a new database schema.
I noticed that the columns always have the same structure except for the last column 'FIELD_NAME_value'.

entity_type | bundle | delete | entity_id | revision_id | language | delta | FIELD_NAME_value

I have many fields that have the same "entity_type" and "bundle".

Can I create programmatically a single schema that contains all of them?

Thanks!

No, it won't be recognized by Field API. By default Drupal uses Field Api and Field Storage API to store field data. It creates two tables for every new field which you create from Field UI (field_data_* and field_revision_*). If you are able to create your own Storage for Field Api then you can use it... Here are some resources:

Field Storage API
Useful discussion


How to the set permission of content types for a specific user role? How to set the permission of content types for a specific user role?

If you want to set permission from admin panel then goto /admin/people/permission after find your content (view/edit) and set the user role (anonymous/ Authenticated/ Administration) permission. but if you want to set it problematically then visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/theme-product  (Drupal 7 - A Simple Content Type: Permissions & Access)


How to print Blocks in commerce-product.html.twig I am looking at building a Drupal 8 Commerce 2 product display through twig but I am having issues with how to print custom blocks in this template file. (And also testing these in normal page.html.twig as well)

Looking at the Custom Block Library (/admin/structure/block/block-content) I can see that the ID is '4', as the ID from the Edit URL is 4. (http://www.example.com/block/4)

I have installed the module Twig Tweak and tried all the combinations below in the commerce-product.html.twig, and each time I get a WSOD

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

{{ drupal_entity('block_content', 4) }}

{{ drupal_entity('block_content', '4') }}

{{ drupal_block('block_content:4') }}

{{ drupal_entity('block', 4) }}

{{ drupal_entity('block', '4') }}

I have also tried in my example.theme file:

function theme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('4');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
 $variables['productinfo'] = $block_content;
}

Then in *.html.twig with lots of cache flushing before and after:

{{ productinfo }}

I also seam to be not even able to use any of the examples from the Twig Tweak Cheat Sheet, as each one of these I add to my any *.html.twig I get the WSOD.

{{ drupal_view('who_s_new', 'block_1') }}

or

{{ drupal_region('sidebar_first') }}

Question:
How do I print custom blocks into a commerce-product.html.twig template?

You can use hook_preprocess_commerce_product to load the block and pass the variable to your twig file.

function YOURTHEME_preprocess_commerce_product(array &$variables) {
  $block = \Drupal\block_content\Entity\BlockContent::load(4);
  $variables['custom_block'] = \Drupal::entityTypeManager()->
    getViewBuilder('block_content')->view($block);
}

and then in your twig file you will have the {{ custom_block }} variable set.

On a sidenote, this answer helps a lot when trying to programatically load blocks.


Add CSS file to certain pages only with theme.info file? If I want to add a CSS file to certain pages only I know how to do this with the drupal_add_css function in the template.php file, but can you also do it with the theme.info file? Or is the theme.info only for adding CSS files globally?

I think it only globally, you should do it the the preprocess page instead.


How can I pass page variable to a form builder function in a custom module? I have an entity page where the entity has an email field. On that page, there is a form built in a custom module. What I'd like to to is that on form submit, the module sends an email to the address that is the value in the entity field.

So somehow I need to pass that email address to the form submit function.

What is the best way of doing this?

One way is to put either the e-mail or an ID referencing the e-mail (the NID of the node where it is stored for example) as a hidden field, which will be received by your submit handler hook.

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#hidden


Hide or remove the "Remove" button, "Quantity" box, and Price for specific product/SKU on cart page of Ubercart I have a zero-dollar product that, once added to the cart, should never be removed until checkout is completed. Currently, that product has the "Remove" button, "Quantity" field, and Price that all products are displayed with in the cart. How can I remove those three items just for this one product/SKU?

Thanks!

You could achive this with hook_form_alter() and hide the field with $form['field_name']['#access'] = FALSE;


How do you message/email the purchaser an order update? Previously in ubercart 3.x you were able to send messages and log admin notes on each order page. How can this be done using Drupal Commerce? I want to be able to message the purchaser in the order invoice page and also add internal notes if necessary. Which module(s) would I need to achieve this? Can you provide a screenshot of it in action?

Since Drupal Commerce is based on the Rules module, you can simple create a custom rule which watches order status and react when one is changed.

Assuming you have Rules UI enabled you can go to: admin/config/workflow/rules/reaction/import

Here is a simple Rule which you can import:

{"rules_admin_order_update" : {
    "LABEL" : "Admin order update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "commerce-order:status" ],
          "value" : [ "commerce-order-unchanged:status" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "admin@domain.dk",
          "subject" : "Update",
          "message" : "The order changed to [commerce-order:status-title]."
        }
      }
    ]
  }
}

You can then change the add more info, change parameters etc.

Hope this can get you going. :)


How to include data-url-encode data using drupal_http_request()? I am attempting to make a GET request using drupal_http_request(). A basic request works as expected but I need to include extra data. The example provided to me uses curl and the -G --data-urlencode option as shown below. What is the correct way to implement this type of request using drupal_http_request()?

curl -X GET \
  -H "Header-Example: Header Data" \
  -G \
  --data-urlencode 'include=gator' \
  https://example.com/1/endpoint

--data-urlencode just appends ?foo=bar to the end of the URL (encoded of course); drupal_http_request() has no special handling for query strings, it parses them directly from the provided URL with parse_url().

That said, this would be functionally equivalent:

$data = drupal_http_build_query(array('include' => 'gator'));
$url = 'https://example.com/1/endpoint?' . $data;
drupal_http_request($url);

Request from Drupal:

GET /1/endpoint?include=gator HTTP/1.0
User-Agent: Drupal (+http://drupal.org/)
Host: example.com

Request from cURL:

GET /1/endpoint?include=gator HTTP/1.1
User-Agent: curl/7.30.0
Host: example.com


login redirect for anonymous users I would like my homepage to seen by every user. But anonymous users should be redirected to a login page if they click on any link.  How can I achieve this?

There are many specific ways to do this, but here's the general idea:

Create a special content type for your home page that allows Anonymous access.

Then, set your other content types to require an authenticated user.

If you get stuck on a specific part of this process, or have more specific questions you may get better responses.


Entity token availabe in Rules but non-functional I'm building a submission-review page where submitters select a reviewer. Submissions show up on reviewers profile page and have accept and decline buttons implemented with Button Field module. When the reviewer clicks the accept button, he gets redirected to a new review content form.

Review content type has a node reference field to submission content type which should get populated automatically using Node Reference URL Widget.

I use the Rules module to check if accept button has been clicked and to fire the Page redirect action:

After defining condition Entity is of type Node replacement patterns show up and seem to be available:

So I fill URL to redirect to with the relative url and the entity id:

node/add/review/[entity:nid]

But it doesn't have effect. Rule gets fired correctly but [entity:nid] is empty and reviewer gets redirected to node/add/review/ and so node id to prepopulate node reference field is not available.

Am I doing something wrong or is it a bug in Button Field? Any hints to implement that funcionality in a different way?

I'm not familiar with using the Button Field module in combination with the Rules module.

But from your question details, it seems that the entity:nid value is indeed blank. A possible solution is typically to add a Rules Action which is either of these:

"Fetch entity by ID" (if you know the ID you're processing).
"Fetch entity by Property" (if you have some criteria to build a list of things to be processed in a subsequent Rules Loop).

Especially the "Fetch entity by ID" is what I think you should give it a try. Also because of what's written in Comment nr 3 of issue nr 1796952, and which has some pseudo code like so:

event : on User clicks a button field
condition: Entity is of type on entity (make sure everything is in scope of rule)
actions:

Fetch entity by id with ID (data selector) : entity:nid
pump the 'fetched entity' into a component and do things in there

If none of the above helps, then the "Submissions show up on reviewers profile page" part of your question is something that may help to use a completely different approach. If that's something like a Views result" (is it?), then you could maybe use either of these approaches:

Add a Rules Action to load a list the list of results created via a VBO enabled view.
Use the Views Rules module to have each row of that view processed via Rules, whereas you can make each column of such view available as a rules token, so if that "nid" is included in it, you have what you're looking for.

If none of the above help, You may want to use Rules debugging (eg to display values of relevant things using the Devel module, so that you can (temporary) add a Rules Action like "Display a value".
For more suggestions about that, refer to  "How can I display the value of a variable inside a condition?".

PS: those 2 AND Rules Conditions are not needed in your case (that's the default of how Rules combines multiole Rules Conditions).


Add a style (CSS) to a custom block I've created a custom Block in Drupal 8 from the UI.

Is there a way to add a custom CSS style to this custom block?
Is it possible, like in Views, to click on CSS and type it in?

Easiest way to add a custom class to a block would be to override the default block.twig.html twig template within your theme.

You'll need to copy the above file from /core/themes/stable/templates/block into your custom theme using the same directory structure.

**  NB don't edit the file found in core directly!! This is bad practice and you'll lose any changes when you upgrade Drupal core. **

Clear the cache and you should now be able to edit the block template file and customize it.

Then, to load CSS, you must define an asset library. You can then load that asset library using {{ attach_library('mytheme/special-block') }} in your Twig template (assuming the theme is called mytheme and the asset library special-block).

Helpful links:

Working with Twig templates
Template naming conventions
Debugging Twig templates
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


How to generate iframe from Drupal 7 view (custom blog) with security token? I have a Drupal 7 site with a custom blog created with custom content types and a combination of views. I need to be able to export this blog as an iframe with a "long security token" to be used on a Salesforce site. I have read about several modules that can generate iframes, but I'm not sure how to go about the security side of things. Any suggestions? I've looked into the Entity Iframe project, and this seems to do what I want for individual nodes, but I'm not sure how to do this for the whole view/page.

A more involved alternative can be found here Drupal Iframe Widgets but this doesn't deal with the security side of things.

So, my questions remains: what's the best/easiest way to export a view to another site with a security token?

If you add ?entity_iframe to the url it will trigger the iframe theme. Entity iframe resize has examples of how to do cross domain communications (assuming sub-domains) securely and with less complexity then the provider / consumer handshake via the PostMessage capability built into browsers (http://caniuse.com/#search=postmessage)


Notify users of new logged heartbeat activity I am using Heartbeat module for a notification system, I've created a pop up block which shows all the logged activity targeted to a certain user. Is there a way to alert the targeted users of new logged activities.

For example, like the notifications on Facebook or twitter?

Any help would be greatly appreciated.

Try to use Notify or Notifications module. I think from these modules you can solve your query.


Check if page view is example node/page I'm having some trouble trying to put an if else statement into my "page.tpl.php". I don't remember (I did it in the past), how to check something like that,  but with some other page for example "www.example.com/home-2" or www.example.com/info . In my case is a page view, I would really appreciate any help you can provide.

Well if I understand you right...

In template.php

function mytheme_preprocess_page(&$variables) {
  $node = menu_get_object('node');

  if (isset($node) {
    $variables['node_type'] = $node->type;
  }
}

In page.tpl.php

<?php if ($node_type == 'your_type') : ?>
  // something here for node type your_type
<?php endif; ?>

Additionally, you can simply add new template suggestions.

In template.php

function mytheme_preprocess_page(&$variables) {
  $node = menu_get_object('node');

  if (isset($node)) {
    $variables['node_type'] = $node->type;
    $variables['theme_hook_suggestions'][] = 'page__node__' . $node->type;
  }
}

After clearing your cache, you can create page--node--(node_type).tpl.php and put page specific markup for that node type there.


How do I alter the file link of an uploaded image in edit/create node form? When I upload an image in drupal, a file icon and a file name that links it to original file is created.

For example, I upload "foo.jpg" then

 foo.jpg

is generated.

I want to change the path-to-file url because it's put putting base_url() + path-to-file which results in Not Found. I'm using amazon s3 for file storage.

I only want the path-to-file url without the base_url. Can anyone share some wisdom?

You could try implementing your own theme_file_link.

  Returns HTML for a link to a file.

  Parameters

  $variables: An associative array containing:

  file: A file object to which the link will be created. icon_directory:
  (optional) A path to a directory of icons to be used for files.
  Defaults to the value of the "file_icon_directory" variable.

Put this into your theme's template.php file:

function MYTHEME_file_link($variables){
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '' . $icon . ' ' . l($link_text, $url, $options) . '';
}

Clear the cache, and then modify the code.

I would also investigate Amazon S3 Stream Wrapper


How ajax framework in D7 forms work? I am trying to understand and get the example working that was discussed here http://api.drupal.org/api/drupal/includes--ajax.inc/group/ajax

I understand the form building function.

function ajax_example_simplest($form, &$form_state) {
    $form = array();
    $form['changethis'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      'callback' => 'ajax_example_simplest_callback',
      'wrapper' => 'replace_textfield_div',
    ),
    );

    // This entire form element will be replaced with an updated value.
    $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
    '#description' => t("Say something about why you chose") . "'" .
    (!empty($form_state['values']['changethis'])
    ? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
    '#prefix' => '
',
    '#suffix' => '
',
    );
    return $form;
}

What I don't understand is what is happening in ajax callback function.

function ajax_example_simplest_callback($form, $form_state) {
    // The form has already been submitted and updated. We can return the replaced
    // item as it is.
    return $form['replace_textfield'];
}

The same form field is returned. I thought we can change the value or something for the form item $form['replace_textfield'] through ajax callback function. Can some one pls help me to explain this part?

All ajax logic placed in construct form function (ajax_example_simplest), ajax callback just return part of form (replace_textfield) or ajax commands. Its Drupal architecture. This form can be validate and altering.


drupal 6 status report, automate via drush? We run around 100 drupal sites, and I want to automate a weekly check that will scan all of the admin/performance/status report pages. I had a look at drush status and it doesn't give me the same information as the web interface does.

Has anyone done this and how did you go about it? Ideally I want to just email weekly to the dev team if there is an alert on any particular site

If you want to use drush, drush -n up will show the available module updates.

Getting the status report (really "requirements" from the API's perspective) is a bit more convoluted, and can be output with

drush php-eval 'include_once DRUPAL_ROOT . "/includes/install.inc"; drupal_load_updates(); print_r(module_invoke_all("requirements", "runtime"))'

Other options are Nagios, Update Status Aggregator, Droptor, or the Acquia Network.


Recieving error: Fatal error: Class 'panels_renderer_standard' not found in I recently migrated a site from a Drupal 6 install to a fresh Drupal 7 install.

I then installed panels 7.x-3.5.
Initially I had an older version of ctools installed, so I had to upgrade from 7.x-1.4 to ctools 7.x-1.6.

I then enabled panels the panels page is not showing up in "Structure". I checked permissions and all the correct permissions have been added.

I then try to flush my cache, and i get this error:

Fatal error: Class 'panels_renderer_standard' not found in C:\wamp\www\projects\elaw\sites\all\modules\panels\plugins\display_renderers\panels_renderer_editor.class.php on line 8

Here is a picture of the error with a full stack trace:

I can run cron just fine, but trying to clear the cache gives that error.
In the modules page "Panels" is enabled.

Before upgrading ctools, I had saved a files/database copy and then tried removing panels from "modules" and adding Panels 3.4 instead.  I got the same error.
I then restored my files and database and tried it again but with upgrading ctools instead as mentioned above.

There was also this error that briefly flashed up when I was enabling the module from the "modules" page, after the ctools upgrade.

********UPDATE*********

I was able to get the cache to clear by just hitting reload.  But, if after the cache clears I try to clear the cache I get the same error.
Now the "panels" shows up in Management->Structure, but it has a strange error on the top of the page:

Notice: Undefined index: rows in page_manager_panels_dashboard_blocks() (line 1251 of C:\wamp\www\projects\elaw\sites\all\modules\ctools\page_manager\page_manager.module).
Warning: Invalid argument supplied for foreach() in page_manager_panels_dashboard_blocks() (line 1251 of C:\wamp\www\projects\elaw\sites\all\modules\ctools\page_manager\page_manager.module).

Notice how none of the predefined panel pages are showing up?

I hit clear cache a couple more times (with it giving the "class panels_renderer_standard not found bug each time I cleared the cache initially and it clearing after I hit reload),
and now the panels page is showing the Predefined  Panel Pages, (user page, etc):

I tried creating a new panel page and got this bug:

I can't seem to create a new panel page.

****END UPDATE*****

************************S E C O N D   U P D A T E*****************

I had an idea that perhaps it was a contributed module that was causing the error.  I was going to just randomly start disabling contributed modules but I thought I would start with any contributed module that had ANYTHING to do with panels.
I found that disabling "Panels Translation" in the "Internationalization" section fixes the problem.

I'm not sure why this was causing the problem, but after disabling it I no longer get the " Fatal error: Class 'panels_renderer_standard' not found" error.
I am also able to get further in creating new panel pages.
I get all the way up to saving and it gives this error:

I have verified that that table is not in the database....

I am on a very tight deadline and would appreciate anyone's insight.
Thanks very much for any help.

Sincerely,

David

Check your modules/panels/plugins/display_renderers folder and make sure there is a file named panels_renderer_standard.class.php inside, that's where the class is contained that is supposedly missing.

Try completely replacing the panels module code with a fresh download, that is: move the current module folder somewhere else (so you can get it again if you need to) and re-upload the module.

If you're applying any patches, make sure you check them for code that might be deleting, renaming, or disabling the display_renderer_standard class.


HTTP error 500 when backup entire site Using Backup and Migrate module on a D7 site

separate backups (data / files) give no problem (backup to nodesquirrel AND download)
but backup entire site (data + files) generates "http error 500" (without "internal server error")

Error reporting

I have no access to Apache error log
Cpanel error: no error messages
Drupal error log: no error messages

Shared hosting | db 10.1.21-MariaDB | php 5.6.30 | drupal 7.53 | backup and migrate 7.x-3.1 | civicrm 7.x-4.7.14

[update]

The web host provider received next message:

 Uncaught exception 'PDOException'
 with message 'SQLSTATE[HY000]:
 General error: 2006 MySQL server has gone away'
 in <drupal root>/includes/database/database.inc:2227
 Stack trace:
 #0 /includes/database/database.inc(2227): PDOStatement->execute(Array)
 #1 /includes/database/database.inc(697): DatabaseStatementBase->execute(Array,  Array)
 #2 /includes/database/database.inc(2406): DatabaseConnection->query('SELECT expire, ...', Array, Array)
 #3 /includes/lock.inc(167): db_query('SELECT expire, ...', Array)
 #4 /includes/lock.inc(146): lock_may_be_available('schema:runtime:...')
 #5 /includes/bootstrap.inc(433): lock_acquire('schema:runtime:...')
 #6 /includes/bootstrap.inc(455): DrupalCacheArray->set(Array)
 #7 [internal function]: DrupalCacheArray->__destruct()
 #8 {main} in <drupal root>/includes/database/database.inc on line 2227

This is your error:

General error: 2006 MySQL server has gone away

You can try to fix this in two ways:

my.ini

Open your my.ini file and locate max_allowed_packet. By default this is 1M. Setting it to 16M and restart your MySQL server. If the problem persists, try setting it to 512M and restart your MySQL server.

MySQL prompt

Enter your MySQL prompt, log in as user root or as a user with the SUPER privilege. Run the following command:

SET GLOBAL max_allowed_packet = 1024 * 1024 * 512;

This method doesn't require you to restart the server.


How can I use a Twig if statement in a View rewrite How can I add a Views field rewrite using Twig that will display the moderation state only if the node is in draft state or review state? I tried the code below but it prints all of the moderation states.

{{ title_1 }}
{% if field.moderation_state == 'draft' %}Draft{% endif %}

This is how my list of titles look:

page1 Draft
page2 Published
page3 Submitted

I want all of the page titles to always display. I never want Published to display. So I want to first check if the moderation state is equal to draft and review.

I also tried variations like this

{% if moderation_state__value == 'draft' %}

Below are the available replacement pattters

   {{ moderation_state }} == Moderation state
   {{ path }} == Link to Content
   {{ title_1 }} == Title
   {{ title_1__value }} == Raw value
   {{ arguments.nid }} == Content: ID title
   {{ raw_arguments.nid }} == Content: ID input

You don't need to strip HTML tags. This works for me:
{% if field_tags == "green" %}
   GREEN
{% else %}
   NOT GREEN
{% endif %}

where field_tags is a taxonomy reference field with "Link label to the referenced entity" disabled.


How to edit how Commerce outputs the Billing and Shipping information in the checkout review table? Drupal Commerce on the Review page of the checkout process (e.g. checkout/4/review) by default outputs billing and shipping information above each other in a table, with each line as a different <tr> row containing one table cell:

I'm trying to re-theme this such that it's responsive and has the two addresses side-by-side on wider breakpoints. I know how to code that HTML, my problem is, how to get my HTML into the Commerce page template?

There's no corresponding tpl file I can find anywhere in the Commerce module, and other answers linked below seem to confirm there isn't one
I can't find a corresponding View to edit
I've read theming checkout pages in Drupal commerce, where an answer suggests creating a file page--checkout--review.tpl.php - but no such file exists already, and I don't want to recreate the template from scratch and potentially miss some important subtlety from the logic of the original, I want to read, understand and then edit the original.
The answer to Customize drupal commerce checkout page doesn't offer the HTML control I need, likewise How to theme checkout completion page in Drupal Commerce. I know I can edit the form array using hooks, but I can't use hooks to make the fine adjustments to the HTML output that I need, removing them from the table to make them responsive.
I wrote the answer to Customize commerce cart form page, which uses a custom module to allow the table to be editted in Views - but this only works for the cart, not checkout

How can I edit (not re-write from scratch) the HTML of the checkout review table?

At time of writing, this isn't a viable solution, but I'm posting it because it might become one, one day.

Commerce Responsive UI module

There's a massive long 5-year-old issue matching my problems theming Commerce checkout in the Commerce issues queue. The "fix" was the creation of a module, Commerce Responsive UI, that aims to modernise the markup of the checkout (and other) pages and make them themable. It sounds like exactly what I'm looking for.

Problem is, there's no stable release, no release at all since November 2015, and it appears to have some serious unresolved issues, like breaking normal cart/checkout page paths. This might become a good answer to the question, but right now it's an unfinished work in progress.


Is a views page an entity? Along with some regular nodes I want to link to a views page with an entity reference field.

Can I reference a views page via an entity reference field?

Can I reference a views page via an entity reference field?

Not out of the box, but you can use the Views reference field module to get that functionality:

  In Drupal 8, Views are now identified as entities and the core Entity Reference Module is able to reference Views, however not Views displays. This module leverages core entity reference module functionality to add the display ID so that a View can be rendered in a field formatter.


How to create nodes "emulating" form submit I usually create and edit nodes, programmatically, using node_load and the node_save, and addind data to fields in this way:

$node->field_custom['lang'][0]['value'] = 'My value';

But in this way I've to check lang, and even if my node is "it" same fields (as terms, or other fields) need "und" and something like this.

Is there way to create and edit nodes loading the form and the submitting the form with new values?

Yep, look at drupal_form_submit.

  Retrieves, populates, and processes a form.
  This function allows you
  to supply values for form elements and submit a form for processing.
  Compare to drupal_get_form(), which also builds and processes a form,
  but does not allow you to supply values.
  There is no return value, but you can check to see if there are errors
  by calling form_get_errors().

// register a new user
$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account');
drupal_form_submit('user_register_form', $form_state);

I find the easiest way to see what the form takes is to use the Net Panel in Firebug. Turn on Persist in Firebug and post your form, then look at the POST keys and values.


RewriteRule causing internal redirect limit error I am trying to server a static HTML site from /sites/default/files/staticsite and make it available via a subdomain. I'm hosting the site on Acquia Cloud, and their docs describe Maintaining a static microsite alongside Drupal's docroot.

This solution is working, with the exception of index.html page (homepage) which returns a 404.

http://subdomain.example.com/ returns a 404
http://subdomain.example.com/index.html success

The setup describe in the docs

I have added the required domain to my Acquia Cloud dashboard so the server will accept requests for the subdomain.

I have updated docroot/.htaccess with the following RewriteRule to redirect requests to the static files. The following rules are the first lines in the .htaccess file.

<IfModule mod_rewrite.c>
  RewriteEngine on
  # Only serve the static site for a particular host.
  RewriteCond %{HTTP_HOST} ^subdomain\.example\.com\.au$ [OR]
  RewriteCond %{HTTP_HOST} ^dev-subdomain\.example\.com\.au$ [OR]
  RewriteCond %{HTTP_HOST} ^stage-subdomain\.example\.com\.au$
  # Don't loop anything targeting the actual mask directory, to allow
  # for linked scripts, stylesheets etc in the static HTML
  RewriteCond %{REQUEST_URI} !^/sites/default/files/staticsite/
  #Any requests that made it this far are served from the /staticsite/ directory
  RewriteRule ^(.*)$ /sites/default/files/staticsite/$1 [PT,L]
</IfModule>

The files have been uploaded to sites/default/files/staticsite

Things I've tried

I thought DirectoryIndex must be disabled for these directories so I tried adding DirectoryIndex index.html in both /sites/default/files and /sites/default/files/staticsite but neither have had an effect.

I tried elevating the DirectoryIndex directive to the top of the existing /sites/default/files/.htaccess file, as well as placing it last. Neither fixed the 404 error.

I've tried removing the /sites/default/files/.htaccess and adding a new .htaccess file with just DirectoryIndex index.html to test if the SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006 was impacting things. No change still got 404.

I've tried adding the [END] flag to the RewriteRule to stop the current rewrite process and subsequent rewrite processes, but still got the 404.

Log entries

When making a request to `http://subdomain.example.com/ I see the following entry in the Apache error log:

  Request exceeded the limit of 10 internal redirects due to probable
  configuration error. Use 'LimitInternalRecursion' to increase the
  limit if necessary. Use 'LogLevel debug' to get a backtrace.

I'm unable to define 'LogLevel` because Acquia Cloud do not provide access to the server config, virtual host, and directory contexts which this directive can be defined in.

Start by getting the base site working at your Drupal domain then slowly add Rewrite rules. First remove everything you've added to the .htaccess files and elsewhere, upload the site to the directory you want and see if you can access it.

http://www.example.com/sites/default/files/staticsite

If that doesn't works then the problem is probably the current .htaccess configuration (docroot or files directory).  If it does work, move on to the next stage.

The next step is to get your custom hostname working. This seems pretty straight forward from the Acquia docs:

RewriteCond %{HTTP_HOST} ^subdomain\.example.com\.com$
# Don't loop anything targeting the actual mask directory, to allow
# for linked scripts, stylesheets etc in the static HTML
RewriteCond %{REQUEST_URI} !^/sites/default/files/staticsite/
# pass-through the matching file from beneath /sites/default/files/ and stop processing
RewriteRule ^(.*)$ /sites/default/files/staticsite/$1 [PT,L]

Important: The above needs to be inserted before the following. If it's not, non-file requests (such as directory index / ) may redirect to index.php instead.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

If that works, start adding the other domains one by one and testing.


How to prevent Migrate from creating null fields? I'm writing some migrations classes using Migrate module. Some of my source fields does not have data for migration but the Migrate module creates Drupal fields with null values anyway. How to prevent that? I only want to create fields if there are non-null values for them.

This comment suggests that it should be enough to just unset field from source row (for example inside prepareRow), but that doesn't work for me - the field with null value is created anyway.

Apparently this feature was added to Migrate 2.6 and for now is available only when you're using dev version. For those who want to try it out, there is RC1 version available.

For older Migrate module versions, the empty field needs to be unset in prepare function, not inside prepareRow as the comment from drupal docs page suggested. Here is an example:

function prepare($entity, $row) {
  // Assuming that 'year' maps to 'field_year'
  if (!isset($row->year) || $row->year === null)
    unset($entity->field_year);

  // Assuming that 'gender' maps to 'field_gender'
  if (!isset($row->gender) || $row->gender === null)
    unset($entity->field_gender);
}

There is also a more "generic" solution prosed in one of the comments on drupal.org (pasting it here for future reference):

/**
 * Removes empty values prior to migrating.
 * @see http://drupal.org/node/1665332
 * @see http://drupal.org/node/1792894
 */
function mymodule_remove_empties($destination, $entity) {
  if ($destination instanceof MigrateDestinationEntity) {
    $entity_type = $destination->getEntityType();
    $form = $form_state = array();
    _field_invoke_default('submit', $entity_type, $entity, $form, $form_state);
  }
}

And in each of your Migrate classes:

public function prepare($entity, stdClass $source_row) {
  mymodule_remove_empties($this->destination, $entity);
}


Updating a drush command from drush 7 to drush 8 what to do if there is a drush command file worked with drush 7 but doesn't work with drush 8. The official docs seem not to have an upgrade guide for this.

Drush makes an attempt to never run any code associated with a module or theme unless that module or theme is enabled. This protection is often more conservative than necessary, as some Drush extensions do not exercise any code that requires a Drupal bootstrap.

None the less, Drush 8 is more rigorous than Drush 7 was. Drush 7 would search for extensions in all of the theme folders regardless of whether the corresponding themes were enabled. Drush 8, on the other hand, ignores extensions stored with disabled themes.

Include paths provided specifically via the --include option are always searched, though; Drush makes no attempt to determine if the specified path happens to correspond to a disabled theme. This is why the workaround you found works.


How to limit the amount of User Points users get? I've a content type 'Content' with the field 'Value' (an integer) and a flag called 'Publish Content and grant points to user'. Every time a Content is flagged with this flag, I'd like to grant the Content's author some User Points, equal to the value in the 'Value' field, but with a maximum of 5.

I've got a question about the 'maximum 5' condition. I made 2 seperate rules with an extra condition 'Data comparison': one with [flagged-node:field-value is lower than 6] and another with [flagged-node:field-value is greater than 5]. (Note that I can choose "field-value" here!) Isn't it possible to do this in just 1 single rule?

Note: I also have a problem with the 'Value' field. See: Grant user User Points equal to value of certain field.

I found a solution for my question; maybe it can help others too. I actually created a 'correction' Rule that's activated after a user was awarded userpoints and a 'Content' node was flagged with 'Publish Content and grant points to user'. This is how I set up the Rule:

EVENT

User was awarded userpoints
A node has been flagged, under 'Publish Content and grant points to user'

Then, I checked whether the amount of points is higher than 5.

CONDITIONS

Data comparison: [userpoints-transaction:points] is greater than 5

Finally, I calculated the difference between the added userpoints and 5 and substracted this value from the user's userpoints.

ACTIONS

Calculate a value: [userpoints-transaction:points] "-" 5 (variable name: difference)
Calculate a value: [difference] "*" -1 (variable name: substract)
Grant points to a user: grant [userpoints-transaction:user] substract points

I had to insert the second calculation, because otherwise, I couldn't substract the 'difference' from the user's userpoints.


Can't get value from cache_page table only cache_default I am fiddling a bit with drupal 8 cache. Looking at cache_page table and there is clearly a value with CID i am trying to fetch. I try this.

if ($item = \Drupal::cache()->get($cid)) {
  dsm($item);
}

and keep getting nothing for that CID, when I try some CID from cache_default. I get it without problem. So I am wondering how to get values from other tables?

Provide the cache bin page, otherwise it defaults to default:

\Drupal::cache('page')->get($cid)


How do I disable a fieldset? I read How to unset fieldset in hook_form_alter? to disable fieldsets in an hook_form_alter() implementation, but it didn't work.

I tried using the following code, but neither of them worked.

// First try.
foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = TRUE;
}

// Second try
foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = 'disabled';
}

How can I disable fieldsets?

You can not access directly to #fieldgroups in form_alter you should add pre_render function like the following:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['#pre_render'][] = 'mymodule_form_pre_render';
  }
}

/**
 * @param $form
 *
 * @return mixed
 */
function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
  return $form;
}

Edit :
if you want to just disable the fields change the pre_render function by:

function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
    if (isset($form[$form_element_id])) {
      //- For entity reference fields
      if (isset($form[$form_element_id]['widget'][0]['target_id'])) {
        $form[$form_element_id]['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
      }
      //- For normal input form
      if (isset($form[$form_element_id]['widget'][0]['value'])) {
        $form[$form_element_id]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
      }
    }
  }
  return $form;
}


How do I properly detect if region is empty? I have condition for printing regions in my page template as is not empty, but it will always print empty regions no matter what. What is the proper way to detect empty regions?

For example, {% if page.local_tasks is not empty %}{{ page.local_tasks }}{% endif %} prints out

.

If I render the region in themename_preprocess_page() with var_dump(drupal_render($variables['page']['highlighted'])); I will get SafeString with placeholder token:

<drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="0" token="a8c34b5e"></drupal-render-placeholder>

So, technically the region is not empty but I can do nothing about it.

try to apply filters after render, like this :

{% set has_sidebar_first = page.sidebar_first|render|striptags|trim is not empty %}
{% if has_sidebar_first %}
    {# ... #}
{% endif %}


How do I include a required context in a ctools content type plugin? I need to include a subject type as a required context for a ctools content type plugin? How and where is context set for the ctools plugin?

You can define the required context in the plugin definition array. Use the 'required context' key and the ctools_context_required class.

Here are a few lines of stripped down code you can find in the CTools Plugin Example module:

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t('Simplecontext content type'),
  'description' => t('Simplecontext content type - works with a simplecontext context.'),
  'required context' => new ctools_context_required(t('Simplecontext'), 'simplecontext'),
);


What URLs does the Update module uses? I have to put in white-list the URLs used by the Update module. What URLs does it uses?

You're probably looking for:

http://updates.drupal.org/release-history

From the update.module file:

/**
 * URL to check for updates, if a given project doesn't define its own.
 */
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');

It's worth noting the "if a given project doesn't define its own." part of that - the vast majority of modules use the standard Drupal URL, but not necessarily all of them. If you have any modules that haven't been installed via Drupal.org, check through their .info file and look for the project status url key. If any modules define a value for that, you'll also want to whitelist it.


How to get the current user id in the path I'm using the Workspace module and when the user goes on their 'SITENAME/user', there's a link which leads them to all the nodes they have added.

The path of the link is 'workspace/<UID>' for example 'workspace/1' for admin. I'm trying to create another tab to do the same function but I can't figure out what path should I put. I tried 'workspace/%', 'workspace/user'. But nothing seems to work.

I found the answer for this myself. Used the me aliases module. And used the path 'SITENAME/me'. Works perfectly

Provides shortcut paths to current user's pages, eg user/me, blog/me, user/me/edit, tracker/me etc.
This means logged in users no longer have to know/remember their uid, and it makes it easier to link to user-specific pages from a site help page (without resorting to using php to put $user->uid in the link).


How to use drush config:set for translations? https://drushcommands.com/drush-9x/config/config:set/

For one language site the command is:

drush config:set system.site name "Drupal 8 English sitename"

But how to be, if the site is multilanguage, at example two languages?
Example:

English site name: "Drupal 8 English sitename"
Italian site name: "Drupal 8 Italian sitename"

At example for site settings in web interface I can translate it in tab "Translate system information" http://take.ms/i9jUN.
But how to set translated config value with drush? It is possible?

For getting the site name in Spanish for example it's

drush config:get language.es:system.site name

Unfortunately the following doesn't work and I wonder if this is a bug or what's missing.

drush -y config:set language.es:system.site name "Hello World"

This just gives me

  Invalid character in Config object name language.es:system.site.

Will update answer later.

Created an issue on drupal.org: drush config:set for other than default collections raises exception. Where I also provided a patch you may use if you are really in need right now.


Change URL of /blogs How would I go about writing a function to change the url of /blogs to /news?

Since the blog URL is hard coded, make an alias using the (core) path module.


Apply coupon from an affiliate link to ubercart Modules involved

Cart Links
uc_discounts_alt or uc_coupon (I like uc_discounts_alt better)
uc_affiliate2
Ubercart

I need to give the ability to have a coupon applied to the cart if the user came through an affiliate link.

Example:

I have a coupon giving 10% off to "Product 1".  I have a partner "Affiliate 1".

I have a link http://site.com/affiliate/1/cart/add/p1?destination=cart/checkout (which there is an issue there since the destination is redirected before the add to cart is applied)

I want to make it so that when that link is followed the coupon is added to the order.

I figured to do this with Conditional Actions, but the predicates/conditions/actions don't seem to exist.

I guess I need to build a predicate for "Item aded to cart", a condition of "Is there an affiliate" does seem to exist, an action for "Add discount".  But I also seem to need something to tie discounts to affiliates.

Any ideas on how to proceed here?  Are there any modules out there for this?  Any alternatives?

Try ECO (Extra Customization Options for Ubercart).

  ECO (Extra Customization Options for Ubercart) provides additional ("extra") options to customize Ubercart.

  Some of the functionality provided also includes a degree of integration with other contributed modules like Legal, Webform, and Ubercart Discount Coupons. Among the customization options are using URL parameters to auto-apply coupons in checkout, requiring new customers to choose a password, and integration with the Webform module to pre-populate address fields in checkout.


Catch first node in a view template I created a view for the front page and also a node--view--frontpage.html.twig to design this view. Is there any opportunity to catch the first node with a if statement to design it differently?

In this case I want to change the order of the first iteration in the node--view--frontpage.html.twig:

{% set createdDate = node.getCreatedTime | date('j.m.Y') %}

  {{ content.field_picture }}

    {{ createdDate }}
    {% if content.typ | render | trim %}
      , {{ content.typ }}
    {% endif %}

    {{ label }}

  {{ content.body }}

The display suite module has a views integration that allows you to choose a different display mode for the first node in a view versus all the others. In this case you can easily create a separate tpl for that view mode and you're good to go. Its extremely powerful. Take a look at this post and look for "Alternating view modes" in the last screen shot.


How to upload videos and play in Drupal 7? I am trying to upload custom video files to Drupal site and play the video. I have custom videos which are to be uploaded to posts.

Here I am not using any YouTube embedded links, instead I want to upload my own videos into my posts.

I also have installed the media module and the JWplayer but I don't know how to configure the module to upload videos in my posts and play those videos.

I am a newbie to Drupal. Can anyone help me to configure this?

Here is complete Community Documentation about the Media module.

There is another Drupal Video Setup Using Media and Media Youtube
 tutorial about using the [Media] and Media Youtube modules in a Drupal site.

If still you can't get it to work, then you can also check the tutorial Post YouTube Videos with Media + Media: YouTube (from Drupal's Post Installation forum).

Now choice is up to you in which you feel easy.


Access to block-system-main div I have block with image so the easy way it's to create a content type.
I have node--nodeName.tpl.php where I built correct DOM.

But this is slider, and all nodes embedded in one div with classes

  block-system-main block block-system

I have to initialize slider. For this I need unique parent class\id

This is beginning of my node--nodeName.tpl:

<div class="<?php print $classes . ' slick_hero ' . ' ' . $zebra; ?>">

Looks like you're having a block of node teasers, and you want to initialize a slick slider on its items using vanilla JS, yes? There's a better way to do this, and that's to use the Slick module together with Slick Views.

Create a slick carousel view, configure it as a block and not a page.
Filter to the desired nodes
Configure to render the teaser displays
Configure the slider parameters.
On whatever block rendering mechanism you have (Block Layout, Context, Panels, whatever), position the view in the desired location.

All that and you never have to touch code or meddle with the template.


How to programmatically create node with image file saved from remote source? I have a remote image URL address saved in $image_url variable and the following code to programmatically create a node:

  $node = new stdClass();
  $node->uid      = '1';
  $node->type     = 'article';
  node_object_prepare($node);
  $node->title    = $title;
  $node->status   = 1;
  $node->promote  = 0;
  $node->sticky   = 0;
  $node->language = 'ru';
  $node->body['und'][0]['value']   = $body;
  $node->body['und'][0]['format']  = 'filtered_html';
  node_save($node);

Calling filefield_sources_save_file($image_url) in a custom module gives:

  Warning: filesize(): stat failed for http://www.remotesite.com/images/2014/11/1414790760.jpg in filefield_sources_save_file() (line 451 of /home/mysite/public_html/sites/all/modules/filefield_sources/filefield_sources.module).
  The specified file 1414790760.jpg could not be uploaded. Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

Could you please help me to make changes into above peace of code to programmatically create a node with the image in the imagefield saved from a remote source.

Finally have figured out. The following code works fine:

$file = file_save_data(file_get_contents($image_url), file_default_scheme().'://tmp/'.basename($image_url));
$file->status = 1;
$node->field_image['und'][0] = (array)$file;

node_save($node);


how to manually add a node in drupal 7 in the database I have managed to display the title but im missing the body of the title. i cant find in the database which table i missed to edit.

here's the list of tables i editted:

node
node_revision
node_comment_statistics
taxonomy_index

for the body i assume that these fields are responsible for it:

field_data_body
field_revision_body
field_data_taxonomy_forums
field_revision_taxonomy_forums

The node i made has no comments so no comment table is editted.

Am i missing other tables to edit here?

SO i assume i have editted all the necessary tables but i seemed to have missed something here cause ONLY THE BODY IS MISSING.

Because you are trying to understand Drupal database concept, you are checking every insert you made in the Drupal admin section, and by doing so Drupal is caching your data.

So you are not missing anything. You only need to clear Drupal cache, try to truncate each cache table one by one.


Custom Ajax Based Search Form I'm trying to create a custom search form that uses ajax to perform the actual search and return the located objects as html.

Currently I'm doing something like this:

function example_module_search_form($form, &$form_state) {
   $form['title'] = array(
     '#type' => 'textfield',
     '#value' => '',
   );
   $form['submit'] = array(
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'example_module_search_callback',
        'wrapper' => 'bottom',
        'method' => 'replace',
      ),
      '#value' => t('Submit'),
   );
   return $form;
}

function example_module_search_callback($form, $form_state) {
   $title = $form_state['input']['title'];
   $objects = db_query('SELECT * FROM {node} n WHERE n.type = :type && title = :title', array(':type' => 'object', ':title' => $title))->fetchAll();
   $output = '';
   foreach($objects as $object):
     $output .= '
'.$object->title.'
';
   endforeach;
   return $output;
}

The above works fine the first time I submit the form, but in subsequent requests the $form_state['input']['title'] is always the same?

Can someone point out what I'm doing wrong or perhaps there's a better approach. The reason why I would like to implement my own search form is that the form will have a very large set of controls which values will be used to query the database.

Usually in Drupal, the ajax callback is business logic free. You should associate your title (ie string) directly in the form, when ajax had run.
I use this :

function contact_contact_search_form($form, &$form_state) {

$string = '';

//Retrive the string value
if (isset($form_state['values'])) { // Does ajax ran ?
   $string = $form_state['values']['string'];
}

$form['string'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
      'callback' => 'contact_contact_search_ajax',
      'method' => 'replace',
      'effect' => 'none',
  ),
  '#value' => t('Submit'),
);

// Display the result in the form, but should work if the results are outside of your form
$form['table'] = array(
  '#type' => 'item',
  '#prefix' => '
',
  '#suffix' => '
',
  '#markup' => contact_contact_display_searches($string),
);

return $form;
}

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

   $commandes[] = ajax_command_replace('#search-table',drupal_render($form['table']));

   return array(
     '#type' => 'ajax',
     '#commands' => $commandes,
   );
}

// Create your table
function contact_contact_display_searches($string) {
// The query
  $query = db_select('node', 'n')
      ->fields('n')
      ->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
      ->range(0, 20)
      ->execute()->fetchAll();

 // Prepare and clean the results
foreach ($results as $result) {
  $rows[$result->nid] = array(
      'type' => check_plain($types[$result->type]->name),
      'title' => l(check_plain($result->title), 'node/' . $result->nid),
      'email' => check_plain($result->field_pers_email_email),
  );
}

// Simple table theming
$out = theme('table', array(
    'header' => array(t('Type de contenu'), t('Intitulé'), t('email')),
    'rows' => $rows,
    'empty' => t('Aucun résultat avec ces critères de recherche')
        )
  );
}
return $out;

}


Request for new password when user login for the first time I am using darland theme in drupal7 site and I want user to reset their password for the fist time when they login with temporary login credentials given by admin,i,e created user when he login for the first time he should able to see the reset password form and later he can use his account as required,!!how to resolve this issue??can anyone know?

And below screen shot which i have added is my login screen and the code showing up in the right page is cos i have added the code in page.tpl.php to solve above problem explained so now it looks like, however if i take off the code from page.tpl.php it will be removed.

Options to set a password

First of all, the very only way for any user to change their password, is using either of these approaches:

using /user/xyz/edit (with xyz = uid of the user), where there is an option to change your password. But: this can only be done for a logged in user (which assumes that the user succeeded in entering their (old) password).
using a "one time login URL", as further described below.

Requesting a new password

When you are not logged in, you can navigate to /user/password within your site (either for D6 or D7). That is where you will find the "request new password".

For a logged in user, in D7, who navigates to /user/password, you won't get the same "request new password" form however. Instead, you'll get something like so (your.name@yourdomain.com is the eMail Id to where the request new password eMail will be mailed to):

  Password reset instructions will be mailed to your.name@yourdomain.com. You must log out to use the password reset link in the e-mail.

eMail a one time login URL

You may also want to look at what is configured as email templates when new users are created (located at admin/config/people/accounts). Such as the template for "a new user created by an administrator". By default (in D7) that template looks like so (bold markup added here):

  [user:name],

  A site administrator at [site:name] has created an account for you.
  You may now log in by clicking this link or copying and pasting it to
  your browser:

  [user:one-time-login-url]

  This link can only be used once to log in and will lead you to a page
  where you can set your password.

  After setting your password, you will be able to log in at
  [site:login-url] in the future using:

  username: [user:name] password: Your password

So this one time login URL could be used by a new user. And if for some reason that URL doesn't work (anymore), then such user can still user  /user/password.

Variation: any user (such as an admin ...) can use that URL and specify the eMail ID of the new user who has to set a new password (the eMail will arrive at the new user ... if the eMail ID is correct).

Redirect on login when using a one-time login URL

One might consider adding links like /user/password and/or /user/xyz/edit (with xyz = uid of the logged in user) anywhere in your site (e.g. somewhere in your theme).

However, I'd use an approach using the Rules module to redirect on login when using a one-time login and password reset. How to actually do so (there are multiple solutions) is detailed in issue # 480584. Personally I'd go for a solution based on what is described in comment #37 of it.

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

Use the Force password change module

Another approach might be to use the Force password change module (available also for D8 now, merci Jaypan!). Here are some details from its project page:

  This module allows administrators to force users, by role, individual user, or newly created user, to change their password on their next page load or login, and/or expire their passwords after a period of time.

  Features:

  Ability to force all users in a role to change their password.
  Ability to force individual users to reset their password from their profile edit page (user/[UID]/edit).
  Ability to set an expiry on passwords so that if users haven't changed their password within that time period, they will be required to do so.
  Ability to force all new users to change their password on first-time login (site-wide setting for all new users).
  Ability for admins to force individual users to change their password on first time login when creating a new user. (Note: If the global setting forcing all new users to reset their password is enabled on the module settings page, this checkbox will not appear as it is redundant).
  Listing of stats on the user edit page (user/[UID]/edit) showing:

  Whether the user has a pending forced password change.
  When the user last had their password forced to be changed.
  When the user last changed their password.

  Status page for each role showing:

  Password change details by user.
  The last time at which the role was forced to change the password.
  A form to force the password change for all users in that role.

Use admin/config/people/force_password_change
and enable  Force password change on first-time login (can also be configured for selected roles).


Need Help passing field data from one content type to another I am working on an Equipment Checkout system using Drupal 7, MERCI, views, panels, rules, and many other modules. I am working for a community college in Oregon. I am upgrading features on an already running system that was built by myself with the help of a few other people last year. The system is offline for the summer.

Before I jump into the nuts and bolts of the question let me give you a little information on our workflow.

When the Student want to checkout equipment (cameras, microphones, whatever) we first open up the students customer account. This is a content type called customer, that has various fields containing data about the student, name, email, L# etc. We do this to verify the identity of the student as well as to make sure that they can actually check out the equipment they are requesting.

After we have verified the students credentials. We then create a new reservation, that is also a content type. Then we input the student information into the reservation.

So what I want to do: Have a button or link on the customer page that will capture the customer data, create a reservation, and then put the data in the appropriate place.

I have done some searching looking for answers and this seems to be a common problem, but the specifics always seem to throw me off. I've tried a few modules to attempt this, autofill and prepopulate but with no success.

This is the first of many features that I am trying to implement over the next 3 months, any help would be greatly appreciated.

Thank You

I don't have enough reputation to comment. I would approach this with an entity reference field, a block, and rules.

Your reservation content type should have an entity reference field for the 'customer' record.

A block would have the button to click. It goes on your customer record page. You might need a module like Rules Link  to trigger rules.

Set up rules so that when you click this button it:

creates a new entity (a node of type reservation)
populates the user reference field with the customer node you are looking at
saves the new node
opens the edit screen on the new node so more work can be done

It will take some playing around play around with rules to get it right.


Drupal 6 not playing nice with jquery 1.11.1 I am trying to incorperate a sequential fadIn of several img using a simple Jquery script

     $(document).ready(function(){
$(".fadeInCopy").each(function(index) {
    $(this).delay(900*index).fadeIn("900");
});
 });

I have the jquery loading properly and no errors in the javascript panel. However, the script will not reveal the elements. I have this working on a test page but once I install in Druapl 6 it does not respond. Any ideas?

I would comment this, but I'm new to drupal stack exchange. Try wrapping this method around your javascript/jquery:

(function ($){
   $(document).ready(function(){
      //code here
   });
})(jQuery);

Sometimes the $ symbol alias for jQuery causes conflict.

Or you can replace all $ symbols with jQuery and see if that works.


How to check if a multi value reference field already has a value I need to check if a multi-valued reference field (referencing other nodes) in a node has a specific value already present to avoid duplicates.

here is the code:

$portFolioNode =  \Drupal\node\Entity\Node::load( $form_state->getValues()['portfolios'] );

//now save location id to reference field.
//$portFolioNode->field_portfolio_locations[] = ['target_id' =>  $form_state->getValues()['location_nid']  ];

// how can I check if location_nid is present already?
$portFolioNode->field_portfolio_locations[]  = $form_state->getValues()['location_nid'] ;

$portFolioNode->save();

Any help will be appreciated greatly. Thanks!

You can check the field's values before saving:

// Id to check if exists.
$query_id = 123;

// Create array of existing ids in field.
$existing_ids = array_column($entity->my_entity_reference_field->getValue(), 'target_id');

// Check if the $query_id is not in the existing ids.
if (!in_array($query_id, $existing_ids)) {
  // In here means your $query_id doesn't already exist in the field's values.
}

Your code updated:

// Load portfolio node id and new location id from form_state.
$portfolioId = $form_state->getValue('portfolios');
$newLocationId = $form_state->getValue('location_nid');
if (!empty($portfolioId) && !empty($newLocationId)) {
  // Load portfolio node.
  $portfolioNode = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->load($portfolioId);

  // Get existing location ids from portfolio node.
  $existingPortfolioLocationIds = array_column($portfolioNode->field_portfolio_locations->getValue(), 'target_id');
  // If new location id is not an existing location id, add to node and save.
  if (!in_array($newLocationId, $existingPortfolioLocationIds)) {
    $portfolioNode->field_portfolio_locations[] = $newLocationId;
    $portfolioNode->save();
  }
}


Taxonomy filter. List terms with ajax checkbox selection I need help to make some filter.
Block with taxonomy terms list and checkbox selection closure. Checkbox need to return all nodes categorized by selected terms on change. It has to be transparent for user (Ajax).
Thanks!

Use combination of next modules:

Better Exposed Filters - module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively.
Views Filters Auto-submit (views_filters_autosubmit) - auto-submits exposed filters on change.


EntityFieldQuery doesn't work correctly in hook_cron I am programming a new module in my Drupal 7 project. in my module hook_cron is override.

in my hook_cron function, I want to select a node type with specific filter for a cck field.

I am using EntityFieldQuery in order to run a query.

my specific content type is "order_status"

here us the first code of query.

$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1);
$result = $query->execute();
dpm($result);

this code works with no problem. it collects all nodes with "order_status" content type that are published. (status is 1)

but when I want to add a new cck filter to the query it doesn't work.

I have defined some cck fileds for my "order_status" content type.

one of them is field_order_status_cr_confirm
type of this field is boolean (TRUE/FALSE or 1 | 0)

for adding a new filter to my above query I used this code.

->fieldCondition('field_order_status_cr_confirm','value',1,'=');

so my final query is

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1)
    ->fieldCondition('field_order_status_cr_confirm','value',1,'=');
$result = $query->execute();
dpm($result);

but this code doesn't work. it returns nothing. also I changed value of the field_order_status_cr_confirm to 1 but it still returns no data.

Do you know what my problem is ?

here is the dpm function result for one node of "order_status" type.

Please help me.

I have also encountered this kind of issue that running EntityFieldQuery does not work sometimes in the cron job.

It turns out that EntityFieldQuery will run access check.

Cron job is run as anonymous user role and it cannot access to order_status node.

To work around this issue you can add tag DANGEROUS_ACCESS_CHECK_OPT_OUT to bypass node access.

Here is the example:

$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1);
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();


How to set percent discount by old and new price I have commerce-product, add new field old price and percent discount

Then i create new rule

There isn't really enough information here to diagnose your issue, but the likely problem is a mismatch between the data type required by your custom field and the data type of your calculated value. Since you didn't specify the type of field you used to create your custom field, I can't say for certain, but Rules will only allow you to set it to a valid value for the field type.

At the very least, it doesn't appear to be anything to do with Commerce or Rules themselves.


Migration after server crash: maintenance mode and/or cache problem I had a crash of my previous server and I tried to rise my website from the dead. I had backups of all the files & of the database (PostgreSQL). I was not the one who set up the website and my knowledge of Drupal is pretty low.
From what I understood/gathered, it is a 7.54 version and it runs with multisite.

What I did so far:

Import my database backup in PostgreSQL (in the dumbest way possible: recreate the right database & user, import everything back in place);
Upload all the files to my new server (running Debian Jessie);
Give access to the sites/ directories to www-data user;
Clear the sites/mysite/css/ and sites/mysite/js/ directories;
Disable CSS & JS aggregation (using drush).

I did the latest because the style of the website was broken; that was enough to revive it.

I still have on major issue: when I log in, I get the maintenance message. I therefore tried to disable maintenance_mode with drush; it didn't work.

I saw it could be related to cache issues; I therefore tried to clear the cache (once again with drush with drush cc all). It put the whole site in maintenance, and not only when I'm logged in.

I am not sure where the problem comes from. Any hint or suggestion would be greatly appreciated!

Here is finally how I solved the problem with Yogesh help: when I tried to access the admin section while logged in as an administrator, I got an error. I therefore checked the watchdog table. The image_dimensions table was somehow missing:

[...] Undefined table: 7 ERROR: relation "image_dimensions" does not exist [...]

I created the missing table, and everyhting was then working (access to the admin section, access to the user section and so on).


User/register Page is not found in Drupal 6 site The user login and user register page are not found in my drupal 6 site.It was working fine until before yesterday and I changed the user login page link as www.sitename/user instead of www.sitename/user/login but the register page is still not found.

Is there any way to get back the user/register page? I didnt installed any module recently.

Thanks in advance.

Have you checked the clean URLs? There might be a problem with clean URLs.

Try www.sitename/?q=user/login.


menu get object doesn't seem to work I'm a trying to pass a var, in this case the var "$node" to the page.tpl.php.
Tried everything for three days but i cannot make it work despite my code is correct apparently. Tried different ways but when i tried to check with isset if the var exists, it returns false. I really need it, so i can check pages and nodes.

This is my code:

template.tpl.php

  function agn_preprocess_page(&$vars) {
  $node = menu_get_object();
  if ($node = menu_get_object()) {
      $vars['node'] = $node->type;
  }
  }

page.tpl.php

<?php if (isset($node)){
   print "true";
}else{
   print "false";
}
?>

Thanks in advance!

$node is already available in page.tpl.php on node pages without you having to do anything. See the documentation


How to write a module that changes user role when account is created I am writing a module called "Applicant" and I want it to add a role called "applicant" to a user after the user creates their own account.

applicant.info

name = Applicant
description = Handles Applicant User Actions
core = 7.x

applicant.module

<?php
function applicant_user_insert(){

}

What would I include inside of the hook in applicant.module to access the current user's roles and add "Applicant"?

Don't re-invent the wheel!  https://drupal.org/project/registration_role

Also I think you want to look at user_presave,  rather than user_insert.  https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_presave/7


What may cause Undefined index in drupal_retrieve_form when uploading an image? I have a developed custom plugin in my Drupal 7.54 site for panels where user can upload image. It works locally, however when I trigger same functionality on production nothing happens and I see in logs following errors.

Notice: Undefined index: hero_block_search_box_edit_form in drupal_retrieve_form() (line 807 of /Users/dpa/Sites/e1/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'hero_block_search_box_edit_form' not found or invalid function name in drupal_retrieve_form() (line 842 of
/Users/dpa/Sites/e1/includes/form.inc).
Notice: Undefined index: content in file_ajax_upload() (line 271 of /Users/dpa/Sites/e1/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /Users/dpa/Sites/econ-websites/econ1/modules/file/file.module).
Notice: Undefined index: #prefix in file_ajax_upload() (line 283 of /Users/dpa/Sites/econ-websites/econ1/modules/file/file.module).

I read about similar issues in google any many people say it could be related to permissions (and it has sense, since locally everything works but not on production side).

Would anybody give me a hint where to look?

You need to either move hero_block_search_box_edit_form() from hero_block_search_box.inc to your .module file, or at the top of your form definition (or hook_form_alter() if that's what you are using), you need to add the following:

form_load_include($form_state, 'inc', MODULENAME, 'hero_block_search_box');

where MODULENAME is the module key (machine name) of your module. Make sure you don't include the .inc in the last parameter - I didn't forget it, I left it out on purpose.


clearing cache to call hooks in .module file I have created a token in .module file. that gives current node title.

But every-time I change the title of node, I have to rebuilt cache so that updated title get reflected in my token.

Of-course clearing cache again and again on every page refresh is not a good idea.

Any other way to call hook_token_info and hook_tokens automatically on every page load?

PS: I also installed "token" module and this module is using hook_module_implements_alter(&$implementations, $hook).

@edit:

function hook_token_info() {
    $info = array();
    $info['tokens']['etf']['node-title'] = array(
    'name' => t('Node Title'),
    'description' => t("Provides current node title."),
    'type' => 'etf',
    );
    return $info;
}

function hook_tokens($type, array $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();

  $url_options = array('absolute' => TRUE);
  if(isset($options['langcode'])) {
      $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
      $langcode = $options['langcode'];
  }
  else {
      $langcode = NULL;
  }
  $request = \Drupal::request();
  $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
  $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  if ($type == 'etf') {

    foreach ($tokens as $name => $original) {
      switch ($name) {
              case 'node-title':
              $replacements[$original] = $title;
//              drupal_flush_all_caches();
//              sleep(2);
              break;
       }
    }

  }
  return $replacements;
}

All code is written in .module file

Short
This is wrong use of tokens, it can never work.
Long
So what you are doing is incorrect usage of tokens. The idea with tokens, is that you have some data object, like a Node, a User etc and based on that you can output something from that object, like the label, uri etc.
Tokens aren't designed to load data from somewhere and display it. For Drupal 8 with all the new caches, it's even more tricky, but even for Drupal 7 this would not work. The reason is that the result of token replacement is cached, since the idea with tokens is that it will always be the same (as long as the data objects which are used for to make the tokens do not change.
To achieve this feature, you would need to load the current node and make it available in the texts where you want to use it as a token, and for Drupal 8 you would also need to add cache context of the url. If I knew what you are using this for, I might be able to give a more precise advise on what the best way would be to achieve this.


Adding a link to an image Is there a module or a way in core to have an Image field be a clickable link to a URL that is either entered as an additional setting for the Image field or can be pulled from another field that stores that URL.

This https://www.drupal.org/project/linked_field looks like what I want, but there doesn't seem to be a token that I can use that will do what I want.

This also looks exactly like I want but it's for D7. https://www.drupal.org/project/linkimagefield

I'm using this for a Custom Field Type

If you are already building a custom field type, you could add properties for the link to your field:

class MyLinkField extends FieldItemBase {

  public static function propertyDefinitions(StorageDefinition $storage) {
    ...
    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'));
    $properties['url'] = DataDefinition::create('string')
      ->setLabel(t('URL'));
  }

and use it in the field formatter:

class MyLinkFieldFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#type' => 'link',
        '#title' => $item->title,
        '#url' => Url::fromUri($item->url),
      ];
    }
  return $elements;
  }


Show contextual link for each node on node listing page I want to show contextual links having Edit and delete links for each node on hover on main listing page of my application. I have searched and found the following code

function MyModule_node_view_alter(&$build) {
  if(isset($build['#node'])) {
        $node = $build['#node'];
        if(!empty($node->nid)) {
            $build['#contextual_links']['node'] = array('node', array($node->nid));
        }
    }
}

But this code displays contextual link on node detail page. For example when individual node is visited like http://www.example.com/node/21. But I want to show these contextual link on listing page where all nodes are displayed. When I hover the node, this should be shown.

This is how my view settings looks like

Any help?

If you are building the node listing page using views, you can

Enable contextual links module.
In the fields for the listing, add a field 'Content : Edit Link'. Then select Exclude from display.
Add a Global : Contextual Links field. In the field settings, check the edit link field.
You should be good to go.
You can also add additional field in the context menu if you want.


translate custom fields in the registration form I've installed i18n and added some new fields to the registration form, but I can't translate these new fields.

If I create a view to list the registered users, the string I want to translate shows up in the Translate Interface, but it only works on that page with the users list. The registration form remains untranslated.

I am using Drupal 7.

You need the i18n_field module from http://drupal.org/project/i18n. This allows to translate field labels, descriptions and so on.


Webform is currently not enabled on any content types I have installed the "Webform" module with no problem, but when I create a new webform, I don't have the possibility to add a new field. I have checked the section config/content/webform. I get this message "Webform is currently not enabled on any content types". Since I am new to Drupal, I don't know what to do,can somebody help me please?

Just make sure you have enabled WEBFORM in the Drupal menu modules


Users and Forum Transfer from a live site to a staging site How do I transfer just the Forum of a Drupal site to another Drupal site as my staging site is lagging behind the live site, So I need to update it with the live site forum content and then  publish my staging site as the live site afterwards.

Use Features for all need of these kind. Module page explains -

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it declares its components (e.g. views, contexts,
  CCK fields, etc.) in its .info file so that it can be checked,
  updated, or reverted programmatically.

So you can make feature of your users setting as well as forum and you can always track the changes at your staging site and if it's overridden then you can make it again and apply the changes at live site by replacing the created feature and enabling it..


What does the outbound path processor do? In some PathProcessor classes there is a processOutbound method which is from the OutboundPathProcessorInterface. The API for that method simply says:

  Processes the outbound path.

What is the outbound path? What is it for? What does it do?

Inbound path processing is used for incoming requests to the site. Outbound path processing is used when generating URL's, doesn't matter if it is outside of the site or not, in fact it would be very uncommon to use it for those kind of links.

The most obvious example is language negotation path prefix/domain, on an incoming request to en/node/1, inbound path processing removes "en" and sets the current language to english, when generating a linke to "node/1", path outbound processing adds the en/ prefix based on the current or provided language.


What is the proper way to set up Drupal 7 on load balanced servers so that CSS and JS files are in sync? We're moving our website to new Cloud Load Balanced servers on Rackspace. It's all a bit of a new experience for us, we've ironed out most of the issues, apart from one.

We've set up the new servers to lsync from Server A to Server B (Server A is master).

From time to time we see css/js files 404. We can guess what's wrong, it's file syncing not happening fast enough between servers, and when a cache clear occurs on Server A, such as a cron run, then Server B is requesting the old CSS/JS files, and that request may go to Server A.

What is the proper way to set up Drupal 7 on load balanced servers so that CSS and JS files are in sync and don't cause 404?

Drupal's core aggregation does not work on a cluster because it creates the aggregates  during the page rendering. Once the page is stored into the cache another server of the pool will read from the cache so it will not render the page again meaning that the CSS or JS aggregation will not be done locally.

To solve this problem, I created a NFS share between the servers just for the "css" and "js" folders. It was running ok for a while but under heavy load Drupal was sometimes generating empty files (2 servers creating the file at the same time). So even keeping in sync the servers is clearly not a solution.

But just as Beebee said, you can use the Advanced CSS/JS Aggregation module. This one is clever enough to be able to rebuild an aggregate just from the URL, because it stores in the database a mapping of the files that are part of the aggregate.

Advagg is also able to handle groups of aggregated files. This can reduce your bandwidth usage if your visitors navigate across different pages because the common files can be merged into a separate aggregate and the delta files merged into another aggregate.


Changing Default Text of Fivestar Rating Widget My fivestar rating says 'no votes yet' when no one has yet voted on the node. How is it possible to change this text to say something else, like 'vote this item'?

I thought this would be a simple problem to solve but wasn't able to find the answer to this anywhere and it's not immediately apparent how this is done when configuring the tool.

The String overrides make it easy to change that text or any other text in your Drupal site. Install the module, then visit /admin/config/regional/stringoverrides in your site and you can change the text as shown below.

Then when viewing the vote you'll see:


File attachments in /files/ disappearing I'm having an issue on my site with uploaded file attachments disappearing. As an example, on our blog, we have images uploaded into the blog post with images added by using the file attachment. I've recently found them being deleted from the server resulting in an image placeholder. Yet the record of the file being attached is there and the source code within is correctly pointing.

Does anyone have any suggestions on how to diagnose this?

Our server is hostgator if that makes any difference. I'm not certain it's a Drupal problem.

We are having a similar issue (http://deepcarbon.net), and it is intermittent. Most of the time it all works. But sometimes the images simply disappear. They were in the database, they were in the file system. Then all of a sudden they were not. Wondering if there's anything new on this topic.

So I know that the files table in the database has a status column. If the status is 0 (temporary) then the file will be removed the next time the cron runs. The other status is 1 (permanent).

I'm also curious about what jdu says "I would suggest bootstrapping drupal and manually running some of drupal's image functions to test it out". Can you explain that more? What functions?

So our current solution is to run a cron every night to determine if any files have been removed from the filesystem since the night before. And we archive the files directory, so we can restore them if need be. At least until the real problem

We've also turned on creating revisions for every change for every content type, so we know when someone does something in a node.

So far we have not had the problem again over the last 3 weeks, so debugging this issue is on hold.


Updating user fields in Drupal 7 I have created several custom fields for my Drupal 7 users, which I imported from an external users table.

I am now trying to automate the population of these custom fields using a custom module, however my code is not working. The following code is what I have been working with:

<?php

function get_sage_fields($username) {

  // Get the extra fields for Sage users
  $sage_fields = db_query('SELECT OFFICE_ID, TRADE_STATUS, DESIGNATION,
    FIRST_NAME, LAST_NAME, PHONE_NUMBER, MAILING_ADDRESS, ACCOUNT_PREFIX,
    ALLOW_TO_TRADE FROM USER WHERE USER_ID = $username');
  return $sage_fields;
}

function sage_fields_user() {

  // Grab all usernames from the users table
  $usernames = db_query('SELECT name FROM users')->fetchCol();

  // Load the users
  $users = user_load_multiple($usernames);

  // Loop through and edit each user
  foreach($users as $user) {

    // Load the extra data
    $extra_data = get_sage_fields($user->name);

    // Update user fields
    $user->field_office_id[$user->language][0]['value'] = $extra_data['office_id'];
    $user->field_trade_status[$user->language][0]['value'] = $extra_data['trade_status'];
    $user->field_designation[$user->language][0]['value'] = $extra_data['designation'];
    $user->field_first_name[$user->language][0]['value'] = $extra_data['first_name'];
    $user->field_last_name[$user->language][0]['value'] = $extra_data['last_name'];
    $user->field_phone_number[$user->language][0]['value'] = $extra_data['phone_number'];
    $user->field_mailing_address[$user->language][0]['value'] = $extra_data['mailing_address'];
    $user->field_allow_to_trade[$user->language][0]['value'] = $extra_data['allow_to_trade'];

    // Save the user object
    user_save($user);
  }
}

I enabled my custom module under admin/modules and included it in my .info file with:

files[] = sage_fields.module

However, if I go to field_revision_[FIELD_NAME] in my D7 database, I do not see these fields populated.

Could someone please point out where I have gone wrong?

So Simple. just paste it

$user_fields = user_load($user->uid);
$user_fields->field_points['und'][0]['value'] = $points;
user_save($user_fields);


Intelligently altering URL's I have a dilemma.

For my articles content type, i'm wondering how to alter a url automatically if i need to replace the hyperlink of my image thumbnails residing on my site to link to my other site which is my data repository on another server. Apart from doing it manually, i would like to know if i could automate this and create a script to do it, but i'm also not sure where to put it.

regards,
V

I believe one of the better solutions to this would involve an extension to Storage API. You can't do it out of the box since it your own server, instead of say S3, but it seems like the best fit. When I saw a demo presentation by the maintainer, he showed how one could split thumbnails storage to a low-redundancy system from base image storage, which was stored more safely.


How to remove markups of 'div' and 'span' from the billing info displayed through token I am trying to add token for billing information in order confirmation email . The token does its job but also displays markups of 'div' and 'span'. Whats surprises me is all the other tokens in the same email works fine and doesn't display any mark ups, however the issue is only with the token of field type: 'Postal Address' within the billing information profile

These are the two tokens I have used:

[message:message-commerce-order:commerce_customer_billing]

[message:message-commerce-order:commerce-customer-billing:commerce_customer_address]

I added these tokens to email through admin->structure->message type, since I am also using the following three modules: Commerce Message, Message Notify and Message

Any help on how to display complete billing info without markups, as entered in the built in field: 'Postal address' will be highly appreciated. Tried all the checklists in admin->configuration->text format, but no luck

If you want to alter the content of tokens you could try using the Token Function module: http://www.drupal.org/project/token_function

With this module you can write a simple function to alter the content of a token (or use one of the few existing functions).

I hope this helps.


Alter title link in taxonomy view mode Under /admin/structure/taxonomy/my_vocabulary/display/entity I've got a view mode "entity". For this view mode, I would like to alter the way the link in the title field is built (the title is replaced by a real field instance due to title module): the link should be rebuilt into an anchor link like this: Title, where term-ID is replaced with the actul term ID of the term. How can I achieve this by a custom module or by a template function? Are render arrays good for this?
Here's a screenhot of the admin page.

I finally altered the title link by using a preprocess hook and a custom field template file (and a custom view mode for my entity, done with hook_entity_info_alter()):

  function hook_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];
  $uri = entity_uri('taxonomy_term', $term);
  // Edits are here:
  $variables['term_url'] = url($uri['path'], $uri['options']);
  $variables['term_name'] = check_plain($term->name);
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  $variables['term_id'] = drupal_html_id($term->name);
  // Flatten the term object's member fields.
  $variables = array_merge((array) $term, $variables);
  // Helpful $content variable for templates.
  $variables['content'] = array();
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);

  // Gather classes, and clean up name so there are no underscores.
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;

  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
}

My taxonomy-term.tpl.php:

<div<?php print $attributes; ?>>
  <?php if (!$page && ($view_mode != 'subcategory_anchor')): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

  <?php if (!$page && ($view_mode == 'subcategory_anchor')): ?>
    <h2 id="<?php print $term_id ?>"><?php print $term_name; ?>

  <?php endif; ?>

  <div<?php print $content_attributes; ?>>
    <?php print render($content); ?>