Advanced Search (Search Api Solr) I'm trying to build a advanced search for a eRecruiting site build with the recruiter distribution. The Recruiter Distribution comes with 3 different search two for applicant that are What ? (Job Search) and Where (Job Location). The another one is to search for applicants. However they are a lot data on the job description and on the applicant that I wanted to used to be more specific .

For instance, the recruiters should be able to search for be able to search for the following items:

Keyword
Location
Specialty
Employment type

Currently, I have some facets that helps me to make my search more friendly. But when it comes to search many items (such as locations nationwide) it becomes to crowded.

I'm aiming for something similar to  Google Advanced Search but a little bit more simpler.

According to a post Building an advanced multicriteria search one the solution to complete this job is the search api solr module. And I have this part working however he did not explain how to do it. There is another post (Create advanced search) that talks very similar of what I'm asking but nobody replay.

I try to use the Search API Combined module but to be honest is lack of documentation. And it does seem to be clear how to used this module.

What is the best approach to created an Advanced Search (multicriteria search) with search api solr ?

I built a form like this for a website. If I wanted to I'm pretty sure I could use the same principle to build a form like Google Advanced Search. Whether it's the best approach or not I'm not sure.

Which sits on the front page of the websites and then sends to the search page from there.

What I'm doing is recreating the URL thats being created on the search page.  like 'search/applications?f[0]=field_location%3A2439'

I created a Custom Module
used hook_block_info to create a block
used hook_block_view to create a block view - assigned the form to its content
Example of the form code ->

function search_applications_form($form, &$form_state) {
$locations = db_query("SELECT tid, name FROM {taxonomy_term_data} WHERE vid     = 5")->fetchAllKeyed();  // vid will be the id of the location taxonomy data

$form['locations'] = array(
   "#type" => "select",
   '#multiple' => TRUE,
   "#title" => t(""),
   '#required' => FALSE,
   '#default_value' => 'Select Application Locations',
   '#options' => $locations,
   );
 return $form;
 }

And in the submit

function search_applications_submit($form, &$form_state) {
     global $base_url;

     $search = $form_state['values']['search_applications'];

     $i = 0;

     if($form_state['values']['locations'] != NULL && $form_state['values']['searchlocations'] != '0' && $form_state['values']['locations'] != 'none'){

     $tid = $form_state['values']['locations'];

     $addlocationsearch = '&f['.$i.']=field_job_location%3A'.$tid;
      $i++;
     }
     else {
     $addlocationsearch = NULL;
     }

     $searchUrl = $base_url.'/search/applications?'.$addlocationsearch;

     $form_state['redirect'] = $searchUrl;
     }

I think the logic used here could be used to make a much better module. If you've a plan for some development I'd be happy to join in a project.


How to replace URL fragments? I suppose this is more of a PHP question.

I'm trying to work on some redirects that's outputting:

http://localhost/mysite/?q=node/add/cmsdeliverable%3Ffield_demo_id_reference%3D1208

But what I need is this:

http://localhost/mysite/node/add/cmsdeliverable?field_demo_id_reference=1208
How can I cut the ?q=, and replace the &3F with ?, replace %3D with =

You need to enable clean URLs. From the documentation:

For Drupal 7:

Navigate to the Clean URLs configuration page (Administer > Configuration > Search and metadata > Clean URLs)
Wait for the automated Clean URLs test to run.
Check or uncheck the Enable clean URLs checkbox
Click "Save configuration"

For Drupal 5/6:

Go to the Clean URL's (Administer > Site configuration > Clean URLs in Drupal 5) section of the administrative interface.
Look for the paragraph that reads as follows:

  This option makes Drupal emit "clean" URLs (i.e. without ?q= in the URL.) Before enabling clean URLs, you must perform a test to determine if your server is properly configured. If you are able to see this page again after clicking the "Run the clean URL test" link, the test has succeeded and the radio buttons above will be available. If instead you are directed to a "Page not found" error, you will need to change the configuration of your server. The handbook page on Clean URLs has additional troubleshooting information. Run the clean URL test.

Click on the Run the clean URL test link at the end of the above paragraph.
If the test is successful, set Clean URLs to "enabled" and save the configuration. If the test is not successful, use the steps below to fix your server configuration and try again.


Search result theming I have problems configuring the search-result.tpl. Is it so, that the fields set in Search result view mode are always snippet'ized as plain text? I have for example a taxonomy term on each node, which I set to appear as link in the Search result view mode, yet it is always output as plain text.

I'm using Custom Search and Search API, if that matters.

Assuming Drupal 7 here, which thankfully has more options for you that Drupal 6.

I don't recall the last time I fully traced this out (and it's complicated), but search_excerpt does call strip_tags and check_plain.

You can take a look at search-result.tpl.php, template_preprocess_search_result(), hook_node_search_result() to see what your options are.

Personally, I would build up my own entries in $variables in the preprocess, and display them in the template.  One option is to make a custom node view for the search results, uild it up with the UI, and then use this,something like:

function mytheme_preprocess_search_result (&$variables)
{
  $result = $variables['result'];
  $node = $result['node']; // not 100% positive that this is the right place in D7
  $variables['my_custom_search_result_view'] = node_view($node,
    'my_custom_search_result_view');
}

and then use $my_custom_search_result_view in search-result.tpl.php.

Not a full solution for you, but it should be a decent start.


How can I increase my hit ratio in Memcache? Memcache has been up and operational on my production site http://goniseko.com for a few months now.  After getting everything configured and memory limits where they should be, I noticed that I have a very consistent 70% / 30% hit to miss ratio.

How can I improve this?

Also, I noticed that this is pretty consistent across other Drupal 7 sites where I have memcache installed.

What is it about Drupal, Memcache, or a combination of the two that won't allow for this extra 30% to be stored in the cache bins? How can I figure out what these queries are, and what can I do to get them in the bins?

I am hoping this is similar to APC.  I have that configured so that I have a 100% hit rate for this site. I would like to have Memcache that high, or at least higher than 70%. That's almost 1 out of 3 queries that have to hit the db.

I would interpret the numbers in a way that 70% of the traffic to your site are pages that are currently contained in the cache. The other 30% did go stale because the weren't visited frequently enough to stay fresh.

This is a more common problem about "How to cache?". The base Drupal cache is time based. If you don't use more complex methods like Drupal 8 tries to do for you there will always the problem that from time to time hits can't be cached. So probably 99% of you home page are cache hits. The 1% are the hits while the page is refresh. But any other page that is older than your settings on the "performance" settings page will be immediately stale. Means that if you cache for 5 minutes and the page is visited every 6 minutes it will never get a cache hit.

Your cache is currently more or less a protection against traffic spikes or (D)DOS attacks. But not something that really eases the web server in all occasions.

Real solutions for this go above this question and the easiest thing would be to go to Drupal 8. It really tries hard to cache your stuff for ever.
http://buytaert.net/making-drupal-8-fly

All in all 70% is not that bad. You could try a module like boost:
https://www.drupal.org/project/boost

And than find a way how to cache things until they are updated. But if you use a sidebar with views this will be a big problem if you don't go using asynchronous (AJAX / AHAH) calls by javascript or things like edge side includes (ESI)


How to send an e-mail to a user selected in a webform via a user reference field? I have a webform, that the HR use. I have a form component of the users, that is a user reference field.

I would like to use Webform Rules to send an e-mail notification to the selected user.

If I use: [data:{component}-display], then after the username [1] appears, that refers to the link to the user.

Even though your question doesn't say so (yet), I'm assuming (as per your "... I have a form component of the users, that is a user reference field...") that you're also using the Webform References module. Some details about that module (from its project page):

  Provides a webform component that can reference a node/term/user in Webform. It provides "Select List", "Autocomplete", "Checkbox" and "Radio" as widget.

If you also have the Webform Rules module enabled, then it is possible to create a rule (using Rules), which does what you're asking for. Here is an export of a rule that will send an eMail to the eMail Id of the referenced user:

{ "rules_email_submitted_webform_to_referenced_user" : {
    "LABEL" : "eMail submitted webform to referenced user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains the field labeled \u0022[data:demoform_userref-title]\u0022 which has value \u0022[data:demoform_userref-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_userref-value-raw]" },
          "PROVIDE" : { "variable_added" : { "referenced_user_txt" : "Referenced user" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "referenced-user-txt" ] },
          "PROVIDE" : { "conversion_result" : { "referenced_user_uid" : "Referenced User Uid" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "referenced-user-uid" ] },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "drupal_message" : { "message" : "referenced_user_txt: [referenced-user-txt:value] AND referenced_user_uid: [referenced-user-uid:value] AND\r\n\r\nUser fetched: uid=[user-fetched:uid] name=[user-fetched:name] mail=[user-fetched:mail]" } },
      { "mail" : {
          "to" : [ "user-fetched:mail" ],
          "subject" : "Hey [user-fetched:name] you have new mail ...",
          "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about this rule (prior to trying to import this rule in your own site, make sure to adapt (rename) what's needed to fit your case):

The form ID I'm using is 191.
All form components have machine names starting with demoform.
The machine name of the reference user is demoform_userref.

The Rules Event and Rules Condition should be straight forward, though the actual Rules magic happens in the Rules Actions:

Show a message on the site (just for demo purposes).
Add a text variable (to capture "some" webform data about the selected user, has to be text ...).
Convert a variable from a text to an integer variable (we need an integer for the next Rules Action, text won't work ...).
Fetch an entity by ID (the integer variable, to fetch the user with that ID).
Show a message on the site (just for demo purposes).
Send an eMail (to the eMail ID from the fetched user).

Demo

After submitting my demoform, the messages shown are like so:

The webform submitted contains the field labeled "User" which has value "123".
referenced_user_txt: 123 AND referenced_user_uid: 123 AND User fetched: uid=123 name=Pierre.Vriens mail=pierre.vriens@somewhere.com

Moreover, an eMail got delivered to pierre.vriens@somewhere.com ...

Subject:

  Hey Pierre.Vriens you have new mail ...

Message:

  The webform submitted contains these fields:
   * the field labeled "Title" which has value "Some title".
   * the field labeled "Text" which has value "Some text".
   * the field labeled "Number" which has value "7".
   * the field labeled "Option" which has value "C".


Get node id for page which is set for 403 and 404 I want to get the node number (nid) for the node which is set for 403 and 404 pages in drupal configuration system.
Can you please help me for this ?

You need to use

variable_get('site_403');
variable_get('site_404');

It will return a string like "node/1", then you just have to parse this string to get back the node ID.


How to theme 3rd party modules? I've added the "rate" module to my project. I've added multiple axes to rate but they display below my node content. How would I be able to style this? I know how to create a custom .tpl file for my content type but the module adds code AFTER my template. How I can fix this?

Best answer on how to theme 3rd party modules is always to check their local documentation first, as most of the top-tier modules have very specific hooks, documentation, guidance for how you can theme their results. In the case of the Rate module, check the README.txt file for some guidance on what theme variables are able to be used in your node templates.

It looks like the best answer would then be to make a copy of the rate template into your theme folder and add your styling there:

* rate-widget.tpl.php
  This is the default template for all custom widgets.
* rate-widget--NAME.tpl.php
  This is a widget specific template. Use the machine name for NAME. Replace
  underscores by dashes in this name. This template is only available for custom
  widgets.

This does depend on exactly what it is your trying to theme in the emotion widget.


Redirect to cck url on registration? I have a node that has a cck field that has a link, when the person clicks on it, I need them to sign up then redirect to that link.

Is that possible?

logintoboggan, rules and login destination cant achieve this, they only send to one defined page.

When you redirect to the login or registration page you can add a destination GET parameter to the url, which Drupal will redirect to after form submission.


Cache images in custom module without caching entire render array I created a module that generates a slide show. This isn't using views, I'm manually loading nodes that contain images and placing them inside a render array in a block plugin. When running an audit in chrome I noticed a message

  The following resources are explicitly non-cacheable.

Then it lists all the images present in that slideshow. After reading this I understand that you can cache render arrays, but I still need it to be dynamic, so that the slideshow updates everytime a node is added. Also different slideshows are shown to different users so I need that dynamic as well.

Is there a way to cache only the images in a render array?

Blocks are cached by default in Drupal 8.  The image non-cachable warning isn't a drupal issue.  It's a false flag from chrome.  Because image derivatives in Drupal (those generated from an image style) have a query argument chrome thinks it's not cachable.

To test that your block plug-in is caching, you can put a die() statement inside the build method to test if the code runs on each page load.  If it is running on each page load, you can comment out elements until it does use cache.  Then it should run the code once and then on subsequent page loads it won't run the code.

To make sure your block is refreshed when certain nodes are cleared, you can add them to the cache tags in your build array.  This may happen automatically if you are pulling the render array from each image from the node it came from.  Otherwise you can add them in your code like this:

$build['image']['#cache']['tags'][] = 'node:123';

To test, clear the cache and reload the page.  Verify on the cache_render table that the block is cached and your tag is there.

To test that editing that node updates the block, first update that node.  Then on the next page load of the page with your block, it should re-run the code for your block plugin.

To make sure the block is unique per user, you can add the user context to the cache contexts array

$build['image']['#cache']['contexts'][] = 'user';

To test, clear the cache, then reload the page with your block.  Check on the cache_render table that the cached item has user in the cid column.

Something like:

entity_view:block:my_block:[languages:language_interface]=en:[theme]=abilitylab_theme:[user]=123

Then test the block with a different user, and there you go:  Unique block per user.


How to make content work with and without javascript I have some content that I currently use a javascript dialog box to display. This works great when javascript is enabled but not so good when javascript isn't (it shows the dialog components on the screen along with original content). I would like to fix this so that dialog contents display on a separate screen when javascript is not enabled. I thought I saw some documentation somewhere on how to do this but for the life of me I can't find it by googling it again. Can someone point me to the proper online documentation on how to do this?

Additional Info:
The page has a button on it that allows the user to create a new item. With JavaScript enabled, the add button displays a dialog box in which the user can enter information about the new item. Currently the text/input fields for that dialog box is on the same page the add button is on but hidden by Javascript using special divs (hence why it is visible when JavaScript is disabled). This is code I inherited from someone else and now would like to fix.

This isn't specific to Drupal but its a javascript technique known as 'unobtrusive javascript'. Not knowing how you are displaying the dialog contents, let's assume this simple case:

See Dialog Content

and then somewhere else in your code (next to?) you've got a div with your dialog content set to not display, ex:

Your dialog content here ..

What you want to do is use jquery (you can do this with native javascript but you're using drupal so its already loaded) to bind a click handler to this link. The idea is then that if javascript is not loaded, then the browser will automatically send them on their way. So that would look something like this:

$(".dialog-trigger").click(function() {
   // do your display stuff here,
   return false;
}

The 'return false' statement at the end is key here to making it so that the link won't be followed.


views on top of other views I have a content type called News. There are three taxonomy terms for this content type (In the News, Success Stories, Events)

I want a page that shows each taxonomy term, with the newest three nodes summary, respective of that term, underneath it.

For Instance:

IN THE NEWS:

january 5th, 2001
blah blah blah blah blah

february 5th, 2002
blah blah blah blah blah

SUCCESS STORIES:

March 1, 2011
blah blah blah

Jan 2, 2012
date blah blah blah

EVENTS:

march 1, 2010
blah blahb lah

may 3, 2011
blah blah blah

Is there a way to do this using Views alone or should I make a separate view for each section and use Panels to show the three views?

Any suggestions would be helpful.

You can use Views attachment to put them all together.  See example at http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments


How to create content type programatically how to create content type programatically and attach field api fields to it? hook_node_info() will not work for me since i want to create my node type and its instance in a single method (for testing purposes), so kindly suggest a solution other than hook_node_info().
Thanks

To create a node type, call node_type_save(). Have a look at the documentation of the Fields API for information on how to attach fields to the node type.


Using attributes in templates Twig I am a newbie. I have experience working with Twig but in Drupal it is used in another way.

I have seen a lot of code like that

<section{{ attributes.addClass(classes) }}>

And of course I read this article https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

There are a lot of examples and that is great.

But why do I need this, how could I use them to improve readability and flexebility ?

You should agree that attributes.addClass(classes) method is doing something like adding class to the existing attributes, but not returning the output of all attributes.

Could you tell me please why this attributes variable is useful, how can I use it to provide better decoupling or whatever it is used for. Why not just to keep classes directly in a template file, is it possible to add them from admin panel ?
Thanks

A general reason is that contributed modules or theme code can hook in and add attributes in. Outputting {{ attributes }} ensures that they are all printed without hardcoding them all in templates.

Here is an example.

I want to add a class and data-attr to an input field on a particular form. Instead of hardcoding it, I add to the #attributes key, and they are rendered out for me since {{ attributes }} is printed on the element:

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

My class and data-attr are added to that element automatically. I don't need to know what twig file is rendering it, I just need to provide the attributes I want to add on to, or print out.

Here are some links that explain a bit more in depth what Attributes are:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Template!Attribute.php/class/Attribute/8.2.x
https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file

I heard that in 8.3.x it will be easier to work with attributes, but I can't find the thread offhand.


How do I check a form is a node type form? I am writing a custom module and I want to add some condition in hook_form_alter() to check the form is a node type form.

Is there any function to check whether a form is for a node?

In the case you are referring to the node edit form (the form that allows you to edit a node), instead of hook_form_alter(), you need to implement hook_form_BASE_FORM_ID_alter(), which is a specific implementation of hook_form_alter() used when you know the form ID of the base form. In your case, you need to implement hook_form_node_form_alter() exactly how the Book module does with book_form_node_form_alter().
function book_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];

  // Omissis.
}

$form['#node'] is set by node_form(), which contains the following code. (Note the comment, which says that $form['#node'] is going to be removed in Drupal 8, and that modules should instead use $form_state['node'].)
// @todo D8: Remove. Modules should access the node using $form_state['node'].
$form['#node'] = $node;

In the case you are referring to the form you find at admin/structure/types/manage and that allows you to edit the properties of a content type, you need to implement hook_form_FORM_ID_alter(), which a specific implementation of hook_form_alter() done for a specific form ID, which in this case is node_type. This is what does the Comment module with comment_form_node_type_form_alter(). If you need to know the content type for which the form is shown, you can use $form['#node_type']->type.


Updating composer autoloader after moving modules I have been using composer to install all Drupal modules, when I realized that they had not been installing to modules/contrib. So, I added this into my composer file:
"installer-paths": {
  "modules/contrib/{$name}": ["type:drupal-module"]
}

Then, I moved all modules to /contrib under the modules directory, and rebuilt my cache with drush cr. No errors.
Now I cannot reload the site, I am getting fatal errors about missing modules at their old paths.
How do I clear the autoloader so it gets updated to look in modules/contrib instead of just modules for class files?
Attached picture of the error.
I tried removing the composer.lock file and running composer update - no dice.
Update
Looks like I did everything right, I just needed to reboot the VM to clear the APC cache.
Is there a way I could do that from command line instead of reboot the server?

I am using this to refresh module paths. I tried all other combos with apc_clear_cache etc and didnt help, also nginx restart didnt help, this 2 did.

service php7.2-fpm restart
drush cr


Multiple form submit I have a table of information displayed on a page. Each row of this table has its own submit button. I need to be able to pass information depending on what submit button is pressed.

The form is built like

function numberSubmit_form ($form, &$from_submit){
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

The rows of the table are built like:

$unvalRows[] = array(
            array('data' => '0'.substr($a[0], 2)),
            array('data' => drupal_render(drupal_get_form('numberSubmit_form'))),
        );

How am I able to determine which submit button has been used and pass the applicable phone number?

Add the phone number as an argument to numberSubmit_form and include it in your form array:

$unvalRows[] = array(
    array('data' => '0'.substr($a[0], 2)),
    array('data' => drupal_render(drupal_get_form('numberSubmit_form', $phone_number))),
);

Then in the form constructor:

function numberSubmit_form ($form, &$from_submit, $phone_number){
    $form['phone_number'] = array(
        '#type' => 'hidden',
        '#value' => $phone_number,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

It will then be available to you in the submit handler:

function numberSubmit_form_submit(&$form, &$form_state) {
    // do something with $form_state['values']['phone_number']
}


How to add google analytics code for onclick functions in drupal 6 My requirement is that, i need to my site to be tracked when i click on categories, menus, submenus, send mail button and shopping carts. Need to add onclick function for each  tags and that onclick functions need to be tracked.

What you're looking for is the GA Event Tracking module. It allows your custom module to select web page elements (via CSS selectors), bind them to jQuery events (e.g. clicks, mouseover, etc.), and send them out to the GA Event Tracking API.


Increase the Length of the block title field How to increase the length of the block title of a block?. By default its length is set to 64 characters. Please Help.

Thanks

That will be tricky. Block titles can only be 64 character. You need to alter the database and make the title field for blocks longer.

Put this in a custom modules .install file.

function mymodule_schema_alter(&$schema) {
  // Change length of title field for block.
  $schema['block']['fields']'title'] = array(
    'type' => 'varchar',
    'length' => 128,
    'not null' => TRUE,
    'default' => '',
    'description' => 'Custom title for the block. (Empty string will use block default title, <none> will remove the title, text will cause block to use specified title.)',
    'translatable' => TRUE,
  );
}

and then alter the block title maxlength attribute in a form alter

$form['block_settings']['title']['#maxlength'] = 128;

Another way is that you put your long title in the content of the block instead of using the "real" block title field.

In Drupal 7 I would hint you to checkout Bean module, but as this is Drupal 6 I'm not sure.


Convert links in content to internal form? If I create a hyperlink inside a text field (such as node body) with an internal path uri such as "node/1234" or "index.php?q=taxonomy/term/5678", then I can use an input filter such as pathologic to convert that uri at display-time to the preferred alias uri, such as "http://example.dev/path/to/my/content"

(I would consider this a more resilient way of storing content than using the full aliased uri)

However, I can't see an easy way for a non-technical user to find an internal path uri and paste it in.
Is there any way to get drupal to spot when a user has inserted an alias-based link into the content, and convert it into an internal path uri before saving to the database? I know the menu module does this with links, using drupal_get_normal_path(), but can it be done for html links in the content? Ideally with an existing D7 module?

For example, content like

More info at this link

would be converted to

More info at this link

before saving into storage.

Also, is there any existing online discussion about the advisability of this approach?

In terms of non-technical (which I read as custom development) solutions, what you're describing is one of the features of LinkIt.

  Linkit provides an easy interface for internal and external linking
  with editors and fields by using an autocomplete field. Linkit links
  to nodes, users, managed files, terms and have basic support for all
  entities by default. Linkit has three major advantages over
  traditional linking

It provides a WYSIWYG toolbar button from which a user can paste a URL for embedding a link. Upon setting up a LinkIt profile for you input type, there's a Insert paths as setting with a Raw paths option that defaults the inserted link as Drupal's internal path.


Extending a base template file such as field.html.twig renders no results? So I have a custom content entity that has the typical attributes. Name, Author, Creation Date, ect. In the 'view' tab of this content entity, it displays said name, author, ect.

When I hover over the name or title, it will display that this particular area uses field.html.twig as its default base template. I created my own custom template that extends the base template, and wanted to edit it so it would look different.

However, doing so renders the field invisible. I tried copying the base template and pasting it into my custom twig template, however the field is still invisible. Only when I delete my custom template does it revert back to the original base template and display the field.

Here is where I am confused. My custom twig template is taking precedence, it shows that in the debug info, but I am copying the field.html.twig code into my custom code before I start editing. Why then is the fields disappearing off the page or not rendering considering that I am using the exact same coding?

Just for reference, this is a custom module template and not a themeing template I am working with.

Here is a picture of what the field looks like when its displaying properly, otherwise it vanishs.

My hook theme code for this particular field:

  $theme['field__parent_task'] = [
    'render element' => 'content',
    'variables' => ['content' => NULL],
    'file' => 'task.page.inc',
  ];

I don't know what to put for the key names in the theme array, so I just copy and pasted from another one that was already there.

If you want to only override the field template.

Try with with the following.

Implement hook_theme like the following no needs for variables and file keys.

  /**
     * Implements hook_theme().
     */
    function myModule_theme($existing, $type, $theme, $path) {
      return [
        'field__parent_task' => [
          'template' => 'field--parent-task',
          'base hook' => 'field',
        ],
      ];
    }

Create templates folder in your module root.
Create field--parent-task.html.twig inside your templates folder.
Copy and the paste the base template code into your template file.
Clear the cache.


Looking for core Drupal table DDLs My Drupal 7 installation has a handful of tables that have been corrupted. Attempts to repair them have not been successful so my best chance of being able to move forward is to recreate them.

I have not been able to find the DDLs for the tables that are corrupt so my question is, where might I find the DDLs for the core Drupal tables so I may recreate them?

The 2 tables that seem to be giving me the most grief because they are not available are field_data_field_files and field_revision_field_files.

Those tables are generated dynamically by the field API, and as such don't have a pre-built DDL. This is essentially because fields can be added through the UI/programmatically after installation. Rather than keeping a monolithic registry of those fields and values, the architectural decision was made to split them out into dynamically-created tables with a conventional structure.

If you have corrupt field tables it's a bit...awkward. Drupal will already think the field exists because it'll still be listed in field_config and field_config_instance, so trying to add it again with the API/UI isn't going to work unless you also prune those records.

Those records may also be referenced elsewhere (possibly in serialised PHP strings, no less), and there's no referential integrity of any sort here anyway, so you'd have to be able to work out what types of referenced record you could have, be able to identify them all, and nuke them. Not exactly easy.

The easiest approach will probably be a bit of a hack job; get the DDL of another field table, and twist it to match the table you've lost:

mysqldump -d -uroot -p <dbname> field_data_body

Give us

DROP TABLE IF EXISTS `field_data_body`;
CREATE TABLE `field_data_body` (
  `entity_type` varchar(128) NOT NULL DEFAULT '' COMMENT 'The entity type this data is attached to',
  `bundle` varchar(128) NOT NULL DEFAULT '' COMMENT 'The field instance bundle to which this row belongs, used when deleting a field instance',
  `deleted` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'A boolean indicating whether this data item has been deleted',
  `entity_id` int(10) unsigned NOT NULL COMMENT 'The entity id this data is attached to',
  `revision_id` int(10) unsigned DEFAULT NULL COMMENT 'The entity revision id this data is attached to, or NULL if the entity type is not versioned',
  `language` varchar(32) NOT NULL DEFAULT '' COMMENT 'The language for this data item.',
  `delta` int(10) unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields',
  `body_value` longtext DEFAULT NULL,
  `body_summary` longtext DEFAULT NULL,
  `body_format` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`entity_type`,`entity_id`,`deleted`,`delta`,`language`),
  KEY `entity_type` (`entity_type`),
  KEY `bundle` (`bundle`),
  KEY `deleted` (`deleted`),
  KEY `entity_id` (`entity_id`),
  KEY `revision_id` (`revision_id`),
  KEY `language` (`language`),
  KEY `body_format` (`body_format`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Data storage for field 7 (body)';

Replace the table name and comment. Remove body_value, body_summary, and body_format columns, and the body_format index. These are specific to the body field type, the rest is boilerplate and common to all field types.

It seems likely your field type was a file reference, so you need to find the columns for that field type's schema. These are in file_field_schema(); mix these into your edited DDL:

`field_files_fid` INT(10) unsigned NOT NULL,
`field_files_display` TINYINT(3) unsigned NOT NULL DEFAULT 1,
`field_files_description` TEXT DEFAULT NULL

(add comments if you wish)

And an index for the file ID:

KEY `field_files_fid` (`field_files_fid`)

Repeat for the revision table (using field_revision_body as a starting point), and you should have your table structure back in place. At this point it would be a good idea to restore the data to these tables from a backup, as they reference entities in the file_managed table (and can have references elsewhere throughout the system).


Is it possible to make hook_view() the same as hook_edit()? My current client does not like the separation between viewing their custom content types and having to travel to a different page to edit. They are pushing for the View page and the Edit page to be the same. Are there any negative ramifications of simply redirecting from hook_view() over to hook_edit()?

The client is a desktop application developer, with a large installed base of clients, and I'm making the first "web version" of their desktop software. They want their webapp to behave as close as possible to their last desktop version. Their application is sorta like a CAD/3D-Modeler, and "viewing a model" without the ability to make any edits makes no sense for their users. Hence the request to get rid of hook_view() and make hook_edit() triple functional (create,edit & view).

Supposing that "model" is the content type you are referring, then I would use code similar to the following one.

function mymodule_menu_alter(&$items) {
  $items['node/%node']['title callback'] = 'mymodule_node_title';
  $items['node/%node']['title arguments'] = array('view', 1);
  $items['node/%node']['page callback'] = 'mymodule_node_page';
  $items['node/%node']['page arguments'] = array('view', 1);
  $items['node/%node']['access callback'] = 'mymodule_node_access';
  $items['node/%node']['access arguments'] = array('view', 1);
  $items['node/%node/edit']['title callback'] = 'node_node_title';
  $items['node/%node/edit']['title arguments'] = array('edit', 1);
  $items['node/%node/edit']['page callback'] = 'mymodule_node_page';
  $items['node/%node/edit']['page arguments'] = array('edit', 1);
  $items['node/%node/edit']['access callback'] = 'mymodule_node_access';
  $items['node/%node/edit']['access arguments'] = array('edit', 1);
}

function mymodule_node_access($op, $node) {
  if ($node->type == 'model') {
    return ($op == 'view') ? node_access('edit', $node) : FALSE;
  }

  return node_access($op, $node);
}

function mymodule_node_page($op, $node) {
  if ($node->type == 'model') {
    return node_page_edit($node);
  }

  if ($op == 'edit') {
    return node_page_edit($node);
  }
  if ($op == 'view') {
    return node_page_view($node);
  }
}

function mymodule_node_title($node) {
  if ($node->type == 'model' || $op == 'view') {
    return node_page_title($node);
  }

  if ($op == 'edit') {
   return t('Edit');
  }
}

Using this code, the node edit form is always show accessing /node/%node, or /node%node/view for the "model" content type.


How to get body field within THEME_page_alter Possible Duplicate:
  How do I access node body from template.php?

I've actually asked this previously, but I received an unsatisfactory answer, and thus my question was forgotten, as it was marked 'answered'.

My aim is to have a meta description on my front page, and a meta description for each of my blog entries, I'm using THEME_page_alter to achieve this. Both the metatag and metatags_quick modules don't seem to work properly despite several hours of changing settings.

Here is the code located in my template.php:

function vertaxe_page_alter($page) {
    $description = 'My default desc';
    if (!empty($page['content']['system_main']['nodes']) && is_array($page['content']['system_main']['nodes'])) {
        foreach ($page['content']['system_main']['nodes'] as $nid => &$content) {
            if ($content['#node']->type == 'blog') {
                $description = '';
            }

        }
    }

    $meta_description = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'description',
            'content' =>  $description
        )
    );

    drupal_add_html_head( $meta_description, 'meta_description' );

}

How do I get the node's body field for use in my description?

According the hook_page_alter() documentation you should be able find the body like that.

$description = $page['content']['system_main']['nodes'][$nid]['body'];

But if you still have the problem you can display all data from your page with the help of Devel module or simply with a print_r($page); and look where is the content that you're looking for.


Dealing with hook_cron when configuration is required What's the best way in dealing with functions that require configuration in a hook_cron?

Example (pure fiction):

My hook_cron calls function_close_ticket, this function has various variable_gets all of which have defaults but those defaults may not be relevant to the users setup (they are however relevant to a default casetracker setup), especially if the user has customised casetracker a lot.

Would I be best leaving as is and letting hook_cron fire or wrapping the function inside in a call to get the state of a user configurable variable? Or is there some other way of dealing with this problem?

If you require configuration, then you shouldn't provide a default value using variable get (You provide an empty default value instead). If the no value is set, you should make a log using watchdog and exist without doing anything, since the conf was missing.

If you can provide a default settings that would make everything work, that would be a better option, since the user don't have to do any setup, be can if he wants to.

The checks should not really happen in cron, but in the function actually doing whatever needs to be done.


How to display entity label using entity reference field checkbox form display I am working with Drupal 8. And I want to create a field of entity_reference type. The field has a reference to context_question entity. And the field is displayed fine, but without any description beside the check boxes.

The context_question entity has a label field and I want exactly the label be displayed beside the checkbox in my first entity. What should I change in the code? Or do I need to create the fieldFormatter?

$fields['context_question'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Context Question'))
  ->setDescription(t('Reference to context-question-type'))
  ->setSetting('target_type', 'context_question')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'format' => 'label',
    'weight' => 15,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => 15,
  ))
  ->setCardinality(1000)
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I assume the context_question is your custom entity or coming from a contrib module?

There are two options:

Add label key to context_question entity definition under entity_keys so that Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection pick it up. See Aggregator item for reference.
Add a @EntityReferenceSelection plugin. You have to define one. Check TermSelection for how it is implemented for terms. It looks like this:


Which cache bin to clear after changing services I made some changes to own services and now I get an error about invalid arguments. When I clear all caches everything works fine. I don't want to clear all caches in my production environment. Which cache bin (and how) do I need to clear? I use drupal console. I tried 'drupal cache:rebuild container' but I get a message 'Cache container is invalid'.

Drupal Console uses Cache::getBins() for its list of valid cache bins - that method returns all services in the main container tagged with cache.bin. The container cache service is part of the bootstrap container, which is managed internally by DrupalKernel.

I haven't dug deep enough to know for sure, but keeping the management of that bin internal seems to be deliberate, so there's probably no simple (maybe even no desirable) way to hack around it.

Fortunately, a custom plugin for Console is easy to create with drupal generate:command (there's a tutorial here). Just be sure to inject the kernel service, and call $this->kernel->invalidateContainer(); in the command 's action callback.


Content Lock on Entityform nodes? In Drupal 7, it appears that the Content Lock module (which prevents concurrent editing of nodes) is not able to work its magic on Entityform-based nodes. Is there a workaround? Something similar with Entityform capabilities?

You might get it to work by implementing an "edit-in-progress" (= EIP) feature using the Flag module, combined with using the Rules module. Similar to what I described within "Option 1" in my answer to "Can the Flag module be used to lock content while editing to prevent concurrent edits?" (BTW, that question is a variation of yours, not a duplicate though ...).


Passing arguments to a block I am working on trying to understand the secrets of custom-developed blocks. Namely, I have a use case where a block need to pull content via EntityFieldQuery (this could be done with Views, but I like a challenge) and the contents loaded need to adjust based on a URL argument.

Right now my running assumption is that since the page that will deliver these results is run through Context, my best bet for getting values from the URL are through arg() when the block is generated inside its referencing callback from hook_block_view(). I just want to be sure this is the best approach to actually load values that must be passed in through this approach, and i'm not missing a more reasonable design pattern.

Code example is below.

/**
 * Implements hook_menu
 */
function widgets_and_springs_menu() {
  $items['springs/%'] = array(
    'title' => t('All Springs for Category'),
    'page callback' => 'widgets_and_stone_blank_page', //Returns theme of '', enough for Context to catch
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array(1),
  );

  return $items;
}

/**
 * Implements hook_block_info()
 */
function widgets_and_springs_block_info() {
  $block['springs_listing'] = array(
    'info' => t('All Springs Per Category'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $block;
}

/**
 * Implements hook_block_view()
 */
function widgets_and_springs_block_view($delta = '') {
  $block = array();

  switch($block) {
    case "springs_listing":
      $block['subject'] = "";
      $block['content'] = widgets_and_springs_get_results_by_uri_arg();
  }
}

/**
 * Returns arguments by URL. First item MUST contain a TID argument.
 */
widgets_and_springs_get_results_by_uri_arg() {
  $searchTid = arg(1);
  //Other stuff & Return of results within theme()...
}

It's not uncommon to customize block contents based on URL arguments. I don't see any reason to not do that.

However, since your block contents can change based on the URL, you need to use either no cache at all or DRUPAL_CACHE_PER_PAGE.

If your block contains any Ajax elements, note that arg() will return the ajax path.


How to override a JS function in the Media Module without editing the actual module files? Drupal.media.browser.validateButtons = function() {
    // The media browser runs in an IFRAME. The Drupal.media.popups.mediaBrowser()
    // function sets up the IFRAME and "OK" and "Cancel" buttons that are outside
    // of the IFRAME, so that their click handlers can destroy the IFRAME while
    // retaining information about what media items were selected. However,
    // Drupal UI convention is to place all action buttons on the same "line"
    // at the bottom of the form, so if the form within the IFRAME contains a
    // "Submit" button or other action buttons, then the "OK" and "Cancel"
    // buttons below the IFRAME break this convention and confuse the user.
    // Therefore, we add "Submit" and "Cancel" buttons inside the IFRAME, and
    // have their click action trigger the click action of the corresonding
    // "OK" and "Cancel" buttons that are outside the IFRAME. media.css contains
    // CSS rules that hide the outside buttons.
    //
    // We don't add a "Submit" button if the form already has one, since in these
    // cases, another round-trip to the server is needed before the user's
    // selection is finalized. For these cases, when the form's real Submit
    // button is clicked, the server either returns another form for the user to
    // fill out, or else a completion page that contains or sets the
    // Drupal.media.browser.selectedMedia variable. If the latter, then
    // Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad() auto-triggers the
    // "OK" button action to finalize the selection and remove the IFRAME.
    //
    // @todo An alternate, less hacky solution would be most welcome.
    if (!($('.form-submit', this).length > 0)) {
        $('Submit').appendTo(this).bind('click', Drupal.media.browser.submit);
        if (!($('.fake-cancel', this).length > 0)) {
            $('Cancel').appendTo(this).bind('click', Drupal.media.browser.submit);
        }
    } else if (!($('.fake-cancel', this).length > 0)) {
        var parent = $('.form-actions', this);
        if (!parent.length) {
            parent = $('form > div', this);
        }
        $('Cancel').appendTo(parent).bind('click', Drupal.media.browser.submit);
    }
};

(See also http://jsfiddle.net/S6WXc/.)

This function in the Media Modules js/media.browser.js is clashing with what I've added into the Media Select popup via Form Alter (A simple AJAX call to display thumbnails of images, that when clicked open up in a Colorbox modal window).

I've tracked the problem down to something in Media Module and Colorbox clashing, since when I click a thumb that opens the Colorbox modal popup, an event is launched that duplicates the 'fake' Submit / Cancel buttons in the Library tab, and also some of the Library thumbnails (my own thumbs are shown in the Web tab).

Not going in further detail, is there some way to override the function in the Media Module without editing the actual original .js file? I don't fancy doing edits each time I update it so to override it in my module or my own .js file would be preferable.

You can simply do it like that :

Drupal.media.browser.validateButtons = function(){ // Your code ... };

Of corse, this assignment must be after the original one.


Inserting Taxonomy Images into nodes In Drupal 7 i have added a new taxonomy vocabulary, then added a new field (image field) into this vocabulary and terms with image (logo). In the content type i've added a new field (term reference). But in the node i can see only title of the taxonomy term. How i can insert imagefield into the node from taxonomy terms?

I've done something similar by using a template for the taxonomy term based on template suggestions. Personally I prefer writing theming functions though, and example for how to do this for a taxonomy field can be found in template.php of the default Bartik theme that comes with Drupal. Look for bartik_field__taxonomy_term_reference and here is the api documentation for theme_field().

You will need to install the devel module, which will give you a dump of the node object when you are viewing a node.

You will need to either theme the entire node with specific care taken to render the taxonomy how you want from the node object, alternatively you could just theme the actual term reference field (What I first mentioned and the best way imo.) These are instructions on using the devel module.

With that you will be able to dump the array or object relating to the taxonomy term and then create a template or function theming the field to your liking, as far as I know all the information is available there it's just getting it out of the object/array can be time consuming when you are doing it for the first time.

Overall the Drupal Theming Guide covers the finer details in a lot more detail than what can be kept to a reasonable answer here.


Create a view with user selected fields I need to create a view with user selected fields. My basic requirement is data export. My site contains around 1500 nodes and each node has around 25 fields. I have a view for data export with 5 fields.

My specific need is to create a control panel for selecting the fields i want – and in a following step I have to create a view with the selected fields.

Sounds as you need Views Dynamic Fields. From the project page:

The Views Dynamic Fields module provides a filter for use with Views module. This filter allows the user to pick and choose which fields to display for a rendered instance of a view for that user. This provides a customized view instance for each user.
This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.


How to use url alias in views for taxonomy terms? On a Drupal 7 site with pathauto installed I'm using a view to show all taxonomy terms of a given node. The terms are linked to the term's page. The problem is, that the path of those terms does not use the url alias' that are set for the terms. Is there a way (without programmatically rewrite the view) to use alias in a view?

I know about the globalredirect module, but a redirect is not a clean solution here, in my opinion. And I do not understand why the pathes aren't replaced by there aliases in a view, can someone explain please?

This is a kind of workaround but
I thinks the simplest solution for you would be to use the module:
TVI: Taxonomy View Integrator

Then when when you modify the terms vocabulary you can use a view to replace the default page default view:  the url alias of the term alias would call your view.


Import RSS Feed Programatically I have content in an RSS feed that I'm looking to import into separate nodes. I set up a feed importer, and when I run manually, all works as designed (content is imported, fields mapped properly, etc.).

That said, I need to be able to import from the RSS feed on a regular basis. Unfortunately, Elysia Cron won't work, as I don't have access to the crontab on the server. Can this be done programmatically, and on a regular basis?

Thanks!

There is an option in feed import module settings (admin/config/services/feed_import/settings), where you can set to import your RSS when the cron runs ("Cron import" checkbox).

If you do not have access to crontab, you cannot schedule cron from server side, but if you set cron interval at admin/config/system/cron, cron will be also triggered on, when the time elapses and there will be site visitors on your page (cron will be triggered by one of the site visitors).

Source here.

Edit:
If you would like to run cron each 5 minutes (or other custom interval), you will need custom module and implement hook_init(), which is executed on every page load, when the module is active. See the example:

function mymodule_init(){
  //get variable content (last cron run time), if not exists, return 0
  $last_cron_run = variable_get('mymodule_cron_run', 0);

  //if it was more than 5min before
  $five_minutes = 5 * 60;
  if($last_cron_run + $five_minutes < time()){
    //run cron
    $result = drupal_cron_run();

    //do with $result what needed

    //set last cron run time to variable
    variable_set('mymodule_cron_run', time());
  }
}


Call a JS function when a views ajax request completes? I want to run some JS stuff on the exposed filters of a view which uses ajax. How can I know every time the view is reloaded by ajax, and run some JS?

You can find ahah/ajax success by this function.

Not a Drupal Way.

$(document).ready( function () {
 $('body').bind('ajaxSuccess', function(data, status, xhr) {
  alert('Ajax Success');
 });
});

This function will get invoked on every ajax success.


Dynamic pricing of products/line items with a "pricing entity" I'm trying to achieve a pricing functionality in which product/line item's price is configured in an external entity. So that I can have one product which can be priced by multiple entities depending on which is being viewed.

This external entity is a "host" entity or a product display which has two fields: product reference and a price field (float).

Now, when customer visits this host entity page and adds a line item to cart it should change the price according to host entity price field.

At first I tried this with Rules but it was just so inconsistent that I decided to look other options. So here's a piece code that I think could solve this:

    // Alter the price in list and single product page.
function commerce_dynamic_pricing_commerce_product_calculate_sell_price_line_item_alter($line_item){

    if ($node_wrapper = entity_metadata_wrapper('node',_commerce_dynamic_pricing_menu_get_any_object()) ) {

        if ($node_wrapper->type->value() == "price_list") {

            $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

            dsm($line_item_wrapper->commerce_unit_price->amount->value(). 'Old price');

            foreach ($node_wrapper->field_collection_licenses as $key => $license) {
                if ($line_item_wrapper->commerce_product->product_id->value() === $license->field_license->product_id->value()) {
                                            $line_item_wrapper->commerce_unit_price->amount->set($license->field_license_price->value());
                }

                $line_item_wrapper->save();
            }

            dsm($line_item_wrapper->commerce_unit_price->amount->value(),'New price');
            }
        }
}

The problem with this code is that the price isn't changed/updated. I'm not sure that how the price should be modified.

So this first alter hook handles price on product display.

But price needs to be handled again with another hook: commerce_dynamic_pricing_commerce_cart_line_item_refresh.
This handles prices regarding current line items in cart.

I also needed to avoid combining same type of line items into "quantity groups".This works well in:

    $line_item->data['context']['add_to_cart_combine'] = FALSE;


Drupal 8 Image Styles Not Generating - LEMP on CentOS 7 Centos 7
Nginx 1.10.2
PHP Version 7.1.5
Database 5.5.52-MariaDB
Drupal 8.3.2

I have exhausted just about every possible google result and every forum post I can feasibly find. Thank you in advance for any help you can offer me.

PROBLEM:
Images are uploading to the appropriate folders under /sites/default/files/WHATEVER-SUBDIRECTORY

Image styles are not generating under the /styles folder and I am getting broken images whenever they should appear on-page.

I HAVE TRIED:

Rewriting my Nginx config.
Setting all permissions to 777 (for testing purposes).
Adding $conf['image_allow_insecure_derivatives'] = TRUE; to
settings.php.
All directories and files are owned by the correct user/group.
Flushing cache as well as image stores.
The only type of errors I have been able to find are in my nginx
access.log: "GET
/sites/default/files/styles/large/public/2017-05/my_image.jpg?itok=Ax9jzc70
HTTP/1.1" 404 571 "https://mysite.mysite.come/node/1" "Mozilla/5.0
(Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/58.0.3029.96 Safari/537.36" "-"Safari/537.36" "-"

nginx.conf:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    server {
        listen 443 ssl http2;
        server_name     mysite.mysite.com;
        root /var/www/drupal;
        ssl_certificate SSL CERT HERE;
        ssl_certificate_key SSL CERT KEY HERE;
        ssl_session_cache shared:SSL:100m;
        ssl_session_timeout 30m;
        ssl_protocols TLSv1.1 TLSv1.2;

    location / {
        try_files       $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ /vendor/.*\.php$ {
        deny    all;
        return  404;
    }

    location ~ \.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        fastcgi_param   HTTP_PROXY "";
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param   PATH_INFO $fastcgi_path_info;
        fastcgi_param   QUERY_STRING $query_string;
        fastcgi_intercept_errors        on;
        fastcgi_pass    127.0.0.1:9000;
    }

    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found   off;

    }

    location ~* /sites/.*/files/styles { # For Drupal >= 7
        access_log      off;
        expires         max;
        try_files $uri @rewrite;
    }
    }

server {
listen       80 default_server;
server_name  mysite.mysite.com;
root         /var/www/drupal;
return 301 https://$server_name$request_uri;
}
}

Everything else seems to be working like a dream, but I can't for the life of me seem to figure out these image styles. Any guidance would be greatly appreciated. Thanks again.

I finally found a solution to this problem! As it turns out, systemd is configured to give php-fpm a private /tmp. I had to edit the .service file to set PrivateTmp=false. It is worth noting that if you're running multiple sites on of the same server, PrivateTmp should be set to =true for security reasons.

For reverence, here is the thread that saved my rump in the end.

Thanks again.


How do I add client-side form validation to a Drupal form? How do I add client-side form validation to a Drupal form?  For example, in the comment module.  If the vistor don't enter the email address, I want to popup a window that says: "please enter the email address".

I hope someone can give me an example of how I do this.

I'm biased since i created http://drupal.org/project/clientside_validation, but it is using http://bassistance.de/jquery-plugins/jquery-plugin-validation/ to do all validations, the benefit of the module is that you don't have to write any code


Notice: unserialize() [function.unserialize]: Error at offset 0 of 13 bytes i UserController->attachLoad()? I've created my first module, which gives me this error and I dont know where to look for the error.

The module is a list of nodes sorted by terms. Each node has a checkbox connected to a form (using Form API), which lets the user sent multiple emails at once to the author of that node. The data is then inserted into the database for further use. The funcion seems to work and the node authors gets its own rows in the table, but why this error?

It is shown when the form has been submitted, btw.

Drupal 7

Notice: unserialize() [function.unserialize]: Error at offset 0 of 13 bytes i UserController->attachLoad() (row 303 of /drupal/modules/user/user.module).

Take a look at the Variable Check module (http://drupal.org/project/variablecheck). That will give you a list of the variables stored in your db that are causing the problem. Once you've identified those bad variables, you can delete them from the 'variable' table in your database.


How to provide a translation for a string used within t()? On my site I use a module which creates text using t('text from module'). How can I tell drupal that I have a translation for that, and of course, that my translated text is being displayed?

First, make sure you install the Localization update module.  It is the key to handling anything that has to do with translation.  Enable automatic translation updates.

If the module is an "official" module with a stable release. the Localization update module will pull down translations from localize.drupal.org - provided they exist.  If they don't exist, you should provide them (read about how you can contribute on localize.drupal.org) - and the Localization update module will install them for you within 24 hours (if you've enabled automatic updates).

If the module does not have a stable release, there will not be anything on localize.drupal.org.  In that case, you must add local translations using the built-in translation interface.


How to use two different image styles on teaser? I want to use Medium image preset on teaser when the article is featured, then change to thumbnail style after. Is it clear? For example, in a cuisine recipes website I want to show a "Recipe of the Day" with a medium style image and tomorrow that recipe will be change by the newest ("Recipe of the Day") and shown with thumbnail style. Is it possible?

Thanks in advance.

Alex

You can use Entity View Modes

It will give you the chance to set up a new view mode and change it from Manage Display page.
You can create 2 view modes, one for Sticky e one for Recipes of the day.
From views page, open the sticky display, click on "Show -> Content > YOUR_VIEW_MODE" and repeat it for the Recipes of the day display/view.

In the manage display page you can set up the image style for the View Mode.


Add sitemap.xml inside a view I already generate my xml sitemap with drupal module "sitemap" now i wanted to show that sitemap inside a view.

It is possible to do this?

Thanks

No, or at least not, with XML Sitemap & Views module. There is no Views integration with the XML Sitemap module. Given how both these modules work (a view being defined by base table & XML sitemap trying to generate a list of all indexable site paths), I think you'd be better off looking for another solution to embed all your site paths into the site.


Change authoring information on multiple nodes How can I change the publication date for multiple nodes at the same time without to individually edit each node?

You may be able to use Views Bulk Operations (VBO).

  This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.


How to test for a boolean field in a twig template? field_boolean is a boolean field.

{% if content.field_boolean == true %} or {% if content.field_boolean == 1 %} or {% if content.field_boolean == 'true' %} or {% if content.field_boolean == '1' %} don't work.

How do I test if the checkbox is checked?

You want to look at the raw value, not the render array.

Example:

{% if node.field_foo is not empty %}

This checks if the field exists. The render array won't be useful beyond rendering values.

Don't look at content - that is simply the render array. Look at the fields in your entity object (node, paragraph, etc). You might want to install Twig XDebug to breakpoint your templates or inspect variables in mytheme.theme.

You should be able to look at {% if node.field_foo.value ... %} for equality checking.


Display webform in a modal I am trying to display my webform in a modal (including error/validation messages inside the modal). I am following this approach for a custom drupal form which is not a webform. I am wondering whether this is possible at all with webforms and in case it is, what I need to take into account to make it run?

The first problem I am having is the following code line from the example's TeacherContactController.php

$modal_form = $this->formBuilder->getForm('Drupal\tl_session\Form\TeacherForm');

When I try to use this in my own controller, I cannot get the webform's proper namespace + id. When I check my webform with devel it says:

[__CLASS__] => Drupal\webform\Entity\Webform
  [id] => add_news_webform

But I get a "The form argument Drupal\webform\Entity\Webform\webform-submission-add_news_webform-form is not a valid form" error. I tried many things, but did not succeed.

How can I get the webform with formBuilder and what else am I missing here (like webform specific ajax settings etc.)?

Displaying a weform in modal (might be called popup as well) it is a lot simpler than you thought
Lets assume your webform has URL /contact than you can create a link in the following manner
Contact US

Pressing that link will have your form open in a modal with error validation and messages inside the modal
NOTE:
At least in my case I had to also add the following hook_preprocess_page in the .theme file
function THEMENAME_preprocess_page(&$vars) {
    //custom logic of when to include the library
    // ....
    $vars['#attached']['library'][] =  'core/drupal.dialog.ajax';
}

Some people have reported that this is not needed but I assume some other module included this library for them ...


best reference to theming I'm completely new to drupal and am starting to take interest in the process of theming. I was wondering if anyone could suggest a reference or perhaps even just insert a snippet of code explaining the basic template.

I have some PHP experience but nothing too complex. I'd really like to learn how to apply javascript into my themes and what the best approaches would in terms of that. I attempted the other day to insert some HTML via the regular "create content" section and then wrote a stylesheet to correspond to said HTML, I linked via the template.info file, but it didn't work because Drupal had renamed all of my div's. Is that normal?

Sorry if my question seems to be too broad in scope, I guess I just need a direction or map and I'd be fine. Thanks in advance, and looking forward to becoming a contributing member of this community.

I recommend the theming chapter by @jacine in Definitive Guide to Drupal 7 - http://definitivedrupal.org/. Not free but well worth it.


Is there a module for user level permissions? I know that permissions are controlled by admins. I want regular users to control a different set of permissions, for example my users will have pictures, friends list, personal information in there profile. I want them to be able to create groups and limit access so certain groups can see certain content. Is there a module for this or do I need to put on by big boy paints and start coding?

Yes! Check out the Role Delegation module. Here is a quote from its project page:

  ... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.


Why do the database functions return all fields as strings? db_select('my_table', 'a')
   ->fields('a')
   ->condition('a.campaign_id', $entity->campaign_id)
   ->execute()
   ->fetchObject();

my_table has some columns that are integers, but the query above returns strings.

Why does this happen? It seems strange to me that the query ignores the column types.

The DatabaseStatementBase::fetchObject() method is inherited from PHP's PDOStatement::fetchObject() which returns the object columns as strings. Given that not all RDBMS's have the same set of types & PHP isn't a strongly typed language, it was probably decided to return everything as strings since it's a base datatype that can be relied on.


How to create a URL with $_GET values by writing my own custom module? I am writing my own module and I would like to know how to create a URL from a search form that utilizes $_GET requests so I can pass those arguments into my query.

The Views module is a good example.  For example, after you create a view and have exposed filters, your Views URL would look like:

CustomView?field_data_field_year=2012&field_data_field_month=december

Currently my hook_menu looks like:

function papers_pub_search_menu() {
  $items['papers_pub_search'] = array(
      'title' => 'Papers and Publications Search',
      'description' => 'Search Papers and Publications',
      'page callback' => 'papers_pub_search_viewer',
      'page arguments' => array(1,2),
      'access arguments' => array('access papers and pub search'),
      'type' => MENU_CALLBACK,
  );
  return $items;
}

My problem is the 'page arguments' => array(1,2).  It seems like the format of the URL would be "foo/bar" and it would strictly need 2 arguments.  My user may pass 1 or 3 arguments based on what parts of my form fields they fill out.

Another simple example, if I wanted to do this in pure PHP, it would be trivial:

<?php
if($_GET['submit']) {
  $name = $_GET['name'];
  $query = "SELECT name FROM user WHERE name = $name";
  ...
}
?>
<form action="form.php" method="get">
  <input type="text" name="name">
  <br>
  <input type="submit" name="submit" value="submit">
</form>

What I am trying to do is create a form where a user can fill out some fields, and then do some DB query based on what the user has inputted into various text fields and pull down choices once they hit submit.

If I understood your question correctly, you are mixing the URL arguments and query string.

You can have as many query string arguments as you want and you do not have to define them upfront. Drupal will not limit you. An example of query string is page?arg1=123&arg2=456, just like what views module does for filters. This is what you need for your $_GET form.

What you define in the hook_menu are URL arguments - for example one/two/three. You can get them by using the arg() function, so arg(0) in the example above would return one, arg(1) would return two etc.

UPDATE

  So is the URL arguments in hook_menu not needed (i.e. page arguments)?

Yes, you don't need it in this case. You will solve everything by using query string (~question mark in the URL).

  Does 'page?arg1=123&arg2=456' not count as an argument, or is that just one big argument (i.e. arg(0))?

That is only one argument. arg(0) would return just page. arg1 and arg2 are query string parameters.

Think of page argument as a part of the base URL for the page.
Query string is what goes after the question mark.

You should use filter_input() instead of simple $_GET as it is much more secure.

See also drupal_get_query_parameters().


Line break Twig question I want to add line breaks in title field
I managed to use the replace functions in the template >

{{ node.getTitle()|replace({'|': '<br />'}) }}

Replacement works, but outputs the field as non-HTML. Do you know about a way to force an HTML output? Or any other way to be the  a real line break instead?

It should help to use the raw filter, like @leymannx commented, but then your template is unsafe, because you should never use the raw filter on template variables containing user input.

So escape the node title first, then add the HTML (which you know is safe because it's hardcoded), before passing it through the raw filter:

{{ node.getTitle()|e|replace({'|': '<br />'})|raw }}


Best approach for a minimal HTML5 theme for Drupal Feel like I'm stuck between a rock and a hardplace, I've decide to post.

I'm looking for answers/opinions on getting going on custom Responsive Drupal v7 theme dev using ONLY HTML5/CSS/Less/Responsive with a primary focus on mobile then desktop with a view to it being a MINIMAL design set.
I'm not an IT newbie having been in IT since '86 and then earlydays webdev HTML usage since '97, but due to a health/career change I've recently had to 'upskill' again and hence back in IT and focused now purely on D7 by choice. A lot has changed since '97 and early HTML and now I'm wreaking my brains looking at the best approach to contemporary webdev trends (ie Less/HTML5/CSS/SCSS). I don't really want to use 'off the shelf' free D7 themes as I want to be able to theme myself again using the above. I most definately like the idea of HTML5 Boilerplate/360 and the mobile future.

Numerous hours researching online has left me confused (LOL) with all the available Responsive frameworks (CSS: 360 and up, 1140, inuit/Less etc etc).

So my query here is:

best approach starting grid for webdev on the above technologies at this entry level of learning. (I like building things so I'm keen as an all rounder, as I think I have way long mised the boat on becoming a 'themer' so my interests lay in 'lego' building in Drupal so to speak).
should I skip early CSS theory and go straight into Less/SCSS? (html5 will be easy to pick up on me thinks).
which single Responsive model should I pick to start out with then?

FYI, I'm now on a Linux Ubuntu 11.04 LAMP DEVBOX using a range of tools such as Aptana (and comfortable on a pure text editor) having moved over from M$ but I still have 3 other M$ comps due to other multi-media/pro-music interests.

I've been 'hacking' some D7 themes, but feel I can't see to 'wood for trees' when it comes to hacking to vast amount of data in the css files and feel I'm over whelmed in simply wants to create simple, minimal css so much taht it may be just easier starting from scratch.

Any advice to get me going immediately in the right direction would be most helpful.
Thanks in advance.
Paul, UK

Less or SCSS are not that dissimilar to CSS (since they compile down to CSS anyway), they just have some additional features (such as mixins) and have in some cases a nicer layout. I personally have used scss and Compass to compile my scss, and also for the ability to include resets and things automatically without having to add in your own reset.css file.

In terms of learning Drupal themes, you have a choice, either use something like the omega base theme and subtheme that, or alternatively start from scratch with a clean, empty folder with the following in it:

exampletheme/
    css/
    templates/
    js/
    exampletheme.info
    template.php

And build up from there. The existing themes, whilst good for some information, are very content-heavy (by virtue of being mature, complex themes). Use a browser such as chrome/firefox with firebug in order to find out what elements are tagged or classed as. The drupal.org theme guide and the specific section on d6 & d7 is quite a good place to start.

As far as grid frameworks, I started using 960 grid as that was something which conceptually struck a chord with me. They all have similar features, though the way they work in practice is different.


How do I let my users create organic groups? [n00b apologies] I have installed Organic Groups but am apparently too dumb to understand it.

How do I let me users create and administer their own groups? What do I need to do on the admin pages, and how do I add something on the main page to let them administer & join groups.

Sorry if this sounds dumb

Update: if they can't, and I have to - how do I add a "groups" item to the man menu and a sub-menu for each group?

see documentation for Drupal 6 http://drupal.org/documentation/modules/og or Drupal 7 http://drupal.org/node/1114852.


D6.22 - attach content to node type I was wondering if its possible to setup a facility where I can attach content to existing content?  Let me elaborate...say I have my Page nodetype, but I want to give the content-editor the ability to add extra information to it that can be displayed in a separately styled div (I do not want the editors playing around with the HTML - they don't know how to anyway). This must be a zero-or-one relationship.

I'm thinking something like the nodereference_url module, except that I want to limit the amount of node references to a maximum of one. Does anyone how this can be achieved? Thank you!

This is actually pretty easy.

Edit your content type (or clone to a new type).  Add in a noderefernce CCK field as needed.  Configure it for not mandatory, but limited to one value.
Edit the fields for the type so that they are all hidden.
Add a preprocess_node for your content type in template.php to read in the node relationship, theme the node, and then add it as a theme variable.
Create a node template for your type.
Edit the node template, to add in your div in the markup.
Print out this theme variable in the node template.

This should get you down the right path.


Views: Display number of nodes published by author on profile Using Views, I can create a list of authors, and show the number of nodes that they have published. I've done this using aggregation. The part I can't figure out is how to filter the output based on the user profile that you're viewing. For example, if you're viewing user/1, I want you to see the number of nodes that user 1 has published.

I've tried using different uid contextual filters. In this example, I'm using "User: Uid" as the filter, and I'm trying to pull the uid from the URL by selecting "'Provide default value' > 'Use ID from URL'" in the filter's options. Since aggregation settings are on, you have to apply an aggregation type to the filter, and I'm not sure what that should be set on.

Any feedback would be appreciated. By the way, I'm using Display Suite to build the profile layout, so if there's an easier way to get want I need, I'm open for suggestions. Thanks in advance.

EDIT: For anyone attempting to do this, keep in mind that your output will not show up in the Views preview. I was forced to navigate to a user profile in order to test this. This issue seems to sprout from the combination of aggregation and contextual filters.

In my opinion, You do not need Display suite to achieve this. You can do this in very Simple Drupal way .

1. Your views configuration if perfectly fine. I am just posting my one for reference purpose, Where I did two changes, (1) In the pager setting, I have set the pager item to 1. (2) I removed the User: name as it is not needed.

Note: You do not need to anything with aggregation setting at filter level.

2. From your views it is visible that you have created block.

3. Now, What you need to do is put that block in your user profile, so it looks like as a one of the field of user profile.

4. How to do that:

4.1 Place that Block under  Main page content in Content region on as shown in following image.

4.2 Set the display rule for this block as shown in following image. So what happens, the block are visible only on the user profile page.

4.3 Set the Role permission for the User Role, so other user can see teh profile page of other's Or anonymous users also can see teh profile page of other's: I am sure you are aware of all this.

5. Output Image: As you can see, I have tried in my Bartik theme. I have just given block title,  So it can distinguished in the image. Note: I have removed User:name field from the views, as it is not necessary. The views will automatically detect from the url.

**Other example from other login **

Hence, this way without using any other display help, you can add the new field in the User profile. So you do not have to much play with the User profile page.


Drupal Coding - Menus - hook_menu is not generating menus While working on the layout of a new custom menu, I discovered that the hook_menu process is not working on my D7.12 local site.  As a test I enabled the Menu_example module and found that it will not generate menu items in the navigation menu, although it did a week or two ago.  So far I have reinstalled all Drupal 7.12 files and confirmed that the module file hook_menus are being read (using dsm).  I am at a loss as to what else can be preventing the menu links from being installed.

Does anyone have any similar experiences or suggestions on how to track this problem down to its source?

EDIT:
This code does not add a menu item in an empty menu called "Stuff":

function material_menu_menu (){
  $items['stuff/existing'] = array(
    'title' => '020000 Existing',
    'page callback' => 'material_view' ,
    'page arguments' => array ('sum' , '020000 '),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'Stuff',
    'access callback' => TRUE,
    'weight' => '2 ');
  return $items;
}

The place to start debugging is in _menu_navigation_links_rebuild() which builds up the menu links...it gets passed the menu router items built up from menu_router_build() (which is where hook_menu() is called from). A bit of temporary debug code in that first function would be the best way to go I think.

To address your other question, I've just added a menu item to a module in exactly the way you've done and it's come up in the UI as expected. It sounds like you have something pretty unusual happening with your menus!


Modifying page title with THEME_preprocess_page_title I'm running Drupal 8.2.6, and an Adaptive subtheme and I am trying to modify the page title. I have created the following function in THEME.theme

function THEME_preprocess_page_title(&$variables) {
  $color_title = str_ireplace('some text', 'Some TEXT', $variables['title']);
  $variables['title'] = $color_title;
}

unfortunately, it's not working, at all. I've even tried just

$variables['title'] = 'Hello World';

to see if it would work, but no dice.

EDIT
So the hunt goes on!

Apparently AdaptiveTheme doesn't use the page title block, it writes it into node.html.twig via field--node--title.html.twig

so far, I have edited THEME_preprocess_field__node__title(&$variables) with no luck, but THEME_preprocess_node() seems to work. kind of. if i do

$variables['title'] = 'hello world';

it works, but it still won't let me put the span tags in. I have found the reason for that, titles aren't allowed to have code because of XSS threats.

OK. Fine. Fair enough.

There is options in the code to allow you to to allow certain tags (i found documentation, then i lost it ... argghh)

I will keep this question updated as I go

I think you are looking in wrong place. As far as i remember, in Drupal 8 title is rendered trough block called page_title_block

function MODULE_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'page_title_block') {
    $color_title = str_ireplace('some text', 'Some TEXT', $variables['content']['#title']);
    $variables['content']['#title'] = $color_title;
  }
}


How can I randomize search results in Views? It seems like the simple answer to this issue would be to select Global:Random from the Sort Criteria, but choosing this results in a selection of Global: Random (asc) -- the asc being ascending.

And indeed the results are displayed as ascending instead of random.

How can this be corrected?

Results are displaying in ascending order because you may have another sort criteria present above Global: Random (asc) like say Content: Post date (desc).

Solution: Move Global: Random (asc) sort criteria to top. Surely it will work.

  Note: If you have more than one sort criteria lets say 3, then results
  first get sorted with first criteria then with second and then with
  third.


tpl.php files in subfolders I am creating a big Drupal theme with lots of node types and lots of custom templates. Each having a very diffent look and feel. This is something I can not get round because the design was signed off before Drupal was decided as a platform. I wish to organise my files into folders.

templates/content_type/node-content_type.tpl.php

So for example

templates/page/node-page.tpl.php
templates/blog/node-blog.tpl.php
templates/node.tpl.php

The problem is drupal only scans for the templates files in the same folder as node.tpl.php.

Is it possible to get Drupal to scan into subfolders? Even if I need to hardcode where to look I don't mind.

Views does something which means it can look in subfolders but I don't know if that is because it defines its own type rather then a core type (node/page).

In D6, any custom templates (from core, such as node or page) must be in the same folder as the base tpl file in order to use the auto-recognition of theme files.

You may be able to specify additional template files (in D7 they're called theme hook suggestions) in a preprocess function in your theme's template.php. See the first code example at http://drupal.org/node/249726 to get you started.


Date popup - how to restrict typing into the textfield and return timestamp instead of formated date In D7 I'm using date popup form element:

$form['sidebar']['reg_date']['from'] = array(
    '#type' => 'date_popup',
    '#title' => t('From:'),
);

When user click the textfield a popup calendar will appear, but user also can type the date into the textfield. But he can write something invalid like '44444' and this value will be returned in form state values without any form error. It would be useful if this module had an option for restricting typing date by keyboard. Is there any option for this?

I also have one side question: Is there any option to return unix timestamp value instead of formatted date in form state values? In my case it returns date in format '29.5.2016'.

You can use ['#attributes'] = array('readonly' => 'readonly');

Ex:

    $date_format = 'd/m/Y H:i';
    $form['campaign_popup'] = array(
          '#type' => 'date_popup',
          '#date_format' => $date_format,
          '#default_value' => variable_get('campaign_popup'),
          '#title' => t(' Campaign Start Date.'),
          '#date_label_position' => 'within',
          '#date_year_range' => '0:+3',
          '#datepicker_options' => array('minDate' => 0),
          '#attributes' => array('readonly' => 'readonly'),
    );


How to locate page template in use? I have a strange situation where my Drupal 7 Omega 4 site appears to not be using a page.tpl.php template. The page renders and content appears but when I alter all of my page templates to indicate which one is in use (By adding a "
TEMPLATE NAME.tpl.php
 above the "print render($page['content']);") I see nothing in the rendered output on screen.

I have cleared the caches. Many times.

Is it possible for Drupal to somehow not use a page template and still render a page's content? I would have thought not but can't figure out how this could be happening.
I'm guessing I'm completely forgetting something quite basic here.

Any help greatly appreciated.

You can use the https://www.drupal.org/project/devel_themer module to see what tpl file is in use. You should see the path to your subtheme. If you see the path to the base theme, then your tpl file is not found.


How do I set the "Save draft" button by default on all webform nodes? I have a situation where, when I create a new webform node, its "Save draft" button must be there by default.

How can I achieve this?

/**
 * Implements hook_webform_node_defaults_alter().
 */
function mymodule_webform_node_defaults_alter(&$defaults) {
  $defaults['allow_draft'] = '1';
}


Varnish/Drupal caching for logged in users Problem

Varnish is caching pages when I go onto my website anonymously.

I have "Cache Pages for anonymous users" turned on so this is expected.

But when I login it continues to load the cached page for the pages I visited when I was logged out, so the user specific menu never shows and the login button continues to show even though I'm logged in.

I though Varnish didn't work for logged in users and I'm using the default drupal caching system which I thought didn't work for logged in users? How can I prevent this?

Server Set-Up

LEMP Stack - Ubuntu Server 12.04

APC + Memcached

Varnish

Drupal Caching Settings:

Cache pages for anonymous users -> enabled

Minimum cache lifetime -> 0

Expiration of cached pages -> 6 hours

Varnish Module Settings:

Varnish cache clearing: Drupal default

I installed Varnish using this guide and this Varnish config file: http://andrewdunkle.com/how-install-varnish-drupal-7

Browser Caching

I disabled browser caching in Firefox and I still get Varnish cache hits on my homepage however now the menu loads correctly. What does this imply?

You have two options:

Solution 1: Disallow caching in the browser

In order to prevent a browser from storing and reusing a page, you have to make sure that Cache-Control:no-cache, must-revalidate, post-check=0, pre-check=0 is on the respective (HTML) pages.

You can force this header in sub vcl_deliver. Just make sure that you do not put that header on static assets (like images, CSS and JavaScript files):

sub vcl_deliver {
  set req.http.Cache-Control = "no-cache, must-revalidate, post-check=0, pre-check=0";
}

Solution 2: Ensure that Vary: Cookie is on the response

If you want to force the browser to invalidate its cache whenever the cookies change (i.e. a session is opened), you have to ensure that the Vary: Cookie header is on the response.

sub vcl_deliver {
  if (resp.http.Vary !~ "Cookie") {
    set resp.http.Vary = resp.http.Vary + ", Cookie";
    set resp.http.Vary = regsub(resp.http.Vary, "^,\s*", "");
  }
}

Again, the cache is more effective if you restrict this fragment the page / filetypes which have different contents depending on whether a user is logged in or not.

Safari (at least v5 which is the last one for Windows and the one on iPad 1 and some older iPhones) has a nasty bug. I recommend to add the following snipped in order to deactivate the Safari browser cache:

sub vcl_deliver {
  if (resp.http.X-Generator ~ "Drupal" && req.http.user-agent ~ "Safari" && req.http.user-agent !~ "Chrome") {
    set resp.http.Cache-Control = "no-cache, must-revalidate, post-check=0, pre-check=0";
  }
}

Note: This is a little bit different from the solutions proposed in the comments of the bug report. By placing the snipped into vcl_deliver instead of vcl_fetch we avoid having to separate the bins. Also note that by matching on X-Generator ~ "Drupal" we avoid disabling the browser cache for static assets.

Today (November 2013) I reproduced this misbehavior on Safari 5.1.1 (Windows), 6.1 (Mac OS X 10.8 / Mountain Lion) and 7.0 (iOS 7).


Set default language for domain I have one site with 2 domains one example.de and one example.com its a multilanguage site, so i have urls like this example.de/de/content and example.de/en/content etc, and same on com domain.

Default language is de for this two domains, but for example.com i need english to be default language.

i thought i can change it in settings.php with $conf['language_default'] like this:

$conf['language_default'] = (object) array(
  'language' => 'en', 'name' => 'English', 'native' => 'English',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

its working but for both domains... . also i managed to redirect users to en on example.com (my home page is a node with nid 89)

function MYMODULE_node_view($node) {

        if ($node->nid == 89) {
            if ($_SERVER['SERVER_NAME'] == 'www.example.com') {
             header('Location: http://www.example.com/en');
            }
        }

    }

but its not an option

Is there any solution to change default language for my example.com domain?

Though I'm surprised if there's not an option in the user interface, according to language_default, it appears you could set the default language as a $conf variable in the shared settings.php file.

Something like

settings.php:

switch($_SERVER['SERVER_NAME']){

  case 'www.example.com':

    $conf['language_default'] = (object) array(
      'language' => 'en', 'name' => 'English', 'native' => 'English',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Example per-domain cache prefix if using memcache
    $conf['memcache_key_prefix'] = 'en_';

  break;
  case 'www.example.de':

    $conf['language_default'] = (object) array(
      'language' => 'de', 'name' => 'German', 'native' => 'German',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.de', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Ensures cache varies by domain
    $conf['memcache_key_prefix'] = 'de_';

  break;

}

Update: Added example memcache cache key prefix setting - to ensure cache varies per domain, if required.