How enable PHPMailer to write complete persistent log? I am using the PHPMailer module to send emails to a user group (role) by a poormanscron-job.

I can see errors in my "recent log entry" view in the backend but I cannot get a persistant log with all log entries (I set the phpmailer settings to INFO or DEBUG level in the backend) somewhere.

I would like to check afterwards, who got the email and if there were dropped mails without errors (if that is possible).

It's not clear from your question what Drupal version you are on. But the Maillog / Mail Developer module might be handy here. Some more details about it (from its project page):

  ... provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally you can immediately display the mail through the Devel dpm() facility.

But you might get integration problems, since it's not easy and highly Drupal version dependent to get more than one email module at a time working.


Writing PHP code to creating menu in block show and alert I have a menu in a block and this is my code in that block that is in sidebar second:

<?php
  $url=$base_url.'/drupal';
  echo
  '

One

 Two

';
?>

it is working correctly, but return and red alert:

  Notice: Undefined variable: base_url in eval() (line 2 of C:\xampp\htdocs\drupal\modules\php\php.module(80) : eval()'d code).

You need to define it as a global variable first:

global $base_url;

So that your code is now:

<?php
global $base_url;
$url=$base_url.'/drupal';
echo
'

One

 Two

';
?>

Then you may don't need drupal in your $url variable. and it would become:

$url=$base_url;


Using Filter on NULL Values in Views 3 I'm using Drupal 7 with views 3.

I am listing the student fees in a view and one of the field in view results is pid (payment id) which has some numeric value or NULL value. The NULL value means the payment is unpaid. I have used a custom field handler to show in view result as paid and unpaid for pid = some value as Paid and pid = Null value as Unpaid.

I want a filter on this field also which will have a drop down of two options as paid and unpaid. Which views filter I should use and how can I rename the drop down options?

hook_views_data()

// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_WHICH_ONE_I_SHOULD_USE',
    ),
    );

class fee_management_handler_field_payment_status extends views_handler_field {
    function construct() {
    parent::construct();
    $this->additional_fields['pid'] = 'pid';
  }
  function render($values) {
    $pid = $this->get_value($values, 'pid');
    if (!empty($pid)) {
            return 'Paid';
        }
        return 'Unpaid';
  }
};

Thanks in advance for your help.

I have implemented this custom filter. All Thanks and credit goes to Amar :). I am just sharing the code.

// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'fee_management_handler_filter_payment_status',
      'numeric' => TRUE,
    ),
    );

Handler

class fee_management_handler_filter_payment_status extends views_handler_filter_many_to_one {
  function get_value_options() {
    $this->value_options = array('1' => 'Paid', '0' => 'Unpaid');
  }

    function query() {
    // as per your database st
        ;

  }

}


Feature revert deletes existing Strongarm variable I got a Drupal 7 feature, which contains certain Strongarm variables, such as admin_theme. This feature has been created, released and reverted multiple times, always without fault. Suddenly, the last feature revert leaded to a deletion of some variables which are clearly defined in Strongarm.

The only thing that helped "a bit" was to remove the variables from the feature, release & revert them, and then add the variables again and release and revert once again.

This can't be a solution for the production release because this one has to work in one time. Why can it be that a Feature revert deletes variables from the database (variable table) which are clearly stated in the feature?

In case someone gets on this question: We finally managed to find the answer to our problem.

We had an old version of the strongarm module (7.x-2.0-beta2) instead if 7.x-2.0 which is stable now (since 2012). The update hook from this update saved a lot of variables from the features to the drupal variable table, and on every further feature revert, no more variables would be deleted, so the problem was fixed. Credits to @Weri!


Filter taxonomy term attached to user field I have a user that has a taxonomy vocabulary attached their account and a content type with the same taxonomy vocabulary attached to it.

How do I get a page view filter to only display the nodes that have the same taxonomy term that is attached to the user vocabulary?

One way to do it is a bit of a multi-step process.

First, in the view itself under ADVANCED -> CONTEXTUAL FILTERS set up a contextual filter for the taxonomy field you want to filter the view based on (make sure that field is also added to the view's fields.

second, you'll need to add a bit of code to a custom module. You'll want to implement hook_views_pre_view

/**
 * Implements hook_views_pre_view().
 *
 * @param ViewExecutable $view
 * @param string $display_id
 * @param array $args
 * @return void
 */
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $account = \Drupal::currentUser();

  // DO A LOOKUP FOR THE USER'S FIELD
  $VALUE_FROM_USER_FIELD_LOOKUP = 'SOMETHING';

  // IF WE ARE IN THE RIGHT VIEW AND DISPLAY
  if($view->id() == 'MY VIEW ID' && $view->getDisplay()->display['id'] == 'MY DISPLAY ID') {
    // ADD SOME CUSTOM ARGS TO THE CONTEXT FILTER
    $args = [implode("+", $VALUE_FROM_USER_FIELD_LOOKUP)]; //implode on + or some other character? for multi-value contextual filters...
  }

}


Where and how are escape quotes stripped when saving a taxonomy terms which include comas or quotes? in taxonomy_autocomplete:
https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.pages.inc/function/taxonomy_autocomplete/6
we have the following code:

   // Commas and quotes in terms are special cases, so encode 'em.
      if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $tag->name) . '"';
      }

Imagine we have the taxonomy term which is exactly the following string:

George "madcow" Stewart

THe above code would cause the taxonomy autocomplete to display:

"George ""madcow"" Stewart"

I have re-implemented the taxonomy_autocomplete in order to work with a single term (no comma separated list of terms allowed).
The problem now is that when we want to enter George "madcow" Stewart, a new term "George ""madcow"" Stewart"  is created, including all the extra quotes!

I cannot find where and how in core the escape quotes are stripped before insertion to the database…

Oh! I just found it:

The function taxonomy_node_save(&$node, $terms) calls drupal_explode_tags()

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_explode_tags/6

which has:

// If a user has escaped a term (to demonstrate that it is a group,
// or includes a comma or quote character), we remove the escape
// formatting so to save the term into the database as the user intends.
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));


How to remove a "new" indicator when clicking on a link? I'm showing a list of content in a view and there is a red "new" indicator (field content: has new content) next to the title link. The problems is that when you click a link to read the content and then click back the "new" indicator is still shown.
I don't want to reload the list page every time I click the back button. I'm thinking about using some javascript/css to remove the "new" indicator when you click on the link. Is there a "Drupal" way of doing this?
Screenshot:

The theme function used to add that marker is theme_mark(). You can override that theme function to avoid it adds the "new" marker. Supposing that you override theme_mark() with mymodule_theme_mark(), you could use the following code:

function mymodule_theme_mark($variables) {
  global $user;

  if (!empty($user->uid) && $variables['type'] == MARK_NEW) {
    $variables['type'] = MARK_READ;
  }

  return theme_mark($variables);
}

The theme function is used, for example, in node_admin_nodes(), and in theme_node_recent_content(); the latter function calls the theme function using the following code.

$output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
$output .= '

';
$output .= theme('username', array('account' => user_load($node->uid)));

Even better, since preprocess functions are called also for theme function not using a template file, you can use the following code.

function mymodule_preprocess_theme_mark(&$variables) {
  global $user;

  if (!empty($user->uid) && $variables['type'] == MARK_NEW) {
    $variables['type'] = MARK_READ;
  }
}

This code is preferable because:

What you really need to do is changing the value of a variable passed to the theme function, not altering the output of the theme function, and the preprocess function is perfect for this case
The code works also when another module override the theme function, while the code I shown earlier makes the assumption no other module overrode the theme function


How can I allow users to receive e-mails whenever I update my blog in Drupal 7? I have a blog in English and Japanese in Drupal 7.  I created this blog using a custom content type and Views, not the built-in blog module.

I have an RSS feed (made in Views) for each language.  I would like to allow users to subscribe to receive all English-language updates to content type "blog" or all Japanese-language updates to content type "blog."  (I anticipate most users will only want one language or the other.  If a user really wants both languages, I don't mind making them subscribe twice.)

I looked into using Feedburner on the RSS feeds, but the Feedburner module has not been updated for D7 and I would rather not rely on an external service.  (When I tried setting up Feedburner without the module, it told me my RSS feed didn't exist even though the support link allowed me to validate it.)

I also looked at the Simplenews module, but that module apparently requires creating each newsletter post separately.  What I want to do is automatically e-mail subscribed users when I post an update to the blog.

I'm sure there are a lot of ways to do this, but there are so many "mail helper"-type modules that I'm at a loss as to where to get started.

To summarize my requirements, I want to:

Automatically e-mail subscribers when a new blog post in the appropriate language is added.
Both authenticated and anonymous users should be able to subscribe.
Subscriptions must require confirmation (legal requirement).
Compatibility with the MIME Mail module would be a nice bonus.

This can be acquired easily. I can give you some steps to follow.

There are actually at least 2 ways to achieve that

A. Using Triggers (core module)

First activate the core module Triggers. This will provide you basic triggers (in your case UPDATE trigger) and actions to run when condition is met.
Go to Admin > Configuration > Actions then CREATE AN ADVANCED ACTION, then select: Send e-mail. In the recipient field you need to select a proper token provided by simplenews module to match all the registered users. (make sure you also have Token module installed)
Go to Admin > Structure > Triggers, then Node tab. Choose the third: TRIGGER: AFTER SAVING UPDATED CONTENT.

If you need more control then implement the hook

function YOURMODULE_trigger_info_alter(&$triggers) {
 //Here dpm($triggers) to see where is your update trigger and do the changes.
}
?>

B. Using Rules (contrib module)
Basic the same thing. If you get stuck follow these steps on a similar issue
on this blog:
http://adellefrank.com/blog/how-to-email-notifications-comments-drupal7


Addressing objects and arrays nested in an object? I'm working a .tpl file for my view that is named views-view-fields--viewname--block.tpl.php. With the Devel module, I did a dsm($field); One of the field objects that are returned in the Krumo goes as follows:

fieldObject
    --handler(object)
    ----last_tokens(array)
    ------[title](string, 15characters)

I figured I should address this as

    <?php foreach ($fields as $id => $field): ?>
  <?php dsm($field); ?>
    <?php if ($field->class == 'field-evenement-performer'){
        print $field->handler->last_tokens['title'];    }

?>

but this returns Notice: Undefined index: title in include() (line 34 of /....../sites/all/themes/ibrain092012/templates/views-view-fields--presentatie-kraakhuis--block.tpl.php

How can this be while title does have a value in the Krumo?

This is the correct way to use it (see the usage of the square brackets in the string):

print $field->handler->last_tokens['[title]'];


How to NOT "Print" a section by using Print module? I installed "Print" and "Book Made Simple" modules on Drupal 7. The Print module also print the button "add this child" from "Book Made Simple". How can I not print "Add this child" on PDF?

below screenshot is showing where the button from "Book Made Simple"

And here is the screenshot of a PDF contained "Add child page" and icon.

In those cases I added a custom print--pdf.tpl.php file to my theme and defined my custom css in the head of the HTML page which is rendered in this file (you find the original template file named "print.tpl.php" in the print modules folder - just copy it to your theme and rename it).

Here you can define any element by CSS and give it a "display: none;" - so it will not be seen in your final PDF.


On drupal main page menu, number after /node/7/1 i am starting to learn drupal right now. I downloaded a template and I am trying to figure out where are all the components are stored.

I encountered a problem where on the menu for website,  there are different submenu items under that menu. and one of the items has URL like this: www.example.com/node/7/1, another item URL like this: www.example.com/node/7/2, the list goes on, like www.example.com/node/7/3. When I click on any of those link, it brings me to the same page, however the representation is different.

I am able to find node 7 in the content, however i am not able to find how to configure the number after /node/7. Can somebody tell me what does that number means? Thank you very much and have a great day.

Not sure I fully understand the question, but my 2 cents.

First, default Drupal URLs take the format of /{entity}/{id}/{action}, eg. /node/7/edit and /node/7/view. In both cases you are looking at the 7th node to be created, the first is the edit (admin) display, the second is the default display that visitors will see (view is dropped so you only see /node/7.

The second argument in your example is a little tricky as numbers don't give much away, so without knowing every module you have installed I would assume this is related to your template.

You can tell if this is the case by changing template to the default.

If these are the result of the custom template, the have a look in template.php as this is where theme level custom logic is done. On the off chance it hasn't been done well, have a look in the page.tpl.php and node.tpl.php files too.


Is it possible to access the `session` table using db_query/db_update/db_insert? is there a security feature that is preventing me from doing anything with sessions?

I'm pretty sure this is a bad idea, but I'm switching users around after login.

User A logins in using their credentials, but we switch them to be User B.

Perhaps there's a better way to do this and I don't need to directly change sessions at all.

Yes, it's a bad idea :)

No, there are no extra security measures in place that would stop you having access to the sessions table (certainly nothing that Drupal is imposing, and if your site is working then Drupal must be able to read/write to that table).

If you want to switch users programatically I can't think of a better way than how the Devel module does it:

function devel_switch_user($name = NULL) {
  global $user;

  if ($user->uid) {
    module_invoke_all('user_logout', $user);
  }
  if (isset($name) && $account = user_load_by_name($name)) {
    $old_uid = $user->uid;
    $user = $account;
    $user->timestamp = time() - 9999;
    if (!$old_uid) {
      // Switch from anonymous to authorized.
      drupal_session_regenerate();
    }
    $edit = array();
    user_module_invoke('login', $edit, $user);
  }
  elseif ($user->uid) {
    session_destroy();
  }
  drupal_goto();
}

Even if you don't have devel installed (which obviously you shouldn't on a production server anyway), just make a copy of the function in a custom module and tweak it to your needs.


Creating search pages for specific content types I am currently in the process of implementing different search pages, with distinct layouts/templates and behaviors for specific content types (a search for "blog" nodes, one for "video" nodes, etc), and I am confused as to what the best approach is for this. I've read that the Facet API module may help implement this behavior. I'm already using Apache Solr for the searching component, is this the best approach and what's the path of least resistance if using Facet API?

The best method for me is Search API:

  This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

Uses multiple backends (solr, database, elastic search), is fully integrated with views, etc.


Should Drupal 6 be considered insecure? After reading the post about linkedin on IT security and this issue I would think that having a default Drupal 6 installation without, for example, the phpass module should be considered quite insecure, since the passwords are stored in a way which doesn't require much force to guess and check.

Should I run and install phpass on every Drupal 6 site?

Yes!

You should consider Drupal 6 without phpass to be unnecessarily insecure.  And yes, you should use phpass on all your D6 apps.  There are reasons they've changed the way things work in Drupal 7, and made the same changes available as a module to D6 users.

There is no silver bullet, but there's no reason to ignore an easy-to-use module that will significantly increase your level of security.

Not using it is a little like not wearing a seat belt: of course you want to avoid ever being in an accident to begin with (analogous to ever letting anyone gain access to your data), but once you have an accident it's far too late to try buckling up.  Buckle up now!

Update: A security expert seems to agree with me:

  ...take the view that attackers will ultimately get into your network, access your data... you should be looking at the problem differently.


How to get varchar type input from users on my website? I want to add a field to get a bank account, swift code, card no and IBAN type values from users on my Drupal 7 website.

These fields require a mix of numbers, alphabetical characters and "-".

How can I get this type of info from users?

Note: Core Text field is not sufficient to get varchar type input from users.

Use the Custom Formatters module

Consider using the Custom Formatters module, which is very easy to use and configure. And it integrates with various other modules.

Here is an excerpt from its project page:

  ... allows users to easily create custom Field Formatters without the need to write a custom module.

  Pluggable editor/renderer engines:

  Formatter preset: Create simple formatters from existing formatters with preset formatter settings.
  HTML + Tokens: A HTML based editor with Token support.
  PHP: A PHP based editor with support for multiple fields and multiple values.
  Twig: A Twig based editor provided by the Twig filter module.

  Supports for all fieldable entities, including but not limited to:

  Drupal core - Comment, Node, Taxonomy term and User entities.
  Field collection module - Field-collection item entity.
  Media module - Media entity.

The Community Documentation for this module seems to only be a placefholder for now (which is also where the Read documentation links to on the module's Project page).

However there are a few other resources about it that are worth checking out:

Custom Formatters for Easy Drupal Embeds for a tutorial about using this module.
Video about What's new in Custom Formatters 7.x-2.1/2.2.

Create your custom module

Here are some tutorials about how to solve your question using a custom module (all for D7):

Create a custom field formatter in Drupal 7
Creating Custom Formatters with the Field API.
Creating new field formatters in Drupal 7.
Field API - Creating your own field formatters.


what benefit is it to clearing the Drupal cache now that I have Varnish in front of Drupal? Our site has Varnish in front of Drupal for anonymous user page requests so that these pages are cached.  I know how to clear the Varnish cache within Varnish but my question is what benefit is it to clearing the Drupal cache now that I have Varnish in front of Drupal?

Whenever Varnish Cache expires it asks Drupal to give it the rendered page. Drupal in turn sees if it can server the page from the Cache. If yes it will server from the cache, else it will regenerate the page.

In short, when you clear the Drupal Cache,

No changes are visible to end users for whom the content is served from Varnish.
When the Varnish Cache expires, it will fetch the content form Drupal. Now that you had cleared the Drupal cache, instead of serving from the cache the page will be rebuilt.


Module to import github content onto local drupal server I want to be able to put content from github into the sites/default/files folder of drupal so I was wondering if there was a way to do this.

I made my own module. You can see part of the code here. I put that code on a cron_hook.


Page works with SSL, but not internally I struggled a long time with Drupal in order to get my page to load with SSL. I ended up getting it to work my modifying settings.php:

/**
 * Base URL (optional).
 *
 * If Drupal is generating incorrect URLs on your site, which could
 * be in HTML headers (links to CSS and JS files) or visible links on pages
 * (such as in menus), uncomment the Base URL statement below (remove the
 * leading hash sign) and fill in the absolute URL to your Drupal installation.
 *
 * You might also want to force users to use a given domain.
 * See the .htaccess file for more information.
 *
 * Examples:
 *   $base_url = 'http://www.example.com';
 *   $base_url = 'http://www.example.com:8888';
 *   $base_url = 'http://www.example.com/drupal';
 *   $base_url = 'https://www.example.com:8888/drupal';
 *
 * It is not allowed to have a trailing slash; Drupal will add it
 * for you.
 */
 $base_url = 'https://www. ... .com';  // NO trailing slash!

But now I am faced with an entirely new issue, one related to the changes I made in setting.php.

Now, when I try to reach my page internally by 192.168.1.x/?q=user, I get a terribly messed up login page, and after entering my login information, I get redirected to a page that shows nothing but "SSL connection error".

What have I done!? Will this ever work?

Try this:

$base_protocol = empty($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ? 'http' : 'https';
$base_url = $base_protocol . '://www.mysite.com';

Though you may need the Secure Pages module for it to work, or to have redirection set up in your .htaccess file or virtualhost.


Update CCK Field Every 90 Days I'm using Drupal 7. I have a CCK field called Placement Date (Placement_Date) that the end user will manually put in. I then have two text fields, Start_of_Period and End_of_Period. Start_of_Period initially is set to Field->Placement_Date and Field->End_of_Period is set to 90 days out. The setup is no problem, but after 90 days Field->Start_of_Period needs to be the old End_of_Period + 1, and Field->End_of_Period needs to be another 90 days out from the new Field->Start_of_Period. I looked to Rules to try to find a way to schedule this, but cannot figure out what I need to be doing.

Any help would be greatly appreciated. Thanks in advance.

You need to set up cron tab on your server may be once a day
  use hook_cron() to add your custom code write query to grab nids for which field values needs to be updated.
  use node_load_multiple() to load all nodes with the query returned nids
  update the field values and save the node again in a loop.
  set the crontab to run at the time when your site receives least traffic, this way it will not be performance issue as well.


How to use Kwicks for slider? I see it in premium themes and D6 themes (demo).  I would like to use it on my site.

Yes. There obviously isn't a Drupal 7 module for this yet (http://drupal.org/project/kwicks) but you can always just include the jquery plugin in your own theme / block implementation and roll your own slideshow.

Actual implementation of this would depend on what you are trying to do but according to the Kwicks documentation, all you need is to apply the kwicks js to a simple unordered list like this

So one (module-less) way you could do this is is to create a content-type of whatever it is you want to be in this slider, than create a view of these nodes with a style output of HTML list. In your views header, add a  tag to include the kwicks code in:

and then whatever jquery config you need to make the slide show, ex:

and output it as a block / page to place it where ever you want on your site.


Having issues upgrading from Drush 6.3.0 to 8.0.5 We have been successfully using Drush, latest version 6.3.0. In order to obtain Drupal 8 support, I am trying to upgrade to Drush 8.0.5.

First I located the 8.0.5.tar.gz file and tried getting success that way. It complains:

./drupal-cron.php.sh

  20160407-204933 drush core-cron cron.php begin
      Unable to load autoload.php. Run composer install to fetch dependencies and write this file (http://docs.drush.org/en/master/install-alternative/). Or if you prefer, use the drush.phar which already has depdencies included (http://docs.drush.org/en/master/install).
      X-Powered-By: PHP/5.4.45
      Content-type: text/html

So next I tried pulling down drush.phar as that appeared to have the dependencies built-in. Trying that version also did not seem to successfully execute Drupal cron:

./drupal-cron.php.sh

  20160407-211633 drush core-cron cron.php begin
  X-Powered-By: PHP/5.4.45
  Content-type: text/html

We have been successfully running Drupal cron with Drush since our last update back in 2014 with this script:

#!/bin/bash
DATE=`/bin/date +%Y%m%d`
DATETIME=`/bin/date +%Y%m%d-%H%M%S`
LOGFILE=/kunden/homepages/35/d157794216/htdocs/reports/$DATE.${2}.drupal-cron.php.sh.log
export COLUMNS=132

echo $DATETIME drush core-cron cron.php begin | /usr/bin/tee -a $LOGFILE
/usr/bin/nice -n19 /usr/local/bin/php5.4 /kunden/homepages/35/d157794216/htdocs/drush/drush.php --root=$1 --uri=http://$2 --debug --nocolor core-cron 2>&1 | /usr/bin/tee -a $LOGFILE

And to try drush.phar I swapped out drush.phar for drush.php in the Bash script.

Suggestions how to get successfully upgrade to the latest version?

It's not clear from your post how you are calling the phar, but you cannot call drush.php directly when using that variant. This technique (php drush.php) was recommended in Drush 3, but has been deprecated since Drush 4.  The script you show above will work for calling cron, but will fail for commands that cause Drush to call itself.

If you want to use the .phar, make sure that the correct version of php is in your $PATH, and then call Drush directly.

Alternately, you could install composer and run composer install in the Drush directory after installing the .tar.gz file, or cloning from git. If you do this, set the DRUSH_PHP environment variable to point at the php executable that you would like to use, and call the drush script (not drush.php).


Why is the default Search module not returning partial results? Drupal 7 default Search module not returning partial results

I.E. I have a series of SKU #'s:

S0160-0003
S0160-0004
S0160-0005
S0160-0006

Searching for S0160 returns no results. I only get results when I search for the exact SKU number.

Any recommendations as to how to fix this?

Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. No need for Solr.

Enable both the modules and go to the Search API configuration page
(admin/config/search/search_api)
Add a server and give it a recognizable name (such as "MySQL"), make sure it's enabled
Choose the following service class: Database service (normally the
only option. If you don't see it, make sure that the "Search API
Database Search" module is enabled).
Selecting this service class will provide you the option Search on
parts of a word (make sure you enable it). Now hit "Create
server". Next, go back to the Search API configuration page, and
add an index. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled.
Select the server you recently created (in this example "MySQL").
Datasource options: check the content types you want to index (the
description of this field may be a bit confusing, but make no
mistake: you should check the content types you want to index, not
the ones you want to leave out).
You could check "Index items immediately", but that depends on the
size of your content. This option is alright for smaller websites.
In the other case: let cron take care of it. Hit "Create index".
Next, you want to enable the fields (in the fields tab) to that
very index, e.g.: contant type, title, status and author - and hit
"Save changes" (we'll take care of the related fields later).
Then you want to configure the filters (in the filter tab). Here
you can enable the bundle filter, if you want to finetune the
content types once again (probably won't need to).
Down below you'll find the highlight filter, to highlight the
search word in the results.
Now return to the fields tab and unfold the "Add related fields"
 tab. Add all the fields of which you want to get the content
 indexed, and hit Save Finally go to the "view" tab of the index,
 and index now all the items.

The last step is to create search results page and search block in Views, which only takes a few minutes.

Make sure the submodule Search Views is enabled and create a
view page which will show "Contentindex" (select the name you gave
to your index configuration instead of "content" which is selected
by default.
Add all the fields (make sure your format is "fields") that every
search result should consist of (title [link to content], body, …).
You'll notice that these field look like this Indexed Node: Title
Add an exposed filter: Search: Fulltext search; and select the
following in its settings: Contains any of these words, and use
as: Search keys.

You're done!

There's an excellent video tutorial on this partial search method without Solr, which also incorporates faceted search (which is not necessary for partial search, but in case you're interested…). If you're only looking for a partial search option, you can watch the video until 5:08 and after that skip to 6:45.


Redirect User to their Profile Page After Saving Each user has a "Edit" tab/button on their profile. They click it, edit their profile, and when it is saved, they are kept on that page. I want the user to be taken back to his/her "View" or profile page.

As @Aboodred, if you already have the Rules module installed, adding a simple rule can do the job.

Create a rule with the React on event type After updating an existing user account.
Add a Page redirect action. Set the 'Data selector' field to account:url (either manually or using the dropdown).


How to hide comments below the node, but not close them? Аctually I want to list comments for nodes myself (by Views, for example), so I need to hide standard comments list from core comment module.
I can do it like that:

  unset($node['comments']['comments']);

But it will not prevent DB query for comments.
So I found some crazy ways to trick the comments module. For example, to set fake $node->preview property, or to create new view mode and overwrite standard node/%node callback.

Is it really so difficult to hide comments below the node but still allow to add new comment, or I missed something?

Update about “Hidden” option

What about “Hidden” value for the content type:
I need close/open behaviour for my comments. But if I set “Hidden” for my content type, my new content pieces are set to “Comments closed” instead of hidden (here is the code).
Another problem is that user with permission to “post comments” can't add a comment, if comments are hidden (here is the code).
So I can't get the idea.

Answer

Solution found with hook_module_implements_alter(). Thanks a lot!

In modules/comment/comment.module we can see that hook_node_view() (comment_node_view()) is running on line 614. This is where the functions are firing to load all comments and attach them to the node. The first 2 sets of if () { ... } appear to be handling the add comment form and action link. Then the final block of code is finally adding the comments, which I believe is what you're actually most concerned about hiding, and I assume you want this skipped for performance reasons:

// Only append comments when we are building a node on its own node detail
// page. We compare $node and $page_node to ensure that comments are not
// appended to other nodes shown on the page, for example a node_reference
// displayed in 'full' view mode within another node.
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

I think this code is silly, because comment module should not be dependent on any particular hardcoded view mode. Hopefully this will change and become a setting in the UI.

Regardless, I've found a similar post that might interest you: Is there a way to stop comment_node_view from firing?

Basically you're wanting to use hook_module_implements_alter() to stop the comment module from being able to fire off hook_node_view(). Here is what you need to add to your custom module:

function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    unset($implementations['comment']);
  }
}


Edit content created by users with the same role Is there any module that would allow me to edit/delete nodes created by users with the same role I have?

I would approach this by grouping users with organic groups module instead of by role. Roles are only for defining access level, not for making groups of users.


How to set Disqus Share link to window.location.pathname + window.location.search? Version Disqus 8.x-1.0-rc3
Drupal 8.2.5

I have a page that is built up of multiple nodes using Twig Tweaks.  One of the nodes has the Disqus comment field.  Module runs smoothly and everything, however, the Share url is to the node/#### instead of the page.

Tried the following but to no avail:

Updated the Disqus field's default identifier to [current-page:url].
Overrode the node's Disque identifier manually on /node/####/edit page
Tried modifying modules/disqus/js/disqus.js (w/drush cr), so that

disqus_title = document.title;
disqus_identifier = window.location.pathname + window.location.search;

I thought #2 would work above, but it still is tied to the entity's node id.  The Share link always goes to /node/####.

Any assistance in this matter would be greatly appreciated.

EDIT: Just noticed that [current-page:url] does not include the search portion of the url.  The URL looks like /something/node-title-text-here?page=5

So the solution was to add my own Javascript file and just clear the drupal settings for disqus like this:

Added Javascript file to modules/custom/MYMODULE/MYMODULE.libraries.yml

disqus-overrides:
  version: VERSION
  js:
    js/disqus_overrides.js: {}
  dependencies:
    - core/drupalSettings

Created a new file in modules/custom/MYMODULE/js/disqus_overrides.js

drupalSettings['disqus']['identifier'] = '';
    drupalSettings['disqus']['title'] = '';
    drupalSettings['disqus']['url'] = '';

Then force this file to be loaded on every page load in modules/custom/MYMODULE/MYMODULE.module (this could be optimized to only load on those pages with the Disqus comment field, but I don't know how yet):

function MYMODULE_page_attachments(array &$attachments) {
        $attachments['#attached']['library'][] = 'MYMODULE/disqus-overrides';
    }


How to link taxonomy term with current loaded NID? I want to link taxonomy term with current loaded node
I am using

$nid = arg(1);
$term=taxonomy_term_load($tid)
print $term;

but noting happened.
Please tell what is the correct way

$nid = arg(1);
$node = node_load($nid);
//field_taxonomy is the taxonomy field used in the node
$tid = $node->field_taxonomy['und'][0]['tid'];
$term=taxonomy_term_load($tid)
print $term;


How to implement 'Starts With' for exposed filter of User ID I have a Page based on a View with an Exposed Filter which is the User ID. So the Search form that appears shows the User ID as the standard 'lookup' of users. I don't want that. I want to be able to have the search field be a standard text field and the results be a 'starts with'.

Eg.

Enter User: [Fra      ]

Would return

Francis
Frank
Friend

How is this done?

If you use the "User: Name" filter it will give you an autocomplete text field where you can start typing and it will show you a list of patching users as you type.

That field will not let you enter partial user names though, you must select a user from the autocomplete (you can have multiple comma delimited values if you like).

To match partial user names, use the "User: Name (raw)" filter.

This one allows you to have a text field that doesn't have any validation.
This field can have the operator set to "Starts with".


How do I parse application/vnd.surveymonkey.response.v1+json? I recently asked a question about setting up SurveyMonkey webhooks here: https://drupal.stackexchange.com/questions/252571/surveymonkey-v3-webhook-callback

After laborious troubleshooting, I've determined that the issue is that I need to be able to parse the request as application/vnd.surveymonkey.response.v1+json.

How do I do that?

There's no option to add this type of parser, or a custom parser, in the REST server config. Googling for a few hours has come up with nothing. In a Drupal REST endpoint, how can I use this parser type?

So the answer is to use hook_rest_server_request_parsers_alter(). This way, the application/vnd.surveymonkey.response.v1 Content-Type can be mapped to the standard JSON parser.

function MY_MODULE_rest_server_request_parsers_alter(&$parsers) {
  $parsers['application/vnd.surveymonkey.response.v1+json'] =  'ServicesParserJSON';
}


Social Networking buttons in a list of teasers generated using views I have generated a list of blogs with title and teaser , with a pager also , using views. I need to display social buttons like share on Facebook, twitter etc on each items of the list. How can this be implemented?

Download the ShareThis module. This does what you need.
Here is a quote about it (from the module's project page):

Integration with the ShareThis social bookmarking utility on selected node types.
The code for this project was based on the original share project for Drupal 5.x. The code for this project has been trimmed down to only work with the ShareThis system, and not require any additional modules to work properly.


Pulling content from other nodes into a Panel Node I'm using Panel Nodes* to let users create content with varying layouts. I'm wanting to display another node in one of the panels.

When I create the Panel Node and go to create a new Content pane, I click Entity then Rendered Node. However, the Entity dropdown only lists "This node". If I click Node instead and then try to insert a Node Content panel content type, the Node dropdown is still "This node". What am I missing?

I've tried using EntityReference to associate a Panels node with the other content type, but it doesn't increase the options available to me.

Any idea how I'd render a node from another content type in a Panel Nodes Panel?

Thanks!

*Yes, I know I should use Panelizer, but I'm wanting to know if there's a way to do this without converting everything I've done thus far to that.

When you add an Object to your Panel Pane, you will find in the left column the option to add an "Existing node", choosing this, you can add a node id of the content you want to add.

If you want to dynamically provide different nodes provided by the user input on the node form using a node reference field, you need to add a context to the panel by using this reference field and then the referenced node will also be available.


How do I enable CORS on Service endpoint? I tried to call a Drupal service endpoint, exposed by the Services module, using ionic which is built on Cordova.  I ran 'ionic serve', so it wasn't serving from the file system but had an actual localhost and port url.  I then installed the CORS module and I'm a bit confused by what I need to include.
My endpoint is http://example.com/api/v1/
It is a REST based server and I only enabled JSON.
       I want to get data from the site to load into a mobile app - such as an Android - a hybrid app (meaning coded in HTML/JS and packaged with ionic).

The documentation is a bit confusing to me.  It reads

  "A list of paths and corresponding domains to enable for CORS. Multiple entries should be separated by a comma. Enter one value per line separated by a pipe, in this order:"

  Internal path

  Access-Control-Allow-Origin. Use  to echo back the Origin header.

  Access-Control-Allow-Methods

  Access-Control-Allow-Headers

  Access-Control-Allow-Credentials

  Examples:

  *|http://example.com

  api|http://example.com:8080 http://example.com

  api/*|<mirror>,https://example.com

  api/*|<mirror>|POST|Content-Type,Authorization|true

Do I include Access-Control-Allow-Origin|api/*|http://example.com, or is the domain supposed to represent the domain that can call my service?

Maybe I just need Internal Path and not anything else. None of the examples uses Access-Control-All-*. I don't plan to do more than GET requests at this time.

If your endpoint is "your.host/api/v1/" this minimal CORS module configuration should work for anonymous GET requests:

api/v1/*|<mirror>


content type or normal er table, that is the question I was wondering, when should a drupal developer use normal er table instead a new content type? Is it never? When expected node entries reaches 100 000? i googled it and i didn't find any good answer.

selecting from custom content type with number of fields is very time consuming, because all the join-s. If you have 5-10 content types, each with 10 fields, and expect a lot of nodes, is then the right time to forget about content type?

What are your experiences in this matter?

If you are using Drupal 7, instead of using plain custom tables, use a custom entity type, this is really easy to do with Entity API This gives you basic integration with Views and some other modules such as Rules 'out of the box', and customisation is very easy to handle.

I do not see entities having much overhead above a plain database table when the entities are not fieldable. I have worked on a site with millions of rows of data, which is all available as entities, and we load several thousand of them at a time when necessary, this does require a memory limit larger than 128MB, but I haven't seen memory usage go over 256MB while paginating a thousand or so entities at a time out of the possible millions. (Bear in mind though the entities are not fieldable, and we are using APC which does reduce memory usage.)

You can then also use the full power of entity_metadata_wrapper(), which is really awesome, and simplifies code.

Basicly, entities give you the benefits of a content type, without the overhead of revisions or comments. In fact, nodes are entities, so are taxonomy vocabularies and taxonomy terms.

It is definitely a best practice to use entity API to access entities as this allows all the proper hooks to be run, such as clearing the necessary data from entity cache. However, you are not forced to always use the Entity API to access the database entity rows, but do be aware that there are extra risks and gotcha's attached to this.


How to use the Time ago view formatter when you have an end date collected in your date field? I have a date field in a content type with a collected "end date" and I want to show the end date in a view with the Time ago view formatter.

The problem is that I don't find where to select the end date only display, like in the date and time formatter. Because when I select the Time ago formatter, I don't see the options for select the end date. So when I go to see the view output the Time ago always use the "start date".

This not will solve the "realy" problem with the bug, but is a way:

If you are in a early stage of your project and you don't want use the patch you can delete the field and create two separated fields:

initial_date
final_date

I test it and this works fine.

If you want, you can read this: When should I use collect an end date for a field, instead of using 2 separated date fields?

I will add an explanation in the question about this bug.


Adding users to organic groups in CiviCRM I have a site which uses Organic Groups, specifically with CiviCRM. I want to add a user to a group and I am having issues. The group is marked as closed. I want to how to either

add a user to a existing group
open up a closed group

I haven't been able to figure out how to do either of these.

As @Graham says in his comment, you may want to use the CiviCRM OG Sync module provided with CiviCRM. If your interest is more in coding this, check out how the module does it at https://github.com/civicrm/civicrm-drupal/blob/7.x-master/modules/civicrm_og_sync/civicrm_og_sync.module.


User to send a list of selected nodes via e-mail to the admin I would like the users on a site to be able to select certain nodes and send a list of those nodes to one specific e-mail address.

Gathering the nodes is easy with Nodequeue or Flags, so is sending a mail with Action when a node is flagged. The problem is sending an email with the list when the user want to, when the list is final.

Do you know any solid solution for this problem?

If you don't have a custom module created yet, make one (always good to have at least one custom module for misc tasks).

Create a menu callback for sending the node information in you hook_menu().

function hook_menu(){
  return array(
    'user/%/sendNodes'=>array(
      'type'=>MENU_CALLBACK,
      'page callback' => 'hook_send_nodes',
      'page arguments' => array(1),
    ),
  );
}

Create the callback function to send the nodes.

function hook_send_nodes($uid){
  // Fetch all flagged nodes from database for this $uid.
  // Send this node information through drupal_mail().
  // After your nodes have been sent, use drupal_goto().
}

So now, you can create a link to the URL user/UID/sendNodes and that will send the nodes.
Obviously this is all pseudo-code, but the idea is there.


Unlimited value fields numbered Is it possible to show a numbered output to an unlimited value field (in the input form rather than the display).

Basically I have a field collection and I'd like to show by the side of each one entered a count, so if you write one it looks like

1 | field_one
  | field_two
  | field_three

Then if you added another it would look like

1 | field_one
  | field_two
  | field_three
2 | field_one
  | field_two
  | field_three

and so on...

I'm trying to think where you'd go about doing this, I can't see anything that counts out how many values it has when looking at the $form array in the page itself, and I wouldn't have thought it'd be something that you can do via a template file.

Can this be done?

Wow that was much harder to do than I really thought it would be, for anyone interested in how to do this, you can use the information below, in case anyone is interested I've taken most of the information from this site about how to remove the drag handles, but the principle is the same, added to which, I wanted to remove the drag handles anyway

First you have to create your own module, and use hook_theme_registry_alter to change where the default theming is defined for multiple value fields

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['field_multiple_value_form'])) {
    $theme_registry['field_multiple_value_form']['type'] = 'module';
    $theme_registry['field_multiple_value_form']['theme path'] = drupal_get_path('module', 'mymodule');
    $theme_registry['field_multiple_value_form']['function'] = 'mymodule_theme_field_multiple_value_form';
  }
}

Then you can re-define how it's themed by copying the existing theme_field_multiple_value_form code and writing it into your new function. BUT, be aware that this is going to redefine how ALL unlimited field values work, so really you just want to add in an 'if' clause somewhere, I just put mine at the start

function mymodule_theme_field_multiple_value_form($variables) {
  $element = $variables['element'];
  $output = '';

  if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && $element['#field_name'] != 'field_myfield') {

  // Input normal code, this is for any unlimited input field you DON'T want altering

  } else if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && $element['#field_name'] == 'field_myfield') {

$table_id = drupal_html_id($element['#field_name'] . '_values');
$required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

$header = array(
  array(
    'data' => '' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "",
    'colspan' => 2,
    'class' => array('field-label'),
  ),
);
$rows = array();

// Sort items according to '_weight' (needed when the form comes back after
// preview or failed validation)
$items = array();
foreach (element_children($element) as $key) {
  if ($key === 'add_more') {
    $add_more_button = &$element[$key];
  }
  else {
    $items[] = &$element[$key];
  }
}
usort($items, '_field_sort_items_value_helper');

$count = 1;
// Add the items as table rows.
foreach ($items as $key => $item) {
  unset($item['_weight']);
  $cells = array(
    array(
      'data' => $count,
      'class' => array('count'),
    ),
    drupal_render($item),
  );
  $rows[] = array(
    'data' => $cells,
  );

  $count++;
}

$output = '
';
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
$output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
$output .= '
' . drupal_render($add_more_button) . '
';
$output .= '
';

  } else {
      foreach (element_children($element) as $key) {
        $output .= drupal_render($element[$key]);
      }
    }

    return $output;
  }

Hope this helps someone in the future


Views show empty fields How to use Views to list all empty apartments, which do not have any tenant? So basically I have two content type: Apartment and Tenant as below.

Apartment content type:

Room
Tenant (entity reference to Tenant content type)

Tenant content type:

Name
Phone

Do you guys have any suggestion?

It's simple in Filter Criteria, click add and add your entity reference field.

When you are adding your field, for Operator, select Is Empty (Null)

Drupal 8 Example:

Drupal 7 Example:


An illegal choice has been detected. Please contact the site administrator in drop down list when i am selecting values from dropdown list the corresponding values showing first time. but when i am again selecting the another value its not showing value instead of the error msg displaying An illegal choice has been detected. Please contact the site administrator. can anyone suggest me where i did wrong in the following code

<?php

function form_test_menu()
{
  $items['mark_entry'] = array(
    'title' => 'Mark Entry',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

function form_test_form($form,&$form_submit)
{

$dept = $_POST['dept'];
$batch = $_POST['batch'];
$month = $_POST['Month'];
$year = $_POST['Year'];
$semester = $_POST['semester'];

$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$results = $query->execute();
 $options = array();

foreach($results as $student_result)
{
$options[$student_result->reg_no]=t($student_result->reg_no);
}

  $form['roll']= array(
  '#type' => 'select',
  '#title' => t('Registration Number'),
  '#options' =>$options,
  '#required' => TRUE,
  '#ajax' => array('callback' =>       '_ajaxfunction','wrapper' => 'subjectsdiv'),);

 $form['month'] = array('#title' => t('month'),
    '#type' => 'hidden',
    '#value' => $month,
'#required' => TRUE,);

 $form['year'] = array('#title' => t('year'),
    '#type' => 'hidden',
    '#value' => $year,
'#required' => TRUE,);

 $form['semester'] = array('#title' => t('semester'),
    '#type' => 'hidden',
    '#value' => $semester,
'#required' => TRUE,);

 $form['subjects'] = array('#prefix' => '
','#suffix' => '
');

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

return $form;
}

function _ajaxfunction($form, $form_state)

{

$key = !empty($form_state['values']['roll']) ? $form_state['values']['roll'] : 1;

$month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : 1;

$year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : 1;

$semester = !empty($form_state['values']['semester']) ? $form_state['values']['semester'] : 1;

$query1 = db_select('semester_appear');
$query1->fields('semester_appear',array('subject_code'));
$query1->condition('reg_no',$key,'=') AND $query1->condition('semester_appear',$semester,'=')AND $query1->condition('month',$month,'=') AND $query1->condition('year',$year,'=');
$query1->orderBy('sub_serial_no','ASC');
$results = $query1->execute();

while ($record_res = $results->fetchAssoc())
{

$subject_name = $record_res['subject_code'];

$query = db_select('subject');
$query->fields('subject', array('subject_name','subject_code'));
$query->condition('subject_code',$subject_name,'=') ;
$subject_results = $query->execute();

foreach($subject_results as $sub_result)
{
$options[$sub_result->subject_code]=t($sub_result->subject_name);
}

  $form['subjects']['name']= array(
    '#type' => 'select',
    '#title' => t('Please Select Subject'),
    '#options' => $options,
'#required' => TRUE,);

$form['subjects']['inter'] = array(
  '#type' => 'textfield',
  '#title' => t('Internal Marks'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,);

$form['subjects']['exter'] = array(
  '#type' => 'textfield',
  '#title' => t('External Marks'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,);

}

return $form['subjects'];
}

check for details in watchdog under form to get an indication of which form element is causing the grief - in your case it will be the 'roll' or subject name field (possibly both!)

if you are updating the option array and removing the currently set option, then you have 2 choices:

in your form builder, either

unset($form_state['input']['roll']);

or

$options[$form_state['values']['roll']]
 = "the option i'm trying to get rid of";

the first option just discards the earlier selection, the latter option keeps it available (probably the first option is generally preferable)

additional: I've discovered I can also cause this error by messing my ajax call back so that the options are updated ok, but the form element in the browser isn't updated. In this case you will notice your options are not updating. You then need to double check your callbacks and div id's etc.

hth


Remove field data in submit function Drupal 7. On form validate, I want to:

check the value of one of the form fields [field-1]
based on that value, completely remove another field [field-2] together with its values, from the form

If it makes any difference, [field-2] is a multiple-value entity-reference field.

I think I need to do something like --- get hold of $form_state['values']['field_2'] and set it so that it is in the same state it is before any data was entered by the user.

Am I on the right lines? I haven't been able to find examples or documentation on this.

EDIT:

This is what worked for me in the end:

In the submit function (not the validate function):

// Start with a clean array for the field we want to change.
$form_state['values']['field_2'] = array();
// Restore the array values that correspond to 'empty' for this field.
// In my case this was as follows:
$form_state['values']['field_2']['und'][0]['target_id'] = '';

Short answer is yes you are on the right track. Altering form values on validation can get a little tricky and complex depending on the form. You might want to check out form_set_value if you haven't already.


Using different markup for views last item I need to use different markup for last item displayed by views. Using first last css item does not do the job for me. I assume I would need custom php template probably views-view-fields.tpl.php. What would be the way of doing it?

To do this:

Find template file that adds "last" class
Override it in your custom theme
Expand if responsible for "last" class, to make it contain all element's markup
in if block write markup for last element, in else block - for all other elements.


cannot display new content I am using drupal 7 and i have been having this issue where i am trying to add a new page onto an existing drupal site but all I'm getting is one content (the page title and some body text) displaying.all the content types which include some images that eventually build up the page are  published but are not displaying on the final live site even after clearing the cache both on admin/config/development/performance/cache and on phpmyadmin.i have also created a page--mynewpage--tpl.php page for that page.i believe i have done all the url's correctly.while adding the content types, i referenced the previous working pages just to make sure that i was filling all the required fields so as to have some uniformity within the site
What could i be missing out on, since i added the link of my new page to the page.tpl.php.
I have been trying to get a solution for this for a week now and any assistance form you will be greatly appreciated

are you inserting "inline images" into your content type body-field (1) or using an image field at your content type (2)?

1) Inline images are inserted with an  tag which is stripped out by the standard text formatter (filtered html). Either use the "full html" formatter or (better) make a new text formatter which includes  tags for allowed html tags. Full html is normally below body field at the content edit form.
To add a text formatter (or edit filtered html) go to admin/config/content/formats/filtered_html and add the  tag (including the bracers) into the allowed html tags field.

2) If you are using an image field try to change the image field formatter to "image" and set format settings to a image style like "medium".

Greetings, krueschi


Problem installing a module When I try to enable a module I get

Fatal error: Call to undefined function modulename_cron() in /home/modulename.install on line 17

In modulename.install I have

function modulename_install() {
  db_query('ALTER TABLE {node_revisions} ENGINE = MYISAM');
  db_query('ALTER TABLE {node_revisions} ADD FULLTEXT `similar` (`title`, `body`)');
  modulename_cron();
}

module_cron() is definitely defined in my modulename.module file. What could cause this problem and how could I fix it?

Have a look at the documentation for hook_install. It says:

  Note that functions declared in the module being installed are not yet available. The implementation of hook_install() will need to explicitly load the module before any declared functions may be invoked.


Is it possible to put existing/shared Content type fields as Feature code each in their own individual file to simplify/avoid git merge conflicts? We have a set of content types that share common fields - in that we re-use them in several content types.

When recreating these content types as a Feature, the fields are all in one large file. This has proven to be difficult when resolving git merge conflicts when people adjust/remove/or add fields to content types as a normal part of development. The git ===== >>>>> <<<<< conflict markers 'cross over' different fields and make it hard to see how the merge should be done correctly.

I think a better solution is to have each field in its own file, even if there are hundreds, the host file system should be able to handle this, perhaps even use of directories may help, this would avoid complex merge conflict resolutions.

Is this single file per field possible?

We faced similar problems, what we did was, we created a 4 features of similar fields that were used in multiple content types. This made sure that if a person is working on a similar funtionaltiy, he is responsible for all the content types.
Yes, we still need to be careful for this, but dividing it into multiple features did solve many issues.


Best practices for protecting from injection on form fields I am building a form in Drupal 7. I have a textarea field and would like to know if it is safe to get the field content ($form['values']['field_name']) and save it to the database using something like db_insert, db_update or db_merge. OR do I have to do some sort of filtering to avoid SQL injection attacks. Thank you

If you use the Drupal core database API functions, the content will be automatically escaped, preventing SQL injection.

You can run the content through filter_xss prior to insert, otherwise you'll need to do that on display.

Drupal core stores the content unsanitized and sanitizes it on output.

User input should be validated on input and filtered on output.

More info on sanitization functions here: http://api.drupal.org/api/drupal/includes!common.inc/group/sanitization/7

See also http://drupal.org/writing-secure-code for information on writing secure code.


Associate a Taxonomy term to user who creates it I have field Company Name which is a term reference to a vocabulary with same name. when user types the field if name already exists, so auto complete showed that or else it will be added as taxonomy term. let us consider "BBB" is the company name he entered.

On next scenario when another user keying in this company name as "BBB" so its already their in the taxonomy so i have to send a mail to the user who created added the term "BBB" first.

I tried using rules module but i couldn't find way to get the user who created the term.Meanwhile i use Profile2 module so writing submit handler is best?

Taxonomy doesnt contain this kind of data.
A possible workaround would be-
Creation of a custom module that writes data into a custom table.
You can use hooks to intercept the addition of the item.


Restricted access url for an image uploaded to private filesystem I have a custom content type with an image and a file field, both of which are uploaded to the private file system.

How do I create a public url to the image that will check for user permissions so that anonymous users are prevented from being able to browse to the image?

This is the code I tried first:

$url = file_create_url($node->field_my_private_image[$node->language][0]['uri']);

It generates a url to system/files/ but that url is visible to anonymous users and it isn't being restricted by user permissions.

I saw a security patch for drupal 7.13, but it was supposedly fixed and I'm using drupal 7.22.

Is there a built-in way to do this or do I need to implement some functions in my module to respond to special urls to access these files which will check permissions and then stream the file back to the browser?

You want to implement hook_file_download in Drupal 7.

  Control access to private file downloads and specify HTTP headers.

  This hook allows modules enforce permissions on file downloads when
  the private file download method is selected. Modules can also provide
  headers to specify information like the file's name or MIME type.

A small example:

function mymodule_file_download($uri) {
  global $user;

  // Does the user have access based on some criteria ?
  if (!user_access('ACCESS PAY-PER-DOWNLOAD-CONTENT', $user)) {
    return -1;
  }

  // Does this module own the file given by the $uri ?
  if (db_query('
          SELECT fu.module
          FROM {file_usage} fu
          WHERE fu.module = :module_name AND fu.uri = :uri',
          array(':module_name' => 'mymodule',
                ':uri' => $uri)->rowCount() < 1) {
    return NULL;
  }

  // If the above conditions fallthru then populate HTTP header arrays
  // for content download; If you need to grab the file object and work on
  // it -- say output CSV from the data, you can grab it as follows ...
  $files = file_load_multiple(array(), array('uri' => $uri));
  // If empty, $file will be false, otherwise will contain the required file.
  $file = reset($files);

  return array('Content-Type' => file_get_mimetype($uri));
}


How do you return an entity property of 'type' => 'struct' I am using Drupal 7.x and have a created a custom entity. I am using the Entity API module to extend EntityDefaultMetadataController and override public function entityPropertyInfo() to add properties for displaying when my entity is viewed.

More information on  hook_property_entity_info:

http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.api.php/function/hook_entity_property_info/7

I understand how to return different types of properties such as 'text', 'int', 'list', 'entity', and so on, using callbacks.  However, I have not been able to successfully return a type of 'struct'.  My field is always empty when I try to display it.

Example code:

  $info['properties']['my-structure_property'] = array(
  'label' => t('My Structure Property'),
  'type' => 'struct',
  'getter callback' => ?  // What should this return?
  'property info' => array(
    'sub_field1' => array(
      'type' => 'text',
      'label' => t('Subfield 1'),
      'getter callback' => 'entity_metadata_sub_field1_property_get', // Returns a text field
    ),
    'sub_field2' => array(
      'type' => 'entity',
      'label' => t('Subfield 1'),
      'getter callback' => 'entity_metadata_sub_field2_property_get', // Returns an entity
    ),
  ),
);

What should I be returning in my callback?  I have tried returning an object, an array...?

Based on entity_metadata_node_entity_property_info_alter() and entity_property_text_formatted_info(), I suppose the getter callback should be the most generic callback the entity API offers: entity_property_verbatim_get.

This should allow you to access the properties as: $custom_entity->structure_property->sub_field1


How to share some content in a multisite? I'm working on the Drupal 8 multisite where there is main site and partner sites.

For example partners publish events or news.

I want some content from partner sites to be available on the main site. How can this be done?

What I discovered so far:

sharing db tables seems tricky - there are just to many node tables and their dependencies will likely break.
I could create custom entity but then its not place in "content" (beacause it's not node type) and I will lose nice content handling. but tables are easier to share then.
I could copy the content but then i have copies not the same content (what are possibilities here?)

There are quite a few solutions available in Drupal contrib which allows sites to share the content with each other:

Workspace In core now creates multiple versions of the site.
Entity Pilot is a really good use core serializer solution. It tracks changes allow and merging via UI. If you want to track the content then you can also use Entity Pilot Git
.
CPS D7 version only.
Domain access if your site shares the domain name then this is the best solution to display the same content on different domains.
Default Content you have to manually import export the content.
D8 to D8 migration is the last ditch solution there is no D8 to D8 migration in Drupal core at this moment but you can export content in CSV using CSV Serialization and then import it via Migrate Source CSV. The sites can periodically import or export data in hook_cron.


How to add captcha to pdf version I want to add a captcha to the PDF generator from the Print Module so that my server doesn't waste time generating a PDF for robots and to prevent DOS attacks.

There is a similar question asked, but the accepted answer doesn't actually answer my question (the PDF Version part), but rather only the E-mail part.

Since the PDF Version doesn't link to a form, there isn't a form ID I can add to the Captcha module. Is there a way to require a CaPTCHA to download/generate a PDF?

First you should avoid captcha, their are not user friendly. But good new, in this case you don't need it :).

Print module generate the pdf once and cache it https://drupal.org/node/516466#comment-6390678. So DOS are not possible on pdf generation.

You can still have DOS by requesting a pdf thousand of time, saturating your bandwidth. If you are really worried about that you can for example configure Apache with mod_evasive http://systembash.com/content/how-to-stop-an-apache-ddos-attack-with-mod_evasive/

By robot I suppose you mean search engine robot. You can add that in your robot.txt (But I think is not necessary):

User Agent: *
Disallow: /*.pdf$


"Add to cart" minimum order quantity I am using Ubercart 2 on Drupal 6 with http://drupal.org/project/uc_product_minmax. It works well, except for the fact that the default catalog only provides an 'Add to cart' button with no quantity field, and the quantity it adds is 1, which makes it useless as the minimum order quantity in this particular case is 2.

I have tried implementing hook_add_to_cart() to forcefully change $qty to 2 if it's lower only to find that I cannot manipulate it before uc_product_minmax implements the hook, so I'm in need of an alternative.

Maybe this isn't even fixable without modifying uc_product_minmax itself, but I'm up for trying any other ideas.

If you want to alter the cart item, then you can use hook_uc_cart_alter of ubercart.

  This is called every time the cart is rebuild (e.g. when products are
  added), so it's a good place to alter the cart item.

Code snippets to modify the qty of the item

/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your product

    $items[$index]->qty = 2;
  }
}

For reference:

http://www.ubercart.org/docs/api/hook_uc_cart_alter


how to programmatically set a group audience I am trying to programmatically add the group audience widget to a custom form (without using OG field setting) and set it to a default value.

Would anyone know of a way to do so?

Well after one week of investigation i still haven t find an answer. I gotta say i am really dispointed by OG module, the documentation is so poor and the maintainer doesn't really help improving this. A real shame such a module isn't more documented

First in your .install when creating your content type, add:

og_create_field(OG_AUDIENCE_FIELD, 'node', 'bundle_name_of_your_content_type');

Then when you need to assign a fresh new content of your content type to an existing group, you can do it in two ways:

1) Found it http://drupal.org/node/1249396#comment-4885442 and thanks to tenken

$node = node_load($nid);
$values = array(
  'entity type' => 'node',
  'entity' => $node,
  'state' => OG_STATE_ACTIVE);
og_group($gid, $values);
node_save($node);

2) Maybe less sexy

$node = node_load($nid);
$node->group_audience['und'][0] = array(
  'gid' => $gid,
  'state' => OG_STATE_ACTIVE,
  'created' => mktime());
node_save($node);

Cheers


Is it possible to show contents in a specific sites for multilingual site? Is it possible to show contents in a specific sites for multilingual
  site?

I have a site of multilingual support with english and bangla language.
There is a content type blog. so Now I want to publish english content in a en.demo.com site and bangla content at bn.demo.com site and the different content will be visible at different site and it will generate different url. Is it possible and how ?

Go to en/admin/config/regional/language/configure and make sure URL is at the top. Press configure and select Domain. There you go.


How to know which users/nodes failed to import in feeds logs? I'm trying to convert my implementation from the location to geofield modules. Not finding an easy way to convert the data, I tried the manual way which is to export the data to CSV and then repopulate the appropriate fields through fields. The issue is I have a lot of users, around a 1000, and the feeds log is just telling me that 44 of them failed. Is there anyway to know which ones failed? The feeds log doesn't give me a lot of diagnostic information, and manually checking is going to be a pain.

So views data export will truncate some user names based on their lengths. This resulted in a mismatch between the exported users' name and the user name in the DB, leading to errors.


Programmatically get field definition for custom user profile fields I created several custom user profile fields, including Full Name (a plain text field) and County (a List (text) field). They are displayed on the /user/#/edit form. I want to display these fields (and several others) in a different form I am generating via custom module code.

Question: Is it possible to extract the definition of a field, including its label, default value, and, in the case of County, the list of allowed values?

I imagine a field is an entity of some kind that can be extracted, but after much reading, I haven't seen how. I'm likely just not using the right terminology.

I could easily hard-code replicas of these fields in the PHP+HTML form, but I want to maintain the label, default value, list of allowable values, etc. for them in just one place--as part of the user profile. Thus, I want to extract their definitions and output them into the form I build.

Yes you can get field definition programmatically with field name and entity name, by using EntityFieldManager::getFieldDefinitions.
For your select list how to get allowed values check this example

 $options_array = [];
    $field_name = 'field_country_list';
    $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('custom_entity_name', 'bundle');

    if (isset($definitions[$field_name])) {
      $options_array = $definitions[$field_name]->getSetting('allowed_values');
    }

source : https://api.drupal.org/comment/63953#comment-63953


Access to selected taxonomy terms on user profile field I have a taxonomy vocabulary Area. The terms of this vocabulary are the main menu items. There are no other links in the main menu.

I have a term reference field on user profile.

For every user the main menu should only display those terms which are selected on their profile and have to access to those taxonomy terms only.

Is it possible with any contrib module? Or any idea how to achieve this functionality?

I have achieved this functionality with the following method.

Created a taxonomy term type view which will list only the top level terms.

Added a relationship to view  Taxonomy term: User using Area

Added another relationship Taxonomy term: Parent term

Added a contextual filter on uid for currently logged in user.

This will list only those terms which are selected on user profile. And then display this view as a main menu in the panels.

And then using rules, I return Access denied if a user try to access the taxonomy term page which is not selected on his/her profile.

Hope it will help someone.


Can we change the schema in services module? I am new to Drupal services; I have the below XML format, in which I need to expose nodes as services.

Can I do this using the Services module?

    <?xml version="1.0" encoding="UTF-8"?>
<ngd:mediafile xmlns:ngd="http://www.xyzy.com/ngdine"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.xyzy.com/ngdine mediafile.xsd">
  <ngd:description>
    <![CDATA[This is the description]]>
  </ngd:description>
  <ngd:mediatype id="1"/>
  <ngd:internal>Aalborg city.JPG</ngd:internal>
</ngd:mediafile>

Can I change the schema?

If you need to expose the output that way, THeres 2 ways you can do it. You can alter the response before it gets sent as a payload, or you can write your own Response Format.

Both should do what you need, but its merely a preference.

/**
 * Triggered when the REST server request a list of supported response formats.
 *
 * @param array $formatters
 *  An associative array of formatter info arrays keyed by type extension. The
 *  formatter info specifies an array of 'mime types' that corresponds to the
 *  output format; a 'view' class that is a subclass of RESTServerView; and
 *  'view arguments' that should be passed to the view when it is created;
 *  a 'model' can also be specified which the controller then must declare
 *  support for to be able to serve data in that format.
 * @return void
 */
 function hook_rest_server_response_formatters_alter(&$formatters) {
   /*
    * Sample modifications of the formatters array. Both yaml and
    * rss are formats that already are supported, so the changes are
    * nonsensical but illustrates the proper use of this hook.
    */

    // Add a Yaml response format.
    $formatters['yaml'] = array(
      'mime types' => array('text/plain', 'application/x-yaml', 'text/yaml'),
      'view' => 'RESTServerViewBuiltIn',
      'view arguments' => array('format' => 'yaml'),
    );

    // Add a Rss response format.
    $formatters['rss'] = array(
     'model' => 'ResourceFeedModel',
     'mime types' => array('text/xml'),
     'view' => 'RssFormatView',
    );
 }

The altering of the response is, function HOOK_services_request_postprocess_alter


How to add {less} files to Omega HTML5 subtheme? I would like to use less.js and the less module to work with my Omega-based HTML5 themes.
How to add **.css.less* files to the Omega-based subtheme .info file ?

My current set up is:

/sites/all/themes/omega - the Omega master theme directory
/sites/all/themes/custom-html5 - Omega-based HTML5 subtheme directory
/sites/all/themes/custom-html5/css/custom-html5-alpha-default.css -
my default css file

This question is related to

my previous one: How to use CSS preprocessor LESS.js with Drupal 7?

Install the LESS module and then in your custom-html5.info file just add your LESS CSS files like you would normally add stylesheets:-

stylesheets[all][] = css/custom-html5-alpha-default.less

The module will detect the LESS files (those with a .less file extension) and process them so that they are output as standard CSS.

Processing the LESS files on the server rather than via the browser using JavaScript will give the end user a better experience and ensures that the look of your site isn't dependent on JavaScript. If you really must include the less.js file then perhaps you could consider using the drupal_add_js() method in your template.php file.


Sort related nodes in block views based on a score calculated with common vocabulary Is it possible in drupal8 with Views to show related nodes in a block based on a score calculated with common vocabulary (each common tag adds some  affinity points depending on vocabulary type).

The sorting in views is ordered by:
1- Editor manual selection.
2- Best related nodes ordered by max affinity with the current node
3- Nodes sorted by date

Regards,
Thanks for your help

To place the php code to calculate the score there are several approaches:

Add an extra field for the score to your content type and calculate it in submit or
presave.
Add a custom views field plugin:
http://enzolutions.com/articles/2015/10/11/how-to-include-php-code-in-drupal-8-views/ or a custom sort plugin: https://chromatichq.com/blog/create-custom-views-sort-plugin-drupal-8
Use the module Computed Field.

With (1) you save the value in the database. This is best for calculations that don't change after saving the content.

A custom views plugin (2) is more dynamic and needs no space in the database, but it has to be recalculated each time.

The extra module (3) can do both, but it is not ready for production, still in alpha. If you read the linked how-to for views field plugins in (2) there are some good points that in D8 plugins are often more powerful than contrib modules to extend Drupal with custom php code.


Node edit page not showing up using page.tpl.php? I'm working on a new drupal 7 site right now (I'm new to drupal) and currently have given the ability to users to create nodes. The node creation page (url.com/node/add/) works just fine and uses the page.tpl.php template.

However, when I'm using the edit page (url.com/node/NODEID/edit/), it doesn't even load a page.tpl.php file. I went ahead and added some code to my page.tpl.php file to see if it would even read out--which it didn't. I've found that the edit page is inserting itself at the html.tpl.php level of the site. Is there a quick way I can get this to use page.tpl.php or by creating a node--edit.tpl.php or something? Hopefully I have made enough sense, but am stuck.

Make sure you have the setting 'Use the administration theme when editing or creating content' unchecked in you 'appearance' settings page. This would override your theme on the node edit pages causing your page.tpl.php file not to be used.


"drush up" turns off all of my modules I'm using drush to make version updates and any time a module (in todays case, recaptcha) needs to be updated, it successfully does the update.  However it seems to reset the database turning off every single non-core drupal module.

I cant find anything about this on the internet anywhere. Anyone have any ideas?

When you run drush up, you are actually updating Drupal core along with contrib modules and themes. Try:
drush up recaptcha -y
This will update the recaptcha module only, with no confirmation needed.


Not all content showing up after uploading to live server I have been working on a site for a client and I have ran into a bit of an issue. I built the site locally and then pushed it to a staging server to show the client and everything is running fine. When we got to the point of launching the site, we did what our team normally does and everything seems to be working fine until you look at the page content... It only shows the first sentence.

Here is an example of what's going on:

staging server:

live server:

My head is hurting from trying to figure this one out. I am using a custom theme and using  to display the data on the left hand side like we always do, so that shouldn't be the problem. I am just at a loss, any little help would be awesome!

It could be a control character that would remain or be not there when moving from one platform to another. Line breaks in Windows, UNIX and Macintosh text files all are different. If you have moved the database from one platform to another care should be taken to insure cr lf couplets are considered.

A similar situation could result from a database conversion that did not take into account these differences.


What are the various steps to contribute my own module to Drupal.org? I wrote a custom javascript thing for the Views module but I'm not sure how to go about publishing this on drupal.org.

I know there are a lot of requirements, but what are the steps to be completed and where to publish (contribute) this module?

It seems daunting since I never contributed a module before.

The main pages you need to read are Best practices for creating and maintaining projects and Project application checklist.  If you have never done this before, you need to read Creating a sandbox (experimental) project

In short, you need to

Obtain git access on drupal.org
Create your sandbox project
Commit your code
Submit it for review
If approved, it will be promoted to be a full project

Keep in mind that your project will likely never be officially reviewed unless you get a review bonus.  Participating in other reviews is also a good way to learn about best practices so you can get through the initial review smoothly.


Twig finds if statement true whether or not field has value I have a paragraphs field that contains a sub-title which is optional. My code below still prints out the h3 tag whether or not the sub-title has any value. Any idea why this is happening as I need to hide the h3 html if there is no value, thanks.

{% block content %}

{{ content.field_title }}

            {% if content.field_sub_title %}

{{ content.field_sub_title }}

            {% endif %}

              {{ content.field_prod }}

{% endblock %}

Look at the object itself not the render array:

{% if paragraph.field_sub_title %}
  <h3>{{ content.field_sub_title }}</h3>
{% endif %}


unable to add,edit,delete content types in drupal 7? I'm unable to add, edit, delete content types and content also in Drupal 7, the button links are not working. If I click add, edit, delete button below an error happens. What could be wrong here?

Try following steps.

Make sure clean URLs working first. If you need any help for clean URL visit this link
Try clear cache and then disable all contributed modules. I see there is a problem due to commerce line items module. Disable all contributed modules. Don't disable core modules.
Clear cache and check.

Tell me in comments if you still face problem.


Get clean date without any HTML tags I am using the Date module together with a view to display dates, and I need to get the date timestamp. The problem is that $fields['date_in_timestamp'] content comes wrapped in HTML.

<span class="date-display-single"> 1468473300 </span>

I need only the value and no HTML.

PS: my field "date_in_timestamp" will apply a "U" format for the timestamp.

One possible way I found is described in https://www.drupal.org/node/423870, comment #9. The problem is that this applies to all those who have a certain format, and I don't know how to distinguish them from other similar formats.

Is there any way to get the machine name of the date format?

The solution that worked for me in this case was easier than I thought.

Solution:

In the configurations of the view

1.-
Select settings Style ->
Customize HTML field -> None

Uncheck Add default classes

2.-
In Rewrite results -> Select Strip HTML tags


How to add css to specific blocks or view with CSS injector module? How to add css to specific blocks or view with CSS injector module?

I can add css to specific pages, but what about blocks, views and all sorts of other nodes?

I am try already this but i think it would be helpfull

Use php section to add css against any view or block
and try this one

<?php
if ( $block->module == 'your_block_id/name'){
          //add some code here
}
?>

Or can do it by add a class in view or block


Field Template Suggestions: Target a particular field type on a content type I want to use a field template for all the fields on my "journal_page" content type that use a widget of "long text".
How would I do this?
N.B.  My field is not named "long text". "Long text" is the name of the widget I am using (It is a text field). I want to use the same template file for multiple differently named fields. The only thing they have in common is the widget type.

 Steps I have tried
On Drupal Theming suggestions it says you must use the following format: field--[type|name[--content-type]|content-type].tpl.php, so:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php

I tried the following but, none have worked:

field--long-text--journal-page.tpl.php
field--long_text--journal_page.tpl.php

I just happened upon this question while trying to remember how to solve the same problem. In this case, Drupal simply doesn't do what you're asking for by default. There are two ways to approach it, one by accepting Drupal's default behaviour, and one by overriding that default.

Default behaviour

As has already been pointed out here, Drupal's template suggestions for fields don't consider the field type (though they do accommodate the content type).

Living with Drupal's default behaviour

This is the simplest solution, though it's a bit inflexible. Since your goal is to use only one template, what you can do is this:

Create a field template in our theme according to the field--field-name--content-type.tpl.php pattern. This will customize one of your fields.
Create symlinks to your original template containing the names of the other fields you need to customize.

For example, given fields with names lorem, ipsum, dolor and sit, and the content type contenttype, you'd create one template:

field--lorem--contenttype.tpl.php

Then, you'd create the following symlinks to that template:

field--ipsum--contenttype.tpl.php,
field--dolor--contenttype.tpl.php,
field--sit--contenttype.tpl.php

Drupal will see these as four different but identical files.

Overriding Drupal's default behaviour

The previous solution is quick and simple, but slightly unsatisfying. If Drupal's so flexible, we should be able to handle this problem using the Drupal API, right?

Well, it turns out we can. It's possible for us to add our own template suggestions.

We do this like this:

1. Implement template_preprocess_field()

/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  if ($variables['element']['#bundle'] === 'contenttype' && $variables['element']['#field_type'] === 'text_long') {
    $variables['theme_hook_suggestions'][] = 'field__contenttype__text_long';
  }
}

2. Copy field.tpl.php to your theme

Copy field.tpl.php from modules/field/theme/field.tpl.php to sites/all/THEMENAME/field--contenttype--text-long.tpl.php and then customize to suit.

Notes

The logic in the template_preprocess_field() implementation could be changed in several ways, e.g. to match only by field name in a given content type instead of all examples of a field type in that content type.
The process is almost the same when doing this task in a module except that you'll also need an implementation of hook_theme() in the module to make it work.
It would be possible to to this using only theme_field(), but theme functions are deprecated in Drupal 8, so this is the method that we'll all be using going forward.


http to https htaccess always redirecting to home page I have found following .htaccess code on stackoverflow.com to convert the http requests to https

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

it is converting the http to https but always goes to the home page

suppose If I am trying to go to http://domain.com/about-us it routes me to https://domain.com

Just for information I am using redirect and global redirect module but even if I am disabling them both the result is same.

By default, Drupal includes an .htaccess file that has instructions in the comments for doing https redirection.  I suggest you follow the instructions in that file.

From Drupal 7.22:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]


Get node path for Entity Referenced in Views I have two Content Types: Product and Offer.

Offer has a Entity Reference field to Product

I'm making a view with Offers, and I want to get the Product URL in this View. I was trying with Relations but I have no result.

You already have the Entity Reference module installed and that is sufficient.

Create a view with base table Offer. Then add a relationship as follows: Click on add relationship, select filter by Entity Reference which will only show the entity referenced endpoints. It will show the field in question from two directions. You are working from the entity that contains a reference to another entity. You therefore select the 'A bridge to the Content entity that is referenced via field_whatver.

This pulls in the related entity. Now you just have to add the new field (URL) to your view and make sure that you set the relationship when you add it to the relationship you defined.


How to avoid caching of fields in Entity View? I have a few computed fields on my entity and they have dynamic values. These values cannot be cached because they change often.

I've created the necessary field formatter that uses the same approach that the comment module uses to display the uncached comment form by using the #post_cache_render callback.

This I found does not always work(the value is sometimes displayed in one view mode but not in another).

The other issue I have is that if the value is empty, the field label is still visible because it is not part of the formatter and therefore it is cached with the rest of the Entity View data.

So my question is: how can I use fields with dynamic values so they won't get cached in the Entity View?

I've also tried all hooks that allow adding or changing data in the Entity View but every single one get's cached and so I found it impossible to avoid the cache.

You can not do it per field, that would defeat the purpose. The whole entity is cached.

You can disable render caching for your entity by setting render_cache = FALSE in your annotion and you can do it per view mode.


How can I improve as a site builder for dealing with errors I don't know how to handle? As a relatively new Site Builder, I understand some of what is going on under the hood. But when things go wrong .…

Without an intimate knowledge of module code and inner workings, the error messages often simply tell me something went wrong.

Furthermore, I don’t know if a particular message occurred from the action I just executed, or if I have simply not been to a specific page in a while (or never before), in which case any number of actions could have broken it.

In any case, I have no idea what messages like this one mean:

'Notice: Undefined index: var_name in _some_method_some_where() (line 35 .…'

This are the steps I typically perform (my workflow) to resolve an error:

Check the module's issue queue for known bugs –  Occasionally I find a known problem.
Google the error – Normally this doesn’t help as the same error could happen for so many reasons, but occasionally it leads me to a fix.
Ask a developer if possible – They often have no idea about my problems …
Ignore the error and keep working.
If my site is really broken, I try to reset (ugh) or give up on the module altogether and do something else (sigh).

As a site builder, I really don't want to dive into the code every time.

How can I improve my workflow? Like what other steps, resources, approaches, etc would you recommend to a site builder when such kind of things go wrong?

I'm not really aware of a way to improve your workflow. In general I would recommend limiting your usage to modules that have hundreds or thousands of Downloads by site builders, but that is not a silver bullet. And, sometimes you need to use that -dev module that has only 5 downloads because it will save you tons of time in development work on your project.

Everyone typically builds up a listing modules they are familiar with, comfortable with and trust -- build that list for yourself.

Something you didnt mention and I think is a larger problem than what you've outlined is testing module updates to an existing site that is using tried/tested modules previously. I'm more scared of things breaking during a large update (even amongst stable modules) -- then of experimenting with modules earlier in my site building process.


Dynamic Fields at content type level I got a site where we got pages tagged with several taxonomy terms. We also got several Contactblocks (added as Content Type & displayed by Views) that are tagged with the same set of taxonomy terms.

The Content Type "Contactblock" has the fields E-Mail, Phone & Room. Those Fields may vary from page to page. The reason behind this is some employees have different positions and those have to be displayed on different pages with different information. May way to go atm was to add multiple Contactblocks but its not clean enough for me.

My idea was to display for each tagged term a specific field of E-Mail, Phone & Room. But idk how the system can associate it then..

Atm its like page<->taxonomy term<->contactblock but it should be like page<->taxonomy term, for each tax term<->create fields: mail, phone & room

Any idea how I can solve this? Any better idea is apreciated

Yes you can add fields: mail, phone & room to each of your tax terms, but the problem would be that all your employees would have the same mail, phone & room, because the fields belong to the tax term and not the employee. Unless you create a unique tax term for each of your employees this would work, but why do this when page<->contactBlock will do the same?

So either you stick with page<->taxonomy term<->contactblock

or go with page<->contactBlock using the Entity Reference module in D7 (for D8 Drupal Core already has this module's features). This option will save you save Database space since you don't create tax terms.