print individual field inside views-view.tpl.php I need to theme my view inside views template. Inside custom views-view.tpl.php template I can add individual fields inside loop:

<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
//after a loop I can add any other field for custom theming like so:
<?php print $item['myfield2']; ?>

Question: How can I add another field before the loop is executed? I tried this:

<?php print $item['myfield3']; ?>
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

But the field3 is not rendered because the $item is not defined, I think.

I am not php programmer so I came up with a dumb workaround

<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php endforeach; ?>
<?php print $item['myfield3']; ?>
//field is rendered
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

What is the correct way of displaying an individual field without putting it inside foreach loop?

Thank you

You are wise to admit it before someone else points it out:  "I am not php programmer." ;)  This is a pure PHP problem, having very little to do with Drupal.

Your foreach() loop defines the variables $delta and $item.  Unlike some other languages, they are still in scope when the loop finishes, keeping the values they had at the end of the loop.

You could do something like this (untested):

<?php
  $first_item = reset($view->style_plugin->rendered_fields);
  $last_item = end($view->style_plugin->rendered_fields);
  print $first_item['myfield1'];
  pring $last_item['myfield2'];
?>

After the foreach() loop, $item would be the same as $last_item.

The PHP docs are pretty good:  arrays
and array functions.


Using EntityFieldQuery to order nodes in an OG Group using node_comment_statistics table I have an EntityFieldQuery to fetch nodes of a certain type which belong to an OG group in a Drupal Commons instance.

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', array('post', 'document', 'link'), 'IN')
    ->propertyCondition('status', 1)
    ->fieldCondition('og_group_ref', 'target_id', $panel_args[0], '=');

I was wondering if it was possible to also add the condition to order the nodes by most recent comment using the information from the node_comments_statistics table and the last_comment_timestamp.

Is this possible with EFQ since their are no joins? Or will I have to fall back to a basic Drupal Query?

Add the custom TAG to the EntityFieldQuery and than use the hook_query_TAG_alter() to add the JOIN to the query as below:
// Create the query as below (Note: "CUSTOMTAG" added for altering the query)
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', array('post', 'document', 'link'), 'IN')
  ->propertyCondition('status', 1)
  ->fieldCondition('og_group_ref', 'target_id', $panel_args[0], '=');
  // Added the Tag, which we will be using to alter the query.
  ->addTag('CUSTOMTAG');
  // Complete the query (if you are having any other field condition).
  ->execute();

/**
 * Implements hook_query_TAG_alter()
 */
function MyModule_query_CUSTOMTAG_alter(QueryAlterableInterface $query) {
  // Add the join to the "node_comment_statistics" table.
  $query->join('node_comment_statistics', 'ncs', 'ncs.nid = node.nid');
  $query->orderBy('ncs.last_comment_timestamp')
}

Reference links:
https://drupal.org/node/1157006#comment-7634027
http://www.phase2technology.com/blog/or-queries-with-entityfieldquery/


How do I extract filename and filepath from a file field? Here is what I am trying to tackle: I would like to allow a zip file to be uploaded via the default filefield upload widget for a content type. I am using hook_node_presave to take the zip file and extract is using a helper function based off of the core update manager. The error I am receiving is:

  Notice: Undefined index: filename in filefield_unzip_node_presave() (line 18 of
  /sites/all/modules/filefield_unzip/filefield_unzip.module).
     Notice: Undefined index: uri in filefield_unzip_node_presave() (line 19 of
  /sites/all/modules/filefield_unzip/filefield_unzip.module).
     Exception: Archivers can only operate on local files:  >not supported in archiver_get_archiver() (line 8149 of /include
  /common.inc).

Here is my code:

/**
* @file

* Allows uploading and extracting a zip file uploaded to a file field.
*/

/**
 *
 * Implementation of hook_node_presave($node)
 *
 */

function filefield_unzip_node_presave($node) {
if($node->type == 'game') {
    if (!empty($node->field_game_files)) {
        $zipFile = $node->field_game_files['und'][0]['filename'];
        $zipDirectory = $node->field_game_files['und'][0]['uri'];

        _filefield_unzip_archive_extract($zipFile, $zipDirectory);
    }
}
}

/**
 *
 * Copy of the function used by the update manager update_manager_archive_extract($file, $directory)
 *
 */

function _filefield_unzip_archive_extract($file, $directory) {
$archiver = archiver_get_archiver($file);
if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $file)));
}

//Remove the directory if it exists, otherwise it might contain a mixture of old files mixed with new files (e.g. in cases where files
//were removed from a later release).
$files = $archiver->listContents();

//Unfortunately, we can only use the direct name to determine the project name. Some archivers list the first file as the directory (i.e., MODULE/)
//and others list an actual file (i.e., MODULE/README.TXT).
$project = strtok($files[0], '/\\');

$extract_location = $directory . '/' .$project;
if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
}

$archiver->extract($directory);
return $archiver;
}

I found a solution to this, however stackexchange won't let me add an answer for 8 hours. I have it all typed out so if I forget to come back and upload it feel free to post on here to request the answer and remind me.

go on...


Search API - Acquia Search - Keyword Search I'm using Acquia Search for searching within certain content types (articles, posts, etc). It seems to work for certain keywords but not others. For example, if I search: "Apple TV", I'm expecting the article title: "Spectrum Launches on Apple TV, Offers Apple TV 4K to Customers" to show up (which it does). However, if I search for "4K" the search API brings back "no results".

I reviewed our Acquia connector set up, re-indexed all content and tried with no success. The weird thing is, if I search "4K to customers" it shows the correct article with "4K" also being highlighted (in search results). Does any one have any idea why this would happen? It seems that our config is set up to read basically every field in each content type included and it does seem that this article is indexed. Does anyone have an idea to point me in the right direction?

I'm using the latest versions of Acquia connector, acquia search, search API and Drupal 8.

Set your Minimum keyword length to 2 in the filter criteria of your search-view


Best approach to move content between different instances/installations As most of us are, I am involved on a project where we have different environments.
I have created a profile for the initial installation and we are working with Features to maintain all environments with the same Content Types definition, views, rules, ... When we need to do a change, then we recreate the feature and put in the other environment.

Sometimes I have found I can't do a revert of one feature due to existing data, so I feel interesting and needed to have a very strong mechanism to extract, delete and put again into the site created content.

Also, in the case the customer will use the preproduction environment to start using the application, they will want these contents will be placed into the production environment without the need to create them again.

So I am looking for a strong solution to keep all the contents of the site, easy to backup and move between environments.

I have been playing with:
 - node_export
 - node export dependency
 - field_collection_deploy
 - bulk_copy

But I can't achieve to have a strong copy of the content. One of the content types has Taxonomy references and field collections those are not exported/imported, and at the end of the import I have several Notices as:

Notice : Trying to get property of non-object dans field_collection_field_get_entity() (ligne 1679 dans /users/cve00/web/html/sites/all/modules/contrib/field_collection/field_collection.module).

Please, I'll appreciate if anybody could point me to the best procedure to accomplish this common need or guide me to do it with these modules if I am missing some operation.

Thanks in advance.

PS.- Even if someone will remove this sentence by editing the post, I feel grateful for your reading :)

After discussion on freenode #drupal, I have had the advice to avoid as much as possible migration or copy-content, so I am going to use a dump from preprod environment to install the production one, what I thought it wasn't the best solution, it seems in this case it will be the simplest and valid.

I'll still appreciate all kind of thoughts of this issue.


7 Views $variables/$views/$fields crashing browser Any of following codes in views-view-fields--MYVIEW.tpl.php make my browser unresponsive:

<?php kpr( $variables ); ?>

<?php kpr( $fields ); ?>

<?php kpr( $view ); ?>

I get the FireFox message:

  A webpage is slowing down your browser. What would you like to do? Stop it. Wait.

If I select wait in hangs indefinitely but if I select stop I can see the output though I have to scan through the source-code. I can use other variables kpr($row) works for example.

I had similar results in Chrome.

How do I troubleshoot this?

Instead of using kpr or devel or the like, switch to using a debugger like xdebug. Sometimes these arrays are so large that simply rendering them in the browser can crash it. This happened to me all the time with Drupal 8 and kint.


Update role with hook user update i'm updating role using hook user update like this :

function my_module_user_update(&$edit, $account, $category) {
  //print_r($account->field_my_field['und'][0]['value']);exit;
  if($account->field_my_field['und'][0]['value'] == 1 ) {
    $uid = $account->uid;
    $role_name = 'Spanish';
    if ($role = user_role_load_by_name($role_name)) {
      user_multiple_role_edit(array($uid), 'add_role', $role->rid);
      //print "1";print_r($role);exit;
    }
  }
  elseif($account->field_my_field['und'][0]['value'] == 0 ) {
    $uid = $account->uid;
    $role_name = 'Spanish';
    if ($role = user_role_load_by_name($role_name)) {
      user_multiple_role_edit(array($uid), 'remove_role', $role->rid);
     //print "2";print_r($role);exit;
    }
  }
}

but it is not working : user's role is not updating
my hook_update_user is correctly called,
i clear cache after all change in script ,
i have syslog and database logging enabled to see the error log, but there is no error

When i doing like this (with just one condition), it's working , i have no problem : user's role is correctly updated accoding the condition

function my_module_user_update(&$edit, $account, $category) {

     if($account->field_my_field['und'][0]['value'] == 1 ) {
       $uid = $account->uid;
       $role_name = 'Spanish';
       if ($role = user_role_load_by_name($role_name)) {
            user_multiple_role_edit(array($uid), 'add_role', $role->rid);
          //print "1";print_r($role);exit;
       }
    }

}

any ideas ?

hook_user_update : Modules may use this hook to update their user data in a custom storage after a user account has been updated.

So that hook is call only when you edit the user account. other things is disable you module which implement this hook.

Morever if you want to edit the role every time when user is created/edited use hook_user_presave.


Filter category taxonomy with tabs i have a node which is of content type "Album", they all have categories defined by terms , and i want the user to be able to choose which category he want to filter by but with tabs instead of a dropdown list.

Cant find anything on the internet so this is my last hope.

Thank you.

Have a look at the quicktabs module. You could use it to embed views in each tab, based on your required filter options there. For example, you can pass a contextual filter option to the quicktab for a single view display to show that content only.

Alternatively, the better_exposed_filters module may provide some options for you, such as a list of links, instead of a select box.


How to select Google Web Fonts (via @font-your-face) from drop down in SWeaver UI? I am using the SWeaver module for "in-situ" editing of the (CSS) styles of elements on pages i.e. by "in-situ" I mean within Drupal style changes (instead of raw editing the theme files CSS via FTP).

Sweaver provides the means to change the font of the text on a page via it's pop up user interface panel that resides at the base of the page.

I am trying to get the Google Web Fonts listed in the drop down menu of available fonts but this does not show. Apparently, Sweaver provides support for various web font foundries including Google Web Fonts via @font-your-face. So I've gone into the Admin/Configuration for @font-your-face and enabled Google Web Fonts and enables the fonts I want but they don't appear in the Sweaver drop down list.

Can someone supply a step-by-step guide to getting Google Web Fonts to appear in the drop down list of fonts in Sweaver

References:

http://drupal.org/project/sweaver
http://www.google.com/webfonts

There should be a solution in the issue queue for SWeaver; several other users have reported similar problems. 2 things to try would be to clear the cache and to install the latest development version.

http://drupal.org/project/issues/sweaver?text=%40font-your-face&status=All


How to use an image with Responsive Image style as a background? We have a need to use the Responsive Image module. The key is that we want to be able to use the image (field_image) field with Responsive Image styles as a background and put the node's title on top of them.

How can we achieve this?

We have tried the following but this only fetches the original photo in a twig template. In other words, when i use Chrome Dev tools to see if it fetched the other images as part of the Responsive Image style settings, it does not fetch them.

 {# title goes here #}

Sample image:

Currently we are using the out of the box Responsive Image twig template

{% if output_image_tag %}
  {{ img_element }}
{% else %}
  <picture>
    {% if sources %}
      {#
      Internet Explorer 9 doesn't recognise source elements that are wrapped in
      picture tags. See http://scottjehl.github.io/picturefill/#ie9
      #}

      {% for source_attributes in sources %}
        <source{{ source_attributes }}/>
      {% endfor %}

    {% endif %}
    {# The controlling image, with the fallback image in srcset. #}
    {{ img_element }}
  </picture>
{% endif %}

What you're trying isn't going to work on a background image. You'd need to do this yourself with javascript. How i've done it previously is added data attributes to the div for each breakpoint e.g.

<div data-mobile-image="mobilestylename/aaa.jpg" data-desktop-image="desktopstylename/aaa.jpg">

Then in javscript use matchmedia or a body class if its already being added by your theme to know which breakpoint you are in and then do

var mobile_image = $('.mydiv').data('mobile-image');
$('.mydiv').css('background-image',mobile_image);


'Flags: Node flag relationship' - Search Api - Solr - Views Flag - 7.x-3.0-alpha4
Search API - 7.x-1.3
Solr search - 7.x-1.0-rc2+13-dev
Apache Solr - 3.5

I have Flag 3.x working fine in my Solr Views.  I am able to flag/unflag correctly.  Flag comes with a default 'My Bookmarks' view, that shows the current user what they have flagged at the moment.  I basically took that view and recreated it using Solr Views.  But I am unable to find the Flags: Node flag relationship to only Include only flagged content by Current User.  I believe I am just missing something that is already there, because Flag 3 now uses entities, and relationships are solved for the most part.  If someone could shed some light on this so I don't end up writing unnecessary code, I would appreciate it.

Forgot the close this a long time ago.  Anyway, I wrote a custom module for solr to index some extra data, and a views handler to do what I needed.


How to stop hook_menu item being called I have a function like:

function MYMODULE_menu() {
  $items['cars'] = array(
    'title' => 'Cars',
    'page callback' => 'section_index',
    'page arguments' => array("cars"),
    'access arguments' => array('access content'),
    'file' => 'pages/section.inc',
    'type' => MENU_CALLBACK,
  );
}

It works fine. Going to cars calls this page. I have a load of node pages like cars/ford and cars/volvo and they get called. However. If you go to cars/volvvvo (for example), it calls the "cars". No 404 is triggered etc.

This also seems to mean that the breadcrumb is glitchy for other pages called by hook_menu which have cars in the path, e.g.

 $items['cars/help'] = array(
    'title' => 'Cars Help',
    'page callback' => 'cars_help',
    'access arguments' => array('access content'),
    'file' => 'pages/help.inc',
    'type' => MENU_CALLBACK,
  );

Has a mangled breadcrumb with additional paths to "cars" in it.

Am I missing something? Is there a way to stop additional arguments being just silently pased through via hook_menu?

No, you can't, see the following question/answer: https://drupal.stackexchange.com/a/33493/31

If you only want to allow certain arguments, you need to validate the argument and return MENU_NOT_FOUND. Or you can use a named argument, e.g. cars/%brand, which will automatically call the brand_load() function, pass the value of the parameter to it and if that function returns FALSE, then it's automatically returned as 404. This is used for node/%node, user/%user and so on.


How to add an existing variation to a product How to add an existing variation to a product?
When I create a product the form forces me to create a new variation, but I also want to add an existing one to the same product.

Turns out I know what you're talking about Nikolaos, and you're in luck! There's a checkbox!

Here's an animated gif that walks you through the steps that I've outlined below:

Navigate to your Content Types
Manage Fields on your Product Display (you may have more than one of these)
Locate the Product Reference or Product Variations Field, click "Edit"
Scroll to the middle and locate the checkbox "Allow users to add existing variations"
...
Profit!


Search API view doesn't display placed block Using Drupal 8.6 here and going mad with this:

I installed Search API module that has Database Search and Database Search Default included.

I can't install Database Search Default for the following reason "Content type article not found. Database Search Defaults module could not be installed.

Content type page not found. Database Search Defaults module could not be installed.".

I don't know what content type article or content type page the message is referring to

Another strange thing that i noticed is that i am not able to preview fulltext with "expose filter to visitiors" on my view
and also i can't see the block in my page tho i place it on block layout.

Can someone please tell me how do i display the block in the block layout?

Thank you for reading,

Database Search Default module expects the page and article content types that exist with the Standard Drupal install. You should be able to recreate these content types (and then later delete them) if you want to install that module. You should create Page|page, Article|article and keep both with the default body field. I think that'll be enough to let you install the Database Search Default module and see the configuration. You'll probably want to remove the configuration for page and article from the search configuration before you delete the content types.

If you don't choose to expose your form in block than you cannot place the form as a block on a page. If you're search results view is a block then I believe choosing to expose the form as a block will not work at all. If you want to expose the view as a block, you'll want to be sure that "Exposed form in block: No." Alternatively, if you're view is a page and you want your form to be a block, "Exposed form in block: Yes" and make sure Ajax is not enabled. (Afaik, Exposed form in block and ajax are not compatible at this time.


Why is this code to programmatically create a content type failing? <?php

            function news_article_install() {

                // Define node type
                $news_article = array(
                    'type' => 'news_article',
                    'name' => 'News Article',
                    'base' => 'node_content',
                    'description' => 'A news article content type',
                    'body_label' => 'Article Text',
                    'custom' => 1,
                    'title' =>  1,
                    'title_label'   =>  'Headline'
                );

                // Save content type
                $news_article = node_type_set_defaults($news_article);
                node_type_save($news_article);
                node_add_body_field($news_article);
            }

?>

Edit: I've simplified the function as much as possible, still having errors. The errors now are...

Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).

You have node_type_save and node_add_body_field in the wrong order. You can always steal ideas from http://api.drupal.org/api/drupal/profiles--standard--standard.install/function/standard_install/7


Commerce- Is it possible to hide the radio button on payment select with only one payment type? I just set up Drupal Commerce (not Kickstart) and am using the Commerce PayPal module to allow customers to pay for their orders.  This is the only payment method available; however, there is a radio button displayed next to PayPal, as if there was another option that could be selected (although there is not).

How can I hide this option?  I assume there is an option in the UI somewhere that I missed, because it is not standard practice to show a radio button when no choice is in fact possible.

It looks like this:

Here is a more elegant way:

function yourmodulename_form_commerce_checkout_form_review_alter(&$form, &$form_state, $form_id)
{
   $form['commerce_payment']['#access'] = FALSE;
}

I'm not confident if the payment selector might be put into another form in checkout settings. Then it might be part of the commerce_checkout_form_checkout_alter instead. Then do this:

function yourmodulename_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id)
{
    $form['commerce_payment']['#access'] = FALSE;
}


Display the flag link only for the node author I'm trying to display the flag link only for the node author, and I'm using the following code:

global $user;
if ($node->uid == $user->uid) {
  //print your flag
}

The link doesn't appear.

Do you have any idea on what is causing this?

You may use hook_flag_access(), as in the following code.

 function crystal_qa_flag_access($flag, $entity_id, $action, $account) {
   // Only the author of the question has right to use flag "Accepeted" on answers.
   if (($flag->name == 'accepted') && ($flag->content_type == 'node')  && ($node = node_load($entity_id))) {
     if ($node->type=='answer') {
       // The content type machine name must be answer.
       $question_nid = $node->field_answer['und']['0']['target_id'];
       $question = node_load($question_nid);
       return ($question->uid == $account->uid);
     }
   }
 }


Node's cache isn't automatically cleared on update (intermittent problem) Occasionally, about 1 out of 5 times, a node's cache isn't cleared when it is updated. Even going to view the revision that the update created or editing the node doesn't show the changes. Minimum cache lifetime is set to 1 minute but even after waiting for a minute and running cron it isn't automatically cleared.

It seems that this problem happens more during the site's busier times and we haven't been able to reproduce the issue in our development environment (which typically only has 1 user on it at a time). The cache tables are all InnoDB so I'm told this means we shouldn't need to worry about locking.

A similar problem with the chosen answer saying that this is just an issue of properly setting the minimum cache lifetime. But, I found this Drupal bug that implies that on node updates the cache should be cleared regardless of that setting. Though, its status is still "needs work" which maybe means a solution was never implemented and this is still the case.

Update

Building off a patch in the bug and using hook_node_update I tried the following

function MYMODULE_node_update($node)
{
   // Forcibly wipe this node's page view from the cache because, if a
   // minimum cache lifetime is in effect, cache_clear_all() will not
   // clear any page cache entries younger than that minimum.
   //
   // Page cache cids are absolute URLs.  url() in absolute-mode will
   // get the aliased path if there is one, and we also wipe the
   // absolute version of the node/nid URL just in case.
   // Copied from http://drupal.org/node/256416#comment-838118
   global $base_url;
   cache_clear_all( url('node/'.$node->nid, array('absolute' => true))
                  , 'cache_page' );
   cache_clear_all($base_url .'/node/'. $node->nid, 'cache_page');
}

This should work around the minimum cache limit and only clear the cache for that node. Unfortunately, this did not work.

Update 2

After digging further I discovered that running cache_clear_all('field:node:<nid>', 'cache_field') (where <nid> is replaced with the relevant node ID) cleared the correct cache when the problem cropped up. I tried putting this in a MYMODULE_node_update() hook but it did not resolve the issue.

In discovering this and following the path of the code I also discovered that the APC module is taking care of the caching and none of this is being stored in the database as I originally thought.

Knowing that the caching is being handled by APC and considering the intermittent nature of the issue it brings me back to a possible locking issue with APC. Would that even make sense? Preliminary searches have not revealed anything.

I updated the APC module to 7.X-1.0-beta4 from beta3 and it seems to have fixed the problem. At least the client has not reported any further issues for several days now and we have not been able to reproduce the issue in our somewhat limited testing.

I noticed nothing in the change lot between beta3 and beta4 that would suggest a fix to this issue. I'm not convinced that this is what fixed it, but I have no other clues.


FullCalendar links open a new tab, don't want that I have D7 with FullCalendar (7.x-2.0) installed. When viewing a month view and clicking on an event, the event opens in a whole new browser tab (no matter what browser I'm using).

I don't want that, I want to stay in the same tab.  I read at http://arshaw.com/fullcalendar/docs/mouse/eventClick/ that I could change the "self" value from False to True.  See below,I did that in fullcalendar.fullcalendar.js and now the link opens itself in the existing tab AND a new tab both.

How do I get this to work the way I want?   Thank in advance for any help you can give me.

var options = {
  eventClick: function (calEvent, jsEvent, view) {
    if (settings.sameWindow) {
      window.open(calEvent.url, '_self');
    }
    else {
      window.open(calEvent.url);
    }
    return false;

In view edit, click on FullCalendar settings under Layout. There is an option to open events in new window.


What's the alternative for my failing PHP code about block visibility based on user? I would like to remove certain blocks, so that admin can not see them.
In block visibility settings - in pages tab, I try to put followng php code but with no effect. (In user tab there is no php field to put code.)

<?php
if(arg(0) == 'administrator' )
return true;
else
return false
?>

What I am doing wrong?

EDIT: On my other D6 site I use argument:

 user_access('access administration pages')

but on D7 site it does not work, what can be another way of doing it?

You could perhaps just set the "Roles" options under the block visibility settings.

Alternatively, something like:

global $user;
return in_array('administrator', $user->roles) ? FALSE : TRUE;


Form block: how to choose which fields are being displayed? I created a form block using the form block module to allow users to post a certain content type and fill out the form without leaving the page. I don't remember how I chose which fields to show. Currently it only shows the title and the submit button but I would like to add another field and change the label of the button. Can I do that with this module and if so, how? Thanks!

I needed to adjust custom field permissions for the field I wanted to show and once I set the field permissions to "public" they showed. The permissions were under edit field in manage display of the content type.

I had originally looked in both permissions and in edit display.


how to customize user profile page I want to customize user profile page as per my own way.
I have created one file named as page--user.tpl.php, but after making changes in this file during user logged in, the changes reflects on sign up(register page) without logged in.
But i only wants to change the look and feel of individual user's page.

Please help me.

Thanks

You've simply used the wrong template. page--user.tpl.php affects "user pages" like, as you've discovered, the user login.

The template you want to create and modify is user-profile.tpl.php https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7


How can I pass a query string from the url to a hidden user form field? I'm building a conference registration site in Drupal 8. I've set up a register link for a custom user role that includes a query string (/register?reg-id=custom-id) and would like to pass this value (custom-id) back to a hidden field when my form is displayed to my user so that I can have users that are of the same role but with varying reg-id depending what they signed up for.

Ideally I would like to set it up using the user fields available under account settings and not through the template settings as more than one template may be used in the future (on a per conference basis). Alternatively a module might work, but I can't seem to find a starting point for this in Drupal 8. As a side note the custom-id is generated from a taxonomy term field on the referring page - just in case there an option to feed the form the variable another way.

I have looked at the following, and numerous others, but they don't quite meet the requirements for my use case:
How to retrieve GET parameter in Twig template
https://www.drupal.org/project/userreference_url (seems ideal but not ported to D8)
How do I pass a value from the url to a custom field in the registration form? (for D7)

Any assistance would be greatly appreciated.

You may be able to do a hook_form_alter() and call \Drupal::request()->query->all() (or \Drupal::request()->query->get('reg-id')) to access the query parameters to pass it to your hidden form field.

See https://api.drupal.org/api/drupal/vendor%21symfony%21http-foundation%21Request.php/property/Request%3A%3Aquery/8.2.x and https://www.drupal.org/node/2150267.

For example:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, FormStateInterface $form_state) {
  // Get the query parameter with 'reg-id' if it exists.
  if ($custom_id = \Drupal::request()->query->get('reg-id')) {
    $form['hidden_field'] = // Do whatever you need here;
  }
}


Is it possible to add form elements to the existing fields with Field API? Is it possible solved with field api this task?
I need to add new elements to an existing field.
For example there is a field image. I create a widget and add a checkbox

/**
 * Implements hook_field_widget_form().
 */
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $elements = image_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);
  foreach (element_children($elements) as $delta) {

    $elements[$delta]['#process'][] = 'custom_widget_process';

  }
  return $elements;

function custom_widget_process($element, &$form_state, $form) {
  $element['myelement'] = array(
    '#type' => 'checkbox',
    '#title' => t('My checkbox.'),
  );
  return $element;
}

How do I save the value of the checkbox? (If I have a table for it)

Can I add additional column into an existing image field scheme?
(hook_field_schema_alter - not exist)

File Entity module allows you to add extra fields to file fields.

  File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters.


How to unpublish content when form submitted and notify a user by eMail? In my Drupal 7 site I have content type Job.

Recruiters post information about open positions. Registered users can apply for any position by flagging node using the Flag module. I have built custom form for recruiters where they can manage applications. With this form recruiters can review profile and select candidate for position by submitting the form.

I want to hide/unpublish content when form is submitted and notify user via email that his application was confirmed. How can this be done programmatically?

Also I'm using Rules. If these actions can be implemented via Rules, how can I create event and conditions to perform actions against specific user id and node id?

The Rules module is, for sure, your best bet for addrerssing this (therefor +1 for this question already ...).

Can you further enhance (edit) your question to explain what you have tried already using Rules? And what worked, or failed, and what the remaining questions are while using the Rules module? I.e.:

which events?
which conditions?
which actions?

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.


Features - keeping Git up to date when changing features on production I have a Drupal 7 site with a UAT version and Production version. Most of the features on production have been overridden. I want to keep my repository up to date in case anything happens to my database I can redeploy with the most current (overridden) changes.

My question is: what is the best way to go about updating my Git repo without a lot of unnecessary work?

My thinking is that I could just download the features off of production, overwrite the features on my local and commit / deploy to remove the overrides. Is this a viable strategy? Is there any risk involved with this strategy?

I appreciate any help / nudge in the right direction.

Great question. I work in a Drupal agency where we see this all the time.

Imaging this scenario:

Locally you've made some amends to a site that overrides a bunch of features. Locally you can run feature updates, placing the changes from the database into the code and then get ready to push live. But when you go to push live, you see there are feature overrides existing on the live site. There can be feature overrides for a number of reasons but the most often one is fields and blocks moving. If there are additions in your code they will be ok, but if you need to revert one of the features to say, move a field, then it gets a bit tricky.

My personal solution to this is to download the latest live database and run feature updates from that database locally, then merge the code changes. Then when you push your code you will have your changes and your live sites overrides in the code.

This isn't perfect, but it's workable.

Why not just run feature updates on the live server and pull that code change locally for a merge? Most, usually all, servers don't allow write permissions in live environments. So cloning the db locally is often necessary for this.

It's also worth trying to structure you features well, it's an art not a science! I usually leave ALL blocks out of features as they always get overridden. Also don't make a feature for all content types or all views as that will easily be overridden. Yes you can make too many feature, this is where your experience will come into play and it gets easier the more you do it.

Our senior dev also hook_update_N which may be worth looking into.


Create a node type that acts like a PHP page? Drupal 7.24, fresh installation

I'm fairly new to Drupal and I'm trying to figure out if it's possible to create a node type that acts like a PHP page. I have a code library that needs certain files required once in a node type that displays output.

I've tried using Full HTML and also created a new text format that had all vanilla Drupal options unchecked and the PHP snippets do not function.

I'm sure I'm mixing up terms and I hope you understand what I'm going for, like I said I'm fairly new. Do I need to look for a different text format?

Thanks for your time, and Happy New Year!

First, you will need to enable the "PHP filter" core module in admin/modules.  I think you did.

Then, you'll need to configure the newly added text format in admin/config/content/formats and assign some role to that text format.  Note that you can also do this from admin/people/permissions.

Useless to say you'll need to be very conservative here and only allow this text format to - very - trusted users (roles).

Finally, in your node content, select the "PHP code" text format and type your code (including  tags).


After setting $base_url, I can only access the front page I have Drupal installed in a subdirectory of public_html on BlueHost.

It looks like this: /www/drupal7/mywebsite.

I want to run the site out of the mywebsite subdirectory instead of www.  However, I want the URL to appear to be http://mywebsite.com.

Here is the suggested .htaccess configuration from BlueHost.  This is the .htaccess for the www/ directory; I am using the default Drupal 7 .htaccess in Drupal's subdirectory.

# BlueHost.com
# .htaccess main domain to subdirectory redirect
# Do not change this line.
RewriteEngine on
# Change example.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/subdirectory/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /subdirectory/$1
# Change example.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ subdirectory/index.html [L]

This successfully allows me to use Drupal from the subdirectory, but the URLs look like this:

http://www.mywebsite.com/drupal7/mywebsite/PAGE

But I want it to look like this:

http://www.mywebsite.com/PAGE

This post on Drupal.org suggests that the $base_url must be set in default/settings.php.  I set the $base_url to "http://mywebsite.com"; however, when I do this, whatever link I click, I am redirected to the front page.

Is there an additional step?  What am I missing?

It sounds like the answer from Oleg Ivanov would work. However, if you want to tackle this with a .htaccess approach, the following works for me. Find and replace SUBDIRECTORY with your subdirectory.

Amend your Drupal's .htaccess with the following:

RewriteBase /

# homepage redirect
RewriteRule ^$ /SUBDIRECTORY/index.php?q= [L]

# if directory or regular file...
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} =/favicon.ico
# stop here
RewriteRule ^ - [L]

# if a regular file in SUBDIRECTORY directory
RewriteCond %{DOCUMENT_ROOT}/SUBDIRECTORY/%{REQUEST_URI} -f
RewriteRule .* SUBDIRECTORY/$0 [L]

# Redirect everything to /SUBDIRECTORY
RewriteRule .* /SUBDIRECTORY/index.php?q=$0 [QSA]


Is there any way to reset a node's properties? I would like to know if there is a way to reset a node's properties/fields?For example node's body, title,attachments, so as to re write the contents of the page.

In your theme folder you can override the default output using custom template files.
Let's say you want to modify the output of a standard 'Page' (the machine name for this content type is 'page' -- you can check it in /?q=admin/structure/types).
Go to your theme folder (under /sites/all/themes) and add/modify 'node--page.tpl.php' file.
A standard node template file will have something like:

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>

This piece of code is used to show the title of the current content. You can delete (or comment) the entire code and your title won't appear when you display this page.
To hide the entire content (including custom fields attached to this content type) simply comment (or delete) this line:

print render($content);

After that, you can add your custom code to display anything in place of the original title (or content) for this page.

You can find an extensive tutorial on working with custom themes here: Theming Guide


Check if user can edit node with certain ID I need to know a function or a way to find out if a user can edit a certain node.

For example I have the nid 200 and the user foo has logged in, I want to check if he is able to edit node/200.

Thanks

You can use node_access to do this:

$node = node_load(123);
$account = user_load(456);

if (node_access("update", $node, $account) === TRUE) {
  do_something_awesome();
}

If you look at the source for node_access, you will see that the $node argument can also be a $nid.  This is how the path for the edit pages get checked (see the 'node/%node/edit' entry in node_menu).


How to override a theme function? I'm using LoginToboggan as my login page, and on the login form, it has: "You are not logged in." I want to be able to edit this text, and the admin interface doesn't give an option to do so.

Searching around, I see that this is set in the LoginToboggan module in a theme function:

function theme_lt_unified_login_page($variables) {
...
$output .= '
' . t('You are not logged in.') . '
';
...
}

So I can't edit the module directly, nor would I wish to "patch" it. I see that theme_lt_unified_login_page is called by:

function logintoboggan_unified_login_form($active_form = 'login') {
...
$output = theme('lt_unified_login_page', $variables);
...
}

I don't really understand what hook I would use to intercept and override / edit just this text? It doesn't appear in the $form object.

The quickest way might be/would be to copy...

/**
 * Theme function for unified login page.
 *
 * @ingroup themable
 */
function theme_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '
';

  // Create the initial message and links that people can click on.
  $output .= '
' . t('You are not logged in.') . '
';
  $output .= '
';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '
';

  // Add the login and registration forms in.
  $output .= '
' . $login_form . '
';
  $output .= '
' . $register_form . '
';

  $output .= '
';

  return $output;
}

to your theme's template.php file and rename it...

/**
 * Theme function for unified login page.
 *
 * @ingroup themable
 */
function YOURTHEME_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '
';

  // Create the initial message and links that people can click on.
  $output .= '
' . t('PLACE YOUR CUSTOM MESSAGE HERE.') . '
';
  $output .= '
';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '
';

  // Add the login and registration forms in.
  $output .= '
' . $login_form . '
';
  $output .= '
' . $register_form . '
';

  $output .= '
';

  return $output;
}

...along with whatever you wanted that login-message to be.  Clear caches/theme registry and you should be on your way.

ADDITION:

This drupal fu works because, instead of calling theme_lt_unified_login_page() directly, it does it like this:

$output = theme('lt_unified_login_page', $variables);

and it is the theme() function that does the magic in that when you build the theme registry, it will discover that there is a YOURTHEME_lt_unified_login_page() function out there, and will call that as an override to the theme_lt_unified_login_page() one that logintoboggan provides.

(Note that the first argument doesn't start with theme_ or YOURTHEME_, one of these are prepended by the theme system as described above.)


How to change transition to fade on Boostrap Carousel module? I have a boostrap carrousel view that works fine, but the slide show only has one option, tansition in milliseconds.

How can I change the transition to fade instead of slide? I've looked at the css code but it keeps moving, so hard to know what to change, additionally, it seems to be getting the css from boostrap.min.css ...

Site is at:

www.xuzo.com
carousel on home page

you could do that with CSS transitions so it can be done easily without any Javascript.

The CSS:

.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}

I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.

Very smooth.


Drupal7 : Error in install drupal in localhost When install drupal 7 in my localhost its show this error:-

http://im36.gulfup.com/QFe3q.png

why its not show me database type [ MySql ]

when install in my site and install good and return install to localhost show my this error

 Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in D:\AppServ\www\drupal\includes\database\mysql\database.inc on line 46

You need the php's PDO and mysql extensions installed on your system in order for Drupal to use MySql data storage. One or both of them are apparently missing, and Drupal defaults to Sqlite, which is a simple database system and only needs a writable file to work. Please refer to Drupal's system requirements page for further info.


Problem upgrading from 7.22 I'm trying to update from Drupal 7.22 to the current (7.26) version. I keep getting the following error on the Configuration page after updating.

Fatal error: Class 'DatabaseTasks_mysql' not found in /server/path/stuff/here/domainname.com/html/modules/system/system.install on line 188

I have tried upgrading incrementally 7.22 -> 7.23
I've tried upgrading directly to 7.26
I've tried uploading files via FTP, following the standard upgrade instructions, and I've tried upgrading with drush. I always get the same error. (though the line number does change depending on which version I'm updating to.)

Does anyone have any suggestions?

I was experiencing this problem on two different test servers (different Debian and PHP versions) using data imported from our production server. All of the cache tables were emptied first, and I did try reinstalling Drupal using various methods. Couldn't find a solution anywhere.

What finally fixed it for me was emptying the registry and registry_file tables, then running update.php.  (Update didn't find any database changes, but it reset the registry - clearing the cache may have worked as well.)

Hope this helps someone - this problem was driving me crazy for two days.


Backup table from custom module using backup and migrate I have a module that allows a user to add to a custom table in bulk via a custom form. But before they do so I'd like to backup that table to the private folder. Does anyone know if it is possible to create a new profile in the Backup and Migrate module and save a table using code in a custom module?

So what I'd like to do is programmatically create a Backup and Migrate profile in my modules .install file. Then in my custom form submit function, trigger the backup using that profile.

I've had a look at the Backup and Migrate code and I've come up with a solution, one that works for me at least.

I've created a function that gets the default profile data, then alters that to save only the tables I want. It seems to work well but if anyone can see any possible problems with this solution please do let me know.

The function:

<?php
/**
 * @param $tables
 *  An array of table names that will be backed up.
 * @param $filename
 *  Text prepended to the date when naming the backup file.
 */
function _MYMODULE_backup_custom_tables($tables, $filename = 'custom-backup') {
  module_load_include('module', 'backup_migrate');

  // get default profile settings
  backup_migrate_include('files', 'profiles');
  $settings = _backup_migrate_profile_saved_default_profile();

  // set the destination to our private folder
  $settings->destination_id = 'manual';
  $settings->source_id = 'db';

  // get a list of all tables from the database
  $schema = drupal_get_schema();
  ksort($schema);
  $drupal_tables = array();
  foreach ($schema as $table => $table_schema) {
    $drupal_tables[$table] = $table;
  }

  // remove from the database table list the tables we would like to save
  foreach ($tables as $table) {
    unset($drupal_tables[$table]);
  }

  // alter default filters so only the tables we want will be backed up
  $settings->filters['destinations']['db']['nodata_tables'] = array();
  $settings->filters['destinations']['db']['exclude_tables'] = $drupal_tables;

  // change the filename so we can identify the backup in the directory
  $settings->filename = $filename;

  // backup tables
  backup_migrate_perform_backup($settings);
}
?>

The function can then be used like this:

<?php
// the names of the tables we want to save
$tables = array(
  'custom_table_one',
  'custom_table_two',
);

// the text to use when naming the backup file
$filename = 'my-custom-backup';

_MYMODULE_backup_custom_tables($tables, $filename);
?>


How to get node url/address from entity reference (content type)? Is there a way to fetch or print the node url/address from a entity reference to my twig template.

I have already tried {{ related_links.entity.uri }}, {{ related_links.entity.url }} or {{ related_links.entity.path }} but nothing seems to work

{% for related_links in node.field_pbn_additional_items %}

{{ related_links.entity.label }}

{% endfor %}

No need to add the <a> tags, because Drupal will automatically create the link.

So just simply do <h2>{{ related_links.entity.toLink }}</h2>

You don't even need the label with .toLink() because Drupal will automatically grab it when generating the link.

The above is suppose to work, but I get an error

  Twig_Sandbox_SecurityError: Calling "toUrl" method on a
  "Drupal\node\Entity\Node" object is not allowed. in
  Drupal\Core\Template\TwigSandboxPolicy->checkMethodAllowed() (line 105
  of
  /home/ubuntu/workspace/drupal-8.5.3/core/themes/bartik/templates/node.html.twig).

There is an issue about this on drupal.org Add $entity->toUrl() and $entity->toLink() methods to whitelist in Twig sandbox policy applying the patch in #30 solved the issue.


Drupal7+Omega Theme: How to narrow the 20px gutter between columns in 960 grid? Is it possible to alter the allmighty 20px gutter in 960px grid especially when using with Drupal 7 Omega subtheme?

If you search Google for "Drupal Omega custom grid", you find links like:

Creating and Setting up a Custom Grid for Omega 3.x
How to define my own 960 grid ?

Hope that helps.


New VBO bulk operation button not get translated VBO button not translated issue.

I have created a new VBO bulk operation using rules component.

This is the button:

In Rules I have written the translation for this rule, in the translate tab of the rule.

But the button in the view doesn't display translated.
:(

Too I tried to override a label in the view for this button, and translate this label with the translate view option, translating this field.

But the button doesn't translate too.

How could I translate my button?

Sharing a link below:-

http://www.drupalcontrib.org/api/drupal/contributions!views_bulk_operations!views_bulk_operations.api.php/function/hook_views_bulk_operations_form_alter/7

Here a function
function hook_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
}
We can use this function and here we can actually do custom code for this particular action and set the label accordingly.

Would be able to answer more appropriately if you share some more details with your question that what you basically did.


Passing multiple array to drupal_json_output() is not giving correct output in jquery ajax Passing multiple array to drupal_json_output() is not giving correct output in jquery ajax.

I am using a menu_callback function and returning a multiple array like

function test_callback() {
   for($i = 0; $i < 10; $i++) {
    $arr = array('message' => 'test'.$i, 'data' => 'data'.$i);
    $arrs[] = $arr;
   }
 drupal_json_output($arrs);
}

Now, in the jquery, I wrote like this,

$.ajax({
url: the above url,
dataType: 'json',
success: function(data) {
$(data).each(function(key,val) {
  console.log(val.message);
});
})
});

The output in the console is giving an object.

I tried to use $.each for the val also, but the output it is returning as undefined. I tried in a lot of ways using $.get etc. but not getting the output. Can anyone help me here??

To setup a service which returns a json formatted data, you should set the delivery callback to drupal_json_output. This will only output the service data and not all the HTML defined in your theme.

For example

function YOURMODULE_menu()
{
    $items = array();

    $items['service/ajax'] = array(
        'title' => t('Ajax service'),
        'page callback' => 'YOURMODULE_ajax',
        'delivery callback' => 'drupal_json_output',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function YOURMODULE_ajax()
{
    for($i = 0; $i < 10; $i++) {
        $arr = array('message' => 'test'.$i, 'data' => 'data'.$i);
        $arrs[] = $arr;
    }

    return $arrs;
}


Drupal commerce taxes and ip location Im using smartip to show taxes to users by country, but I have a problem:

If a user is browsing the web with a USA IP but the order address is France?

So I have to use two conditions when calculating product price:

One user IP is in USA
And order address comparison is USA.

This doesnt work, I suppose when calculating product price the order is not complete, so i dont know how solve it.

The order's billing profile will always be authoritative on an order. If you want to be able to provide tax/shipping estimates, you have two options:

Use something like Commerce Cart Estimate to provide an estimate by request to a customer. This doesn't put it on the order, but simply provides the estimates in a block.
Take the result of the SmartIP lookup and stick it in the billing address on the order. That way when the customer sets the actual billing address, it will just override it and it will stick. You should be able to swing this with the Smart IP module since it has a rules integration. Just tack it onto the order if it doesn't already have a billing address. Then, let commerce's rules do the rest and output the order's values.

Something that isn't out of the box would be to ask the user: Pop up a box or a block somewhere on the page that asks them to verify their country/postal code.


How to add “Download file” link in Drupal 7 files attachment when chosen table formatter By default Drupal 7 output attached files: file name and size of attachment
I heed to add an additional column with Download link to every attached file.

In my template.php i have added:

// Override attachments files in case of use table formatter
function bkisk_file_formatter_table($variables) {
$header = array(t('Attachment'), t('Download'), t('Size')); // added Download column
$rows = array();
    foreach ($variables['items'] as $delta => $item) {
        $rows[] = array(
            theme('file_link', array('file' => (object) $item)),
            theme('file_link', array('file' => (object) $item)), // ???
            format_size($item['filesize']),
        );
    }
    return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}

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

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

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

    // Use the description as the link text if available.
    if (empty($file->description)) {
        $link_text = $file->filename;
    }
    else {
        $link_text = $file->description;
        $options['attributes']['title'] = 'откроется в новой вкладке';
        $options['attributes']['target'] = '_blank'; // add _blank param
    }
    return '' . $icon . ' ' . l($link_text, $url, $options) . '';
}

i have http://i.stack.imgur.com/W76kW.png

i need to do like this http://i.stack.imgur.com/cmKMj.png

ill be very appreciated for your help!

use File Force Download module to add download functionality to your site. It has field formatter, views integration, good api and etc..

If you want to create a download link programmatically then you can generate download link such way:

l('Linktext', file_force_create_url($image['filepath']), array('query' => array('download' => '1'))).


Content access based on on the field reference I want to make a content access ( node ) based on it's user reference field .
ie: While i'm creating a node that have a user reference field, i want that it will be accessible just for the users that i mentionned before .
Is there any module or a way to do that ?
Thank you very much

There are plenty of node access modules available for Drupal but I honestly am not sure if there is one that would do exactly what you are looking for.

Either way, I would probably avoid a specific node access module for this and use Panels - read the Panels module - to do this since its makes this scenario easy to accomplish.

You can easily override Drupal's standard Node template and create an invariant that matches both the content/node type you want to apply this rule on and add a condition that the logged in user's ID matches the user id in the reference field defined by the node.


How do I create a "More like this" block? Is there a way to create a "More like this" block with the Views, and the Search API Solr modules?
I saw this, but it doesn't work.

Here is the recipe for search_api_solr as per the OP. Note: both apachesolr and search_api_solr leverage Solr's builtin more like this feature. It is, therefore, not available to normal search.

Enable some modules: search_api, search_api_solr, search_api_views
Create a Search server of the Solr class.
Create a Search index (or use the Default node index) and point your Solr search engine at it.
Create a new view on your search index NOT on Search index.
eg:

Show *Default node index* sorted by *unsorted*
Continue and edit.
Reveal Advanced and Add a Contextual filter.
Filter on Search or scroll down to find Search: More like this.
Under When the filter is not available select Provide default argument: Content ID from URL.
Configure by selecting the Fields for Similarity that you want to determine likeness on.

http://drupal.org/node/1250304#comment-4870278


Page not found - Even after I implemented Hook_Menu() I have implemented hook_menu() & called a function, but if I am trying to browse the page URL it's giving me "Page not found" error...

This is the code --

function user_type_registration_menu(){
  $items = array();
    $items['paypal/payment/ipn'] = array(
          'title' => t('Paypal Payment IPN'),
          'description' => t('Paypal Payment IPN'),
          'type' => MENU_CALLBACK,
          'page callback' => 'paypal_payment_paypal_ipn_callback',
          'access callback' => TRUE,
        );
      return $items;
}
function paypal_payment_paypal_ipn_callback(){
  dpm("here");
}

I have cleared the cahche too..so cahche can't be the problem...

With the code you posted you will get a blank page.

If you actually return something from your callback you will get a proper page, with no 404 error.
A menu callback has to actually return something.

For example, this works:

function user_type_registration_menu() {
  $items = array();

  $items['paypal/payment/ipn'] = array(
    'title' => t('Paypal Payment IPN'),
    'description' => t('Paypal Payment IPN'),
    'type' => MENU_CALLBACK,
    'page callback' => 'paypal_payment_paypal_ipn_callback',
    'access callback' => TRUE,
  );

  return $items;
}

function paypal_payment_paypal_ipn_callback() {
  dpm("here");
  return 'test';
}

Also, make sure your module is named "user_type_registration" or else your menu hook will not get picked up.


Why isn't my view title displaying? I have a view, displaying in a block, with a views-view--VIEWNAME--block-1.tpl.php:

    <?php
        print render($title_prefix);
        if ($title): print $title; endif;
        print render($title_suffix);
    ?>

    ...some view content...

Most of the content in this template has been copied straight from the template given by theme => information => display template in the view settings.

This displays (with some whitespace differences):

BLOCK TITLE

    ...some view content...

Why is the view not displaying the view title inside the
? The title is definitely set for the view.

I've put the following code in the view template:

print print_r(array_keys(get_defined_vars()), 1);

And the result (including "title" at index 30) is:

Array
(
    [0] => template_file
    [1] => variables
    [2] => view
    [3] => view_array
    [4] => theme_hook_suggestion
    [5] => theme_hook_suggestions
    [6] => zebra
    [7] => id
    [8] => directory
    [9] => classes_array
    [10] => attributes_array
    [11] => title_attributes_array
    [12] => content_attributes_array
    [13] => title_prefix
    [14] => title_suffix
    [15] => user
    [16] => db_is_active
    [17] => is_admin
    [18] => logged_in
    [19] => is_front
    [20] => rows
    [21] => css_name
    [22] => name
    [23] => display_id
    [24] => header
    [25] => footer
    [26] => exposed
    [27] => more
    [28] => feed_icon
    [29] => pager
    [30] => title
    [31] => attachment_before
    [32] => attachment_after
    [33] => dom_id
    [34] => classes
    [35] => attributes
    [36] => title_attributes
    [37] => content_attributes
)

Just had the same problem on another site: for some reason the view title ($handler->display->display_options['title'] = 'Blogs';) was coming out in the page.tpl.php template $title, but not in the views-view.tpl.php $title (despite the default template for that page suggesting that it should). Possibly the variable gets undefined after it's used in an "earlier" template? Or maybe the title variable is only set for the view template if the view is being rendered as a block, on the assumption that the page template has already printed the title for the page?

Anyway, the solution is just to do the printing in the page.tpl.php right before rendering the page content (which will likely come from either the node template or a view depending on the page):

<?php print $title; ?>

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

Of course if you're doing this you need to make sure not to print the $title variable out in the node template because if you do that you'll have the title printing twice.


Can I specify the location of a .tpl.php while using preprocess hooks? If I override the template file using the code below, can I specify the location of page-ajax.tpl.php? I wanted to leave page-ajax.tpl.php inside my module's directory rather than to place it inside the current theme's folder.

function my_ajax_preprocess_page(&$vars, $hook)
{
    if (isset($_GET['ajax']) && $_GET['ajax'] == 1)
    {
        $vars['template_file'] = 'page-ajax';
    }
}

It has to be in either the module defining the theme function or the active theme, unless you want to make override in the theme registry.

Drupal provides a hook: hook_theme_registry_alter that allows you to alter the theme registry and thus also where Drupal would look for template files. Messing too much with this tends to make it blow up into your face, as you alter some default Drupal behaviors.


How to insert a View inside other View as the last row of the parent View? I need  to insert a View inside other View as the last row of the parent View.

I know I can create a Attachtment but this will be shown before or after the rows of the parent view. I need it to be inserted as the last row of the parent view

Let's say the parent view lists "basic pages" nodes and the inserted view lists "articles" nodes.

Then the results of what I need would be: 6 rows: the first five rows will be "basic pages" and the last one will an "article".

Is there any way to get this?

Use views_field_view module.
This module help you to embed a view as a field in a view.


Include javascript in node myjavascript.js:

    function initialize() {

        var waStyle = [
            {
                featureType: "all",
                stylers: [
                    { saturation: -100 }
                ]
            }
        ];

        var mysiteMap = new google.maps.StyledMapType(waStyle,{name: "Nuance"});

        var img = new google.maps.MarkerImage("/themes/nuance/img/pin.png");

        var myLatlng = new google.maps.LatLng(41.061833,28.997948);

        var mapOptions = {
            zoom: 16,
            center: myLatlng,
            disableDefaultUI: true,
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'mysite_map'],
            }
        };

        var map = new google.maps.Map(document.getElementById('mainmap'), mapOptions);

        var point = new google.maps.LatLng(41.061833,28.997948);
        var marker = new google.maps.Marker({
            position: point,
            map: map,
            animation: google.maps.Animation.DROP,
            icon: img
        })

        map.mapTypes.set('mysite_map', mysiteMap);
        map.setMapTypeId('mysite_map');
    }

    function loadScript() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
        document.body.appendChild(script);
    }

    window.onload = loadScript;

And include in my node via field. (text format: php code)

<?php include('themes/mytheme/scripts/maps/myjavascript.js'); ?>

But get error.

On site:

 function initialize() { var waStyle = [ { featureType: "all", stylers: [ { saturation: -100 } ]
    ...

What's my problem and how can i fix it?

The Drupal way is to add js on the go is drupal_add_js

drupal_add_js($data = NULL, $options = NULL)

Examples:

  drupal_add_js('misc/collapse.js');
  drupal_add_js('misc/collapse.js', 'file');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

There is a better way to add a library file drupal_add_library

Parameters

$module:
The name of the module that registered the library.

$name:
The name of the library to add.

$every_page:
Set to TRUE if this library is added to every page on the site. Only items
with the every_page flag set to TRUE can participate in aggregation.


How can I change the Apache Solr search URL? How can I change the default Apache Solr URL path from "search/apachesolr_search/term" to something else?

This should work if you place it in settings.php:

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  // Filter to get only the apache solr links with filters so it doesn't launch it for every link of our website
  if ($path == 'search/apachesolr_search/' && strpos($options['query'], 'filters') !== FALSE) {
    $new_path = $path.'?'.urldecode($options['query']);
    // See if we have a url_alias for our new path
    $sql = 'SELECT dst FROM {url_alias} WHERE src="%s"';
    $row = db_result(db_query($sql, $new_path));
    // If there is a dst url_alia, we change the path to it and erase the query
    if ($row) {
      $path = $row;
      $options['query'] = '';
    }
  }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  // See if we have a url_alias for our new path
  $sql = 'SELECT src FROM {url_alias} WHERE dst="%s"';
  $row = db_result(db_query($sql, $path));
  if ($row) {
    // We found a source path
    $parts = preg_split('/[\?\&]/', $row);
    if (count($parts) > 1) {
      $result = array_shift($parts);
      // That's important because on my website, it doesn't work with the / at the end of result
      if ($result[strlen($result) - 1] == '/') {
        $result = substr($result, 0, strlen($result) - 1);
      }
      // Create the $_GET with the filter
      foreach ($parts as $part) {
        list($key, $value) = explode('=', $part);
        $_GET[$key] = $value;
        // Add this because the pager use the $_REQUEST variable to be set
        $_REQUEST[$key] = $value;
      }
    }
  }
}

And then when you create a menu entry, you put the link to apache solr : search/apachesolr_search/?filters=tid:13

And create a url alias for search/apachesolr_search/?filters=tid:13 like products/tv.html

Found via: http://drupal.org/node/783836#comment-4136475


Returning HTML through an ajax-call in Drupal 8 I am trying to grasp the MVC/Symphony integraton of Drupal and am making use of the controllers. My controller has a function named "returnHTML" which is called by a normal XMLHttpRequest. Problem is I do not know how to generate the HTML. I could use a theme, but implementing a theme feels a little bit too complicated for this simple task. I want a HTML-fragment, ergo what you see is what you get, not a complete webpage.

Is there a way to return HTML just specifying where a twig is and have this twig-file injected with data in the "returnHTML"-function immediately? Also is there a recommended class (like Symphonys JsonResponse) which will help with the headers?

Since we are fairly new in the Drupal 8 jungle I'll give some feedback how I fixed this. Be aware this is probably not the best solution.

Using a controller I included this function:

    /**
     * Inspiration page action
     */
    function inspiration(){
        $twig = \Drupal::service('twig');
        $template = $twig->loadTemplate(drupal_get_path('module', 'experimental') . '/templates/inspiration.html.twig');
        echo $template->render([]);
        die;
    }

This works fine, allthough it is not very beautiful.


Drupal CSS broken in Internet Explorer 7/8, but works as static page The CSS layout on my Drupal site was suddenly found to be broken in IE 7 & 8. No idea what happened to cause this, but the strange thing is, if I save the source/files, then upload and test as a static page, it works fine (well, good enough for Internet Explorer). I'm using Adobe BrowswerLab to test.
I've turned off caching in performance and boost. I have also turned gzip compression off on the server, and added 10 second delay to browserlab load-time. Nothing seems to make the CSS work straight from the actual site.
I haven't found any threads about this specifically. Does anybody know what might be going on?

I am using Drupal 6.24.

Do you have CSS and Javascript caching enables? IE7 & IE8 can only load a certain amount of external files and you maybe exceeding the limit. Retry with CSS and JS caching enabled.


Rules scheduled email empty when using php variable, but not when hardcoded I'm using rules scheduler (on D7) to set up a reminder email based on a time specified within a commerce order (more specifically a line item in the order). I was able to get everything set up correctly using these instructions, so that the email is scheduled and send out. However, I am having a problem with the actual content of the email appearing correctly.

Just to clarify the rule setup, the flow is

Line item is updated
Rules scheduler schedules a component to run based on line item's date field
When the scheduled time is hit, the component is triggered

A view that serves the list of users is loaded
Component loops through list of users in the view

Email is sent to each user

The content of the email is defined by another view, which I am embedding using:

<?php
$id = $line_item->line_item_id;
print views_embed_view('commerce_checkout_page_for_email_embed', 'block_4', $id);
?>

The $id above is used to pass the line item's ID into the view to filter results by the current line item.

In my testing, when triggering the component directly on Line Item Update instead of at a scheduled time, everything works perfectly. The email is sent, and the body of the email contains the proper view filtered by the current line item.

However, when the email is sent by rules scheduler, the body of the email is empty. When I hard code $id ($id=1776 instead of $id = $line_item->line_item_id) the body of the email is exactly as it is supposed to be. I can only assume that this means that for some reason, the scheduled rule is not able to access the variable I'm passing to it. I also tried passing the token for the line item id, but you cannot pass token in PHP, so that was a bust.

Does anybody know why this might be, or have any suggestions?

Instead of scheduling a rule to execute and send an email with no context, you could use commerce_messages to create a message entity with all the data saved and then schedule the message_notify rule to send an email.

Messages: https://www.drupal.org/project/message

Commerce Message: https://www.drupal.org/project/commerce_message

Message Notify: https://www.drupal.org/project/message_notify


Drupal Commerce: How to prevent (or suspend) checkout where no shipping rate is defined? I am using the physical products module to calculate weight based shipping rates.

My client sells heavy items for which they sometimes need to arrange negotiated shipping rates for offshore delivery areas, such as UK Highlands and Islands.

Because a shipping rate cannot always be provided, this can result in a situation where the system returns a shipping service option of  'No shipping rates found for your order. Please continue the checkout process'.

From this situation it is then possible for a buyer to complete checkout without incurring a shipping cost at all!

What is the best method for preventing (or suspending) checkout in such situations? In such a way that the shop owner can provide a quotation based shipping rate before the buyer resumes checkout?

I understand that the shop owner can manually edit a cart order to include a manual shipping rate and I am also aware the Rules can be used to direct the order flow.

But how to prevent (or suspend) checkout before a shipping rate has been quoted?

Look at https://www.drupal.org/project/commerce_rules_extra (Commerce Rules Extra) which allows you to alter (including disabling) checkout panes based on conditions.


How to prevent the results from being truncated? I want to remove the limit of character imposed from Drupal 7 on the search result page. That is, displaying my result in full rather than truncating the results and adding ... at the beginning and end of the result. I already have a search-results.tpl.php in my templates and looks like that:

<?php if ($search_results): ?>
<?php print $search_totals.' << '.str_replace('%20',' ',basename($_SERVER['REQUEST_URI'])).'>>';?>
  <ol class="search-results test <?php print $module; ?>-results">
    <?php print $search_results; ?>

  <?php print $pager; ?>
<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

How can I prevent the results from being truncated?

You can simply add a new view mode for search results:

Go to admin/structure/types/manage/page/display (where "page" is your content type)
Expand the Show Custom display settings fieldset
Check Search index

Click Save
Go to admin/structure/types/manage/page/display/search_index (again, where "page" is your content type)

My advice would be to use download the Display Suite module (and enable the Display Suite module and Display Suite UI module) for extra fields and more options. No custom theming or coding required!


Using node_view() to display a node doesn't print local menu items When using node_view() to display a node (via return from a function that's called in hook_menu()) the usual View/Edit tabs are missing.

Is this expected behaviour?

Yes this is expected. The reason they are there, is because the path of view a node is at node/[nid] and the edit/view is at node/[nid]/edit. If you changed the default node path with hook_menu_alter the tabs on all nodes would disappear.

The reason they are there, is because they are of type, MENU_LOCAL_TASK, check out the documentation on hook_menu, if you need to know more.


Help on Drupal table prefix I just installed Drupal 7 and made some content and configuration.

After that, I just realized I did not put any table prefix on installation.

My problem is:

Is there anyone here that knows the SQL to add table prefix on Database drupl?

Example

current table: variable
must be: drupal_variable

I want to change all my table and add prefix.

If you have access to phpMyAdmin, you can do that manually following this steps:

Login to PhpMyAdmin
Select all drupal tables
With selected: Replace table prefix
From: {empty}, To: yourprefix_
in settings.php (sites/default/settings.php) change in the database configuration: 'prefix' => '', to 'prefix' => 'yourprefix_',
Run cron.


How to disable input field but show tekst with hook_form_alter? In D8 I have a form with several fields.
One specific field is a number. Input widget is Integer.

This field is prevalued with hook_form_alter like:

$nid     = \Drupal::request()->query->get("source"); // query string param
$node    = \Drupal\node\Entity\Node::load($nid);
$pe_punten = $node->get('field_pe_punten')->value;

I would like to achieve that the user has no access but can see this value. To disable it I can do:

$form['field_pe_punten']['#access'] = FALSE;

But how to replace this input widget with a piece of text which says "10 points"

I red several other QA but could not find out how to do this?

use #disabled like below:

$form['field_pe_punten']['#disabled'] = 'disabled';


Drupal 7 - Display Content type as Block and Block Naming Convention I have created a content type which has some fields, and I want these fields to be displayed as a block.

I've tried renaming a block in my 'theme/template' as block--[machine-name].tpl.php but is of no use.

So, if I understand this correctly, your asking how you can make a block which displays fields from a content type based on some logical requirements, then provide an .tpl override so you can do some custom work to the output of those fields? I hope thats right.

So this is relatively easy depending in how you want to go about this.

Step 1: You've created your content type and added all of the fields that you want. I'm assuming you've also created some content already to test the next part.
Step 2: You need to create a view that has a block display. See screenshot for an example. https://skitch.com/therealwebguy/8ksue/block-step-1
Step 3: Set up your block view appropriately. See screenshot for more specific details for this: https://skitch.com/therealwebguy/8ksw9/block-step-2
Step 4: If you refer to the screenshot provided in Step 3, you'll notice in the bottom right that I have highlighted the "Information" link for the Theme layer. Clicking this link will bring up a list of all of the .tpl files you can create for this view to target what you need. It has everything from the top-level view tpl to the output of a single field being rendered by the view. Choose the one that's best for you needs, copy the HTML provided and add it the view.tpl.php file you've chosen to use.

Lets recap:

We've create a content type and added fields to it.
We've added actual nodes of the new content type for testing.
We've created a new view which will provide a block display, showing us the field values of our content type that we want to show.
We've created a custom tpl override for the view of our choice to do some more customization at the theme level that best fits our needs.

The only thing left to do is to head over to your blocks administration and put the block where you want it.

Good Luck!


What's the syntax to apply hook_schema() in .install file? I want to build a installable module. Let's assume the module name will be bluedog_calculator. I have already created other required files like bluedog_calculator.info and bluedog_calculator.module. Now I am trying to use hook_schema() and whenever i am trying to use drush dre bluedog_calculator -y, Konsole gives me an error as follows:

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;   [error]
  check the manual that corresponds to your MariaDB server version for the right syntax to use near 'unsigned NOT NULL COMMENT.

I am not sure what is the right syntax for applying this hook.

My code is

function bluedog_calculator_schema(){
    $schema['bluedog_calculator_machine'] = array(
    'description' => 'TODO: please describe this table!',
    'fields' => array(
      'id' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'serial',
        'not null' => TRUE,
        ),
      'name' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'varchar',
        'length' => '100',
        'not null' => TRUE,
        ),
      'speed' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'float',
        'not null' => TRUE,
        ),
      'cost' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'float',
        'not null' => TRUE,
        ),
      'image' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE,
        ),
      'web_link' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
        ),
      'is_default' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
        ),
      ),
    'primary key' => array('id'),
);

return $schema;
}

The only place you use 'unsigned' is in this block:

'web_link' => array(
  'description' => 'TODO: please describe this field!',
  'type' => 'text',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

'unsigned' does not apply to text columns. Try removing that line from the web_link column definition. https://api.drupal.org/api/drupal/includes!database!schema.inc/group/schemaapi/7.x has useful reference on this.

(The docs state that unsigned is ignored for other types, but it seems the error is in that chunk, so I'd certainly try removing it in case your database engine is not ignoring it.)


Drupal 8 Webform : Regular expression in conditions to check specific day of the week I am setting another webform on Drupal 8.
I want to enable some fields based on the day of the week selected.
I used JS on a site with Drupal 7, it is working fine,  thanks to JSDrupal.

I would like to implement it on the Drupal 8 site with a regexp.
I am using the HTML5 date field, not the Jquery datepicker.
My concern is the same than before :

if the Day selected on field DATE_D( a Date field) is Tuesday OR Thursday then hide SELECT( select field).

Thank you

I doubt that you can achieve this without some JS involved.

You can use JS RegExp.

You could try Form API #states and try to hide the desired select field if some other field's value matches your conditions.

$form['my_select_element'] = [
  '#type' => 'select',
  '#states' => [
    // Hide this field when the 'weekday' radio has 'tuesday' or 'thursday' selected.
    'invisible' => [
      ':input[name="field_weekday[und]"]' => ['value' => 'tuesday'],
      'or',
      ':input[name="field_weekday[und]"]' => ['value' => 'thursday'],
    ],
  ],
];

(#states with multiple conditions, Source.)


rules condition to check whether user has flagged another Hi I have two user roles, client and consultant. Currently a client is able to flag a consultant as their selected consultant.

Now here is where im stuck. I am looking to use rules to display a message to clients whom have not flagged a consultant yet. How would i go about setting up this condition within a rule?

Okay so I managed to work something out although I dont entire understand why its working. I created a data comparison condition and set the DATA TO COMPARE to "account:flag-consultant-flag-flagged" and DATA VALUE is set to "account:flag-consultant-flag-user".

Here was my logic although I thought it would do the exact opposite. I figured that if i compared all the flagged consultants with the consultants flagged by the current user, there should be a match and so the condition would be true. Weirdly though the rule is firing for users that didnt select a consultant so it turns out it did the exact opposite. If anyone is able to give some clarity, it would be much appreciated.


Disable CKEditor on summary When I use the widget "field-type-text-with-summary" with the CKEditor, my summary is shown in the CKEditor-format. Can I prevent this and display the field with the plain-format? Hooking into the form, I haven't found a format for the summary; there is just one for the whole body field.

using CKEditor module.

I solved this for the CKEditor module for Drupal 7 by altering the widget itself using hook_field_widget_WIDGET_TYPE_form_alter():

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 * Set the '#wysiwyg'-attribute to false for the summary fields.
 */
function YOURMODULE_field_widget_text_textarea_with_summary_form_alter(&$element, &$form_state, $context) {
  if (isset($element['summary']) && !isset($element['summary']['#wysiwyg'])) $element['summary']['#wysiwyg'] = false;
}

Hope this helps!


Can we write php conditions in view field templates? My view fields are as like shown in screenshot, for each row I need to add comment link,revision link ,edit link, voting icons and topic terms etc And I have large number of views which will share all these fields.

So I thought to remove all the fields and have nid field in all my views. Then create common template file of nid. And in that template file I am planing to use node_laod and fetch all required fields and add them with some common required html structure.

Please suggest if this will be right way to achieve such kind of workflow and reducing work load to add fields in each view, make them easy to edit or make change in fields from template files.

Is this will be good idea to write php code in template file or I am supposed to use some pre process functions etc

Please suggest ! Thanks.

No. Do not make a view that pulls a nid, then do node_load in the template. This will be a performance killer.

You should create a view mode using Entity View Mode module, add the fields to the display, and theme it with node--node-type--view-mode.tpl.php. Then the configured View only has to show 'Rendered Content' - and pick the view mode. Then you're done.

See: https://www.youtube.com/watch?v=wcskTtvR6Mo


Insert image or link links When in edit, and presented with a wysiwyg editor for example, I've got a "Switch to plain text editor" link under. However, in one of the sites, in addition to this link I also have  "Insert image or link" links. But not in the other sites. Where is this setting coming from? Is it generally good practice to have these links?

There are few standard "Text formats" for a text field. Which one you actually can use depends on your permission settings (for example permission Use the Full HTML text format).

Then you have the settings for each of the text format (admin/config/content/formats), there you can set up what options a specific format has (you can add/remove image/link buttons).

The last thing to know is that order in which text formats are listed in the administrator page is important. It decides which text format is used as a default. A typical problem with ordering of text formats are automatic messages with broken links (result of "Plain text" format having too high priority).


How to display Webform label Above the field instead of Inline in Drupal 8? In Drupal 7 it was easy to select whether I wanted the label of a field to display Above or Inline with the field.  In Drupal 8 I can't seem to find this feature. I realize this can be done in CSS, but that seems like a kludgy way to do it if there is just a tickbox somewhere that I am missing.

Can anyone point me in the right direction?

Ben, Let me know you webform version I can guide where you can get that option.

As of now I am using webform version 8.x-5.0-beta15 & it seems your requirement is available in this module. Below are steps for same

Choose Any webform. Click on edit of that webform you will see list of fields available in that webform.
Select any of the field and click on edit option provided. You will see one popup is opened.
On that popup if you scroll down little you will find your required option. Please refer attached screenshot.

Hope this helps.. :)


bartik_links__system_main_menu() doesn't work When I implement bartik_links__system_main_menu($variables) in my template.php file, there is nothing different in the main menu than the previous one. I've changed some of the markup in this function; I checked it in the theme developer, and the function that is responsible for the main menu is still theme_links() rather than bartik_links__system_main_menu($variables).

Why?

Make sure that:

theme('links__system_main_menu', ... is actually used to output the menu.
There are no issues with your code.
Caches have been cleared after adding the function (admin/config/development/performance).

To better understand what system_main_menu is all about check keithm's answer here. The main part of the explanation is this:

  links__system_main_menu is a theme hook pattern of the form [base
  hook]__[context]. When links are themed with
  theme('links__system_main_menu', $vars), theme() will search for
  and use theme_links__system_main_menu() if it has been defined. If
  not, it will use theme_links().

Official documentation about it can be found here.


Drush migration no longer working in 8.5 I've been migrating a site from Drupal 7 to Drupal 8. The site was 8.4 when I ran the migrations. I've since updated the site to Drupal 8.5. Now, when I type drush migration-status or any migration-related command, I get the following error:

[error]  The file_entity plugin must define the source_module property.

Ok answering this myself. I keep forgetting that Drupal often introduces breaking changes and treats comments as code. It looks like the annotation changed in 8.5

What was in 8.4:

/**
 * Drupal 7 file_entity source from database.
 *
 * @MigrateSource(
 *   id = "file_entity",
 *   source_provider = "file"
 * )
 */

in 8.5 should now be:

/**
 * Drupal 7 file_entity source from database.
 *
 * @MigrateSource(
 *   id = "file_entity",
 *   source_module = "file",
 * )
 */


No imagecache actions available I have imagecache, imageapi and imageapigd enabled on my drupal 6 site. When I visit imagecache presets no actions (crop / resize et al) are available. This all seemed to work fne with the same configuration on my MAMP home box, however, this fails in production. Some other info:

PHP Version: 5.2.17
GD Support  enabled
GD Version  bundled (2.0.34 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.3.11
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support enabled
PNG Support enabled
WBMP Support    enabled
XBM Support enabled

I'm stumped - any help is greatly appreciated..

Did you happen to be using one of the latest 6.x-2.x-dev versions of imagecache?

I spent an entire day trying to figure this one out (because unfortunately this was the only relevant page that came up in a google search). Once I finally decided to try the 6.x-2.0-rc1 version, everything seemed to work fine.


How do you add a conditional to check if the Node object exists? I have the following code, but how do I add a conditional to check if the menu_get_object() is grabbing a node object or not? Im mainly using this in my contextual filter in views and its throwing an error on etity_metadata_wrapper() as its trying to load a node page while its in the view page. I'm not sure what condition to check before it returns anything. thanks!

$node = menu_get_object();
$wrapper = entity_metadata_wrapper('node', $node);
$tid = $wrapper->field_device_type_vocabulary[0]->tid->value();
return $tid;

If you are on a non-node page, menu_get_object() returns NULL.


overloading the destination url of privatemsg I have a privatemsg message form, and I need to alter the success URL that loads when a message is sent. What is the easiest way to go about doing this? The code i'm using is more or less based on the example code used here:

 module_load_include('pages.inc','privatemsg');dru
 print drupal_render(drupal_get_form('privatemsg_new'));

Using the Devel module implement hook_form_alter and find your forms $form_id. Then supply a #redirect FAPI attribute like, $form['#redirect'] = 'my-custom-thankyou-page'; and be sure to make your custom page as a drupal Page, module callback, View etc.