hook_form_alter based on path I don't know if this is possible but could I do something like

<?php

  $foo = current_path();
  print $foo;

?>

in page--foo.tpl, then something like

function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {
    function name() {
        global $foo;
        if $foo == 'user/register/foo' {
            unset($form['account']['mail']);
    }
  }
}

in a custom module. I'm trying to make fields unique to roles without using profile2. Getting this error when I try it though:

  Parse error: syntax error, unexpected '$foo' (T_VARIABLE), expecting
  '(' in
  /var/www/html/drupal/sites/all/modules/custom_forms/custom_forms.module
  on line 71

Using Auto Assign Role for the path.

It looks like you have researched a few ideas and mixed them all.  The page--foo.tpl is a theme template file, and the names there are often used with theme suggestions so you can change the regions and wrapping html for different pages in different ways.  This is theme layer, and should be used for changing the appearance but not the processing.

The Hook_form_id_alter() is used to alter that specified form before it is passed to the theme layer, so that function will run before the print $foo; in the template.

So with what is in your question, the process would go like this:

  Check value of yet-to-be-set global $foo If foo is a specific page,
  remove field from form send form to theming get current page save
  current page to local $foo and ignore the global $foo that has already
  been checked. print out the value of local $foo into the html of the
  page

Also, I do not see roles touched anywhere in your question.  If I have read it right, you dont need the tpl at all and you can do this all in the form_alter.

function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {
  global $user;
  if( current_path() == 'user/register/foo' ){
    // do what you want here
  }
}

Considerations.  Since you are using hook_form_ID_alter instead of hook_form_alter it is pretty safe to assume that this will only fire on the registration form so checking the registration url is a little redundant.  Since you are trying to define a function inside a function, you are used to javascript and the php scope handling is causing you some trouble; you should google for available drupal functions (like current_path() ) to help you before trying to write your own helper functions.


Set input value in custom search module I'm using custom search module in my site. What I want to do is set a value for the input (text box) in the username and password field.
How can I do that?

The Form API is your friend. Take a look in the Form API Quickstart Guide, how to change a form for your needs.


How to get Views Total number of records in Page.tpl.php file. (Before Views rendered) See this image for more understanding.

I want to fetch Views total number of records in page.tpl.php before views.tpl called. Is it possible to fetch that row total  before views rendered?
I am also using contextual filter for this view. Views have page type display.

I have also used module views_record_count. but this will print total number of records on Views header or footer. (Not outside of views)

You could use this code to print the count.

<?php

$view = views_get_view( 'test' );
$view->set_display('block');
$view->set_arguments( array( 1, 2, 3 ) );
$view->execute();
$count = count( $view->result );
print $count;

?>


How do I use Taxonomy reference field tokens in a path alias? I have a content type with two taxonomy entity reference fields. Both are required fields that only allow one value. I have path_auto and token enabled. I would like to use them to set the path of the node type.

This is the path pattern that is a problem:

[node:field_main_site_section:entity:name]/[node:field_content_category:entity:name]/[node:title]

It looks close to the answer given in another questionn here.

Result: The only thing showing up in the path is the title.

Versions: Drupal 8.8.5, pathauto 1.8, token 1.7

What have I tried?

I tried running the code through the debugger and found out that the action is in the functions PathautoGenerator::createEntityAlias() and Token::generate(). I see that the three tokens are found and that a Node data is passed to Token generate. Then the generate function runs $replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]). There were 9 modules found that implement hook_tokens but the only one returning any data is node_tokens. Looking at that code I don't see any attempt to return fields.

I also found an issue on the token module that indicated that I might be missing Token view modes. I was indeed missing a token view mode for my two taxonomy vocabularies so I created them. I added each field in the vocabulary including "name" in plain text.

I also tried to guess that the node needed to be converted to an entity to grab it's fields:

[node:entity:field_main_site_section:entity:name]/[node:entity:field_content_category:entity:name]/[node:title]

That was an invalid pattern.

Question:
What is the correct pattern or what else do I need to configure?

Solved by two changes:

Apply the patch from this Token issue, "Inconsistent loading of third party hook implementations"
Make sure Token display mode exists for each taxonomy vocabulary

I tested and confirmed that both the patch and the display mode config changes were needed.


How do I show a 403 error page when the server returns a 403 error code? I use the nginx config file from https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
It has return 403 and deny all on some file.
Ex. When I visit /core/CHANGELOG.txt, nginx returns default 403 Forbidden page.
I want it to display drupal 403 error page not nginx white default 403 page.
I have tried adding error_page 403 /403  but it returns

Not Found
The requested URL "http://mysite/core/CHANGELOG.txt" was not found on this server.

What you need to do is to configure nginx to serve a drupal page that generates a 403 page. There are severals ways to do this.

The easy solution is to route the traffic to Drupal (the index.php file), which would generate a 404 since the page doesn't exist in Drupal.

I think doing

location ~* \.(txt|log)$ {
  try_files @rewrite
}

should accomplish this for .txt and .log files. It should try to serve the file from Drupal. By default this will be a 404, but you can add the a route for specific files and return 403 instead.


Views don't seem to be working properly on localhost with Chrome This seems to be something connected to being on localhost rather than a server as once the site is uploaded it works fine - it's almost as if Chrome is too fast for my drupal site. Parts of the views don't register properly (fields will be missing) but some of them do.

The site works fine locally on FireFox, IE and Safari - it's just Chrome. Any ideas?

I think your chrome cache is loading the 'old' page

clear your chrome cache:

when in chrome press shift+ctrl+del
then check ´Empty the cache´
click clear browsing data.

should be fixed now ;)


Label Prints multiple times I have a list and I only want to print the label once. Right now, it prints for each variable.

if (isset($vocabularies));
$vocabularies = taxonomy_get_vocabularies();
if ($vocabularies) {
  foreach($vocabularies as $vocabulary) {
    if ($vocabulary->vid == 5) {
      $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
      if ($terms) {
        foreach ($terms as $term) {
          print '
Event Type:

' .$term->name;  '

';
        }
      }
    }
  }
}

Try this:

 $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
 if ($terms) {
   print 'Event Type: ';
   foreach ($terms as $term) {
     print $term->name;
   }
 }


Conditional drupal_add_css and _js are adding code to every page I am trying to add a CSS and JS files when a certain content type is being viewed (Drupal 6).  The problem is that the code is being added to every page.

I have tried this first, included in template.php:

function phptemplate_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if ($node->type == 'mytype') {
        drupal_add_css(path_to_theme() . "/css/mytpess.css");

        drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
        drupal_add_js("$(document).ready(function(){
                          $('.node').masonry({
                            itemSelector: '.field-type-flexifield'
                          });
                        });",'inline');
  }
}

Then I moved it out of there and placed it in node-mytype.tpl.php:

drupal_add_css(path_to_theme() . "/css/mytpess.css");

drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
drupal_add_js("$(document).ready(function(){
                  $('.node').masonry({
                    itemSelector: '.field-type-flexifield'
                  });
                });",'inline');

But either way it gets added to every page.  How can I resolve this?

If you are adding drupal_add_css or_js in phptemplate_preprocess_node,

First fetch all the added css in one variable and assign this for $styles value
Same like css you need to do for js also.

Here with see the sample code below

function phptemplate_preprocess_node(&$vars, $hook) { $node = $vars['node'];
if ($node->type == 'mytype') {
    drupal_add_css(path_to_theme() . "/css/mytpess.css");

    drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
    drupal_add_js("$(document).ready(function(){
                      $('.node').masonry({
                        itemSelector: '.field-type-flexifield'
                      });
                    });",'inline');
 }
$css = drupal_add_css();
$scripts = drupal_add_js();
$vars['styles'] = drupal_get_css($css);
$vars['scripts'] = drupal_get_js('header', $scripts);
}


Creating view using Index results in "plugin does not exist" I was having some problems with Search API after adding my second index (using DB not Solr).  The index I was trying to create was supposed to just be the body and title of a content type.  I was able to build the index just fine, but when trying to attach it to a view (My Test View) I'm getting a funky message directly above the Preview section on the view page.

  The "views_page:my_test_view__page_1" plugin does not exist.

I am utterly confused by this.  I uninstalled Search API and reinstalled, but the only change is this now happens to both views using a search index.  I am able to successfully create non-search index views, but that's the only evidence I have this is even Search API's problem.  Can someone please direct me on how to start debugging this?

This is Drupal 8.

I now believe this is some type of caching issue, though I'm not sure why.  Originally I thought uninstalling a particular module fixed the issue, but the "plugin does not exist" error appeared the next day when creating a new view. Clearing the cache seems to clear the error, which is a good enough workaround for now until I have more time to dedicate to this.


Drupal 7 : Programmatically validate form by form ID Intro - i am trying to implement Sales Force form within Drupal FAPI but now it requires to add captcha so i need to send first request to internal page so i could validate captcha and only after this i can redrect user to Sales Force.

So I want to do such thing :

i have page /contacts and usual form coming from my module that
was created within FAPI
the form has some standard validators
when it is submitted to the same page where the form is, e.g. /contacts, the
validation works fine i can get the errors, but i want to send first
POST request to e.g. /forms URL and validate it there, but /forms
knows nothing about the form and thus validation is not called

The question is :

Basically, i need to validate form separately without rendering it on a new page. Can i do something like this :

drupal_get_form($formId)->validate() ?

Update #1 :

I am already using Captcha module but Sales Force usually is implemented this way - there should be a form on my site with the fields which SF is aware of, when this form is submitted to SF page (external site) SF gathers needed data from the POST request and redirect user back to my site ... but in this case there will no be any validation because right after submit user will be redirected to SF site, Drupal will not process such requests.

Now i really need this validation before submit so i created new page (internal) and want to trigger validation on this page but the issue is that form is located on the page "Contacts" and i am trying to send and validate data to the empty page "Forms".

If i simply send POST to Contacts (where the form is) then validation works fine, Forms does not trigger validation at all.

And as i already said i have form array that describes all fields and validators for them, then i render this array as a form on a Contacts page so i cannot understand why do i need to add hook_form_alter and create some extra validation function on a Forms page if i already described all validation rules on Contacts page?

Update #2 :

Seems that i already got the answer from Wolwerine, i would like to explain why i so willfully wanted to have initial form on a Contacts page and validate it on a Forms page.

I have Parallax site, i.e. single-page-application, which means that eveything in this application should be done without page reloading including those two requests for the issuing form :

validation request
final request to Sales Force after validation

As a result all requests are done within AJAX.

Page Contacts contains main layout and HTML form and any request to this page will return me tons of HTML which i will not be able to analyze in JS and understand whether this request and validation were successful or not.

Of course i can parse these HTML results and try to find some validation errors in this HTML but IMO this is not the case.

So i created separate page that does not include main layout and neither content, i.e. some kind of page that will work only with AJAX request and return exact type of response that i can get in this case HTML, JSON and so on without messing them up.

Thanks, i appreciate your help and upvoted all answers that look helpful.

P.S. This is how i do validation on a Forms page now :

<?php

$data = $_POST;
$form = drupal_get_form($data['form_id']);
$errors = form_get_errors();

if ($errors) {
    print json_encode(array('errors' => $errors));
    die();
}

$c = curl_init();
curl_setopt($c, CURLOPT_URL, $data['destination']);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $data);
curl_setopt($c, CURLOPT_HEADER, 0);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($c);
curl_close($c);

You can add an extra validation function using hook_form_alter.

If all you need is to add a captcha to the contact form you could try simply using the captcha module, or the mollom module.

If you've created the form yourself using a form builder function, you can add a validation function (with all your validators) to that:

function YOURMODULE_YOURFORM_form_validate($form, &$form_state) {
// Your validation code.

}


php in views contextual filter for different user roles I am attempting to filter a view based on a php contextual filter, however the filter needs to come from different sources depending on the users role:

administrators - from a query string
all other roles - from an entity reference field on the user

I am using draggable views which prevents me from using two separate views.

So far I have:

global $user;

    if (in_array('administrator', array_values($user->roles))) {
        $query= $_GET['query'];
        return $query;
      }
    else{
        $user_uid = user_load($user->uid);
        $myfilter = $user_uid->field_custom['und']['0']['target_id'];
        return $myfilter;
    }

The else filter works great but it is failing to filter for the administrator role.

You could also use user_access() to see if a user has the rights do to something.
If you use some core administrative tasks, you can be sure that it will trigger only for administrators

E.g.

global $user;
if (user_access('administer site configuration')) {
  $query = $_GET['query'];
  return $query;
}
else{
  $account = user_load($user->uid);
  $myfilter = $account->field_custom['und']['0']['target_id'];
  return $myfilter;
}

Note: I used $account instead of $user_uid to store full user object; most of the contributed modules and core name the variable this way.


Embedding the s3slider jQuery plugin in a block How can I add a custom image slider similar to this one in a block?
I tried integrating it in a block, but it doesn't work.

What is the best image slider for Drupal 7, excluding the View Slideshow module? I tried using it, but it only displays the last image of the slideshow.

I would use in D7 the Fields Slideshow module.

If you still want to use the s3 slider, these are some general steps to make.

Make a content type with an imagefield.
Add nodes for each slide in your slider.
Create a view that has the fields you need.
Set the field stye of the imagefield to none for all the items (label and wrapper too).
Set the body field style to span and set none to label and wrapper. Trim the field to your desired length and remove any html.
Go to 'Theme information' in your view. You need to copy the name of the templates of the views you will be replacing. You need to get the list template (views-view-list--MYVIEWNAME.tpl.php).
Go to the themes folder in the views module and copy the views-view-list.tpl.php into your theme and rename it to what you figured out in the first step.
Change the content of the template with something like this, remember to change MYTHEMENAME to the name of your theme and remember to flush your theme registry so it recognizes the new template file.

I couldn't add the code successfully so I made a Drupalbin: http://drupalbin.com/20119


How do I implement a custom theme function? I'm trying to print a markup in a peg. I've implemented a function passed the values through the variables. Also I've implemented a custom theme function with a markup.

But it is giving the error.

  Template "modules/custom/example/templates/example.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/custom/example/templates/example.html.twig" in the Drupal theme registry.).

Here is my code.

/**
 * Implements hook_theme().
 */
function example_theme($existing, $type, $theme, $path) {
   return array(
    'example' => array(
      'variables' => array('items' => array()),
    ),
  );
}
// Theme function
function theme_example($variables) {
   return 'hi'
}
// Preprocess implementation.
function template_preprocess_example(&$variables) {
  $value = 'hi how are you';
  return $value;
}

I've implemented both one after another, but they didn't work. Is the custom theme function format changed in Drupal 8?

From the description of valid parameters in the docs:

  function: (deprecated in Drupal 8.0.x, will be removed in Drupal 9.0.x) If specified, this will be the function name to invoke for this implementation. If neither 'template' nor 'function' are specified, a default template name will be assumed. See above for more details.

So if you must use a function, you need to be explicit:

function example_theme($existing, $type, $theme, $path) {
   return array(
    'example' => array(
      'variables' => array('items' => array()),
      'function' => 'theme_example',
    ),
  );
}

But considering that method is deprecated in favour of template files, it would be better to use one. You can do so by simply creating a template file at modules/custom/example/templates/example.html.twig


How to show payment form on node form preview in Drupal 7? I have make a content type, I have make compulsory to preview node before saving, now what I need when user click on the preview button, he can review his information which he wrote in the form and then there should be payment form, if the payment is successful, node will be saved else not.

Try out Pay-per-node module.

  It can be used as standalone module or as an e-commerce plug-in. In
  the second case paypernode can be integrated with Ubercart, providing
  a new "product feature" which will allow, upon product purchase, to
  create a number of nodes.


Cache warming in drupal7 I have a drupal 7 website that uses Varnish for caching (through drupal's Varnish module).
 I want a cache warming mechanism that would automatically cache the latest version of the pages after the cache expiration time has passed.

How can i do this?

You could try the cache warmer module, which apparently does just that.

There are also a bunch of blog posts on the topic around the web.


How can I log in as admin to my Commerce-kickstart demo site? I am new to Drupal and I have completed the installation process for Commerce Kickstart in my XAMPP environment.

When I try to access the admin page of my sample commerce-kickstart demo eshop, I get an error like so:

  error 403 access denied

I am using the predefined Username (admin) and password and PHP 5.3.6.

Can anyone help me to get logged in as admin?

Check if anything in this list of typical things might help:

Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem. To solve that, delete the cookie in the browser where you have the problem.
Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly (in your settings.php).


Entity template file/suggestion not working I've created a entity template file but it's not working.   I've looked at the theme registry and I can see the template file is in there but it's not getting applied for some reason.

Thank for you help,

I figure this out and it was relatively simple.   I added a preprocess function to template.php for entities and added the template file back in to theme_hook_suggestions array.

function theme_preprocess_entity(&$variables){
  $variables['theme_hook_suggestions'][] = 'entity__your_template_name';
}


Views Slideshow, white backround when hover I'm using drupal 7,views slideshow and views slideshow cycle modules, I have a white background color when hover on the slide, I can't remove it or find their css selector in chrome webdeveloper.

Help me please.

As Sohail mentioned, it's really hard to figure this out for you without being able to view the actual web page. It's most definitely a CSS issue and is just a matter of finding the right selector. Can you just use Inspector in Chrome to find the selector that encompasses that area, and then search within the stylesheet it says it's using for that selector with hover? Perhaps just search the stylesheet for #fff to see where white is being used and then see where it is making that area white?


How can I access the node ID when writing PHP into a block? I see that when I am creating a block through the drupal admin I can use PHP, in addition to plain text & html.  Is there a variable in scope that I can use to access the node id?

<?php echo my_custom_function( $node_id, $my_desired_class); ?>

You can use the menu_get_object() function which will get you the node object for the page, assuming of course your block is being displayed on a node page:

$node = menu_get_object();

if (isset($node->nid)) {
  $nid = $node->nid;
  echo my_custom_function($nid, $my_desired_class);
}


How can I get a default value in a dropdown using form API? $results = db_select('users', 'u') ->fields('u',array('name','uid','mail')) ->execute();
$options = array();
foreach ($results as $result) {
$options[$result->uid] = $result->name.' | '.$result->mail;
}
unset($options[array_search(0, $options)]);
$form['user'] = array(
'#type' => 'select',
'#title' => t('Select User'),
'#options' => $options,
'#default_value'=>('select a value'),
'#states' => array(
'visible' => array(
':input[name="data_set"]' => array('value' => 'education'),
 ),
 ),
);
$form['submit']=array(
'#type'=>'submit',
'#value'=>t('Expire')
);

I have this dropdown , how can I get the default value like Select a value or something

For required items a -select- item is added automatically. If the form field is not a required one, you'll have to add it manually, for example with the following code.

  $options = array('_none' => '-select item-') + $options; //Places an extra option at the start

If it's the first item it should be selected automatically but if you want to be safe.

  // Use the array key, not the value.
  '#default_value' => '_none',

You'll have to filter it out the '_none' value in the submit handler afterwards.


Display content based on URL I am working on Drupal 8. I have a to display content from a content type on different pages. I am trying to use Views to achieve this.

In the content type I added a field to refer to Pages so that I can create relation between content of content type and Pages (another content type). Basically its like tagging content with page name.

I want to display content from content type created on those pages tagged in the content. I am not able to achieve using views.

Any ideas how this can be done? I have tried contextual filter and relationship but none works.

Thanks

You can use as an example the taxonomy term view, which is in the D8 standard installation:

admin/structure/views/view/taxonomy_term

Two steps are necessary. First define the parameter in the path. For the taxonomy term this is:

Path

taxonomy/term/%

This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term

Then add a contextual filter in the advanced section, which will process this parameter:

CONTEXTUAL FILTERS
Add contextual filters
Content: Has taxonomy term ID

For the details see the example in your drupal installation. In your case you would use the referenced Pages node id.

If you want to use the view as a block, you cannot define the parameter in the path setting of the page. Then you have to switch in the contextual filter to "Provide default parameter" and configure the parameter from URL.


Why hook_user_logout is not working? I am trying to display message or run some other action when user logout and redirect them to home page. I am trying following code, but all I get is just set_message and it never logoff me. why?

/**
 * Implements hook_user_logout().
 *
 */
function ucenter_user_logout($account) {
  drupal_set_message(t('Thanks for visiting, come again!'));
  drupal_goto();
}

Calling drupal_goto(), you are avoiding the session is destroyed. The function that invokes hook_user_logout() (user_logout()) contains the following code.

  watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
  module_invoke_all('user_logout', $user);

  // Destroy the current session, and reset $user to the anonymous user.
  session_destroy();

  drupal_goto();

drupal_goto() calls drupal_exit(), which means that with your Drupal's execution is interrupted before session_destroy() is called.

What you can do is changing the code to something similar to the following one.

function ucenter_user_logout($account) {
  user_cookie_save(array('ucenter.logoff' => '1'));
}

function ucenter_init() {
  // Check the value of the cookie Drupal_visitor_ucenter_logoff
  // and print the message if the user precedently logged off.
}


db_query returning blank page I've been stuck on this problem for a while now. I am trying to get the results to display from the api if there are no entries in the db that match the id thats being called from the api and then store those results into the db if there is a Id that matches then pull the results from the db and display them instead of displaying the results from the db.

I keep running into this error which is causing the page to go blank when being displayed PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '29f1fc0bbd3dfe65a9e0ba6e044fb8e3398967a3' in 'where clause': SELECT * FROM {places} Where {ID} = 29f1fc0bbd3dfe65a9e0ba6e044fb8e3398967a3; I guess its because it cant find the id in the db, but it should still show the results from the api.

My logic makes sense im not sure what I am missing, Any suggestions?

       $listings_key = 'xxxxxxx';
            $xml = file_get_contents('https://maps.googleapis.com/maps/api/place/textsearch/xml?query=loans+near+'.$city_name.'&sensor=true&type=bank&key='.$listings_key.'');
            $listings_request = simplexml_load_string($xml);

            $loans_places = '';
            $loans_places .= '
';

            foreach($listings_request->result as $pre_list){
                $xml2 = file_get_contents('https://maps.googleapis.com/maps/api/place/details/xml?reference='.$pre_list->reference[0].'&sensor=true&key='.$listings_key.'');
                $xml2 = simplexml_load_string($xml2);
                $l_ID = reset($xml2->result->id[0]);

                $dbresult = db_query("SELECT * FROM {places} Where {ID} = ".$l_ID."");

                foreach($dbresult as $db_inlist){

                    dpr($db_inlist);

                    $places = array(
                        'Name'      => $xml2->result->name[0],
                        'Address'   => $xml2->result->adr_address[0],
                        'Phone'     => $xml2->result->formatted_phone_number[0],
                        'Website'   => $xml2->result->website[0],
                        'Ref_ID'    => $xml2->result->reference[0],
                        'ID'        => $xml2->result->id[0],
                        'City'      => ucwords(arg(2)),
                        'State'     => arg(1)
                    );

                    if($l_ID != $db_inlist->ID){
                        $loans_places .= '
';
                        $loans_places .= ''.$xml2->result->name[0].'
';
                        $loans_places .= $xml2->result->adr_address[0].'
';
                        $loans_places .= (isset($xml2->result->formatted_phone_number[0]) ? $xml2->result->formatted_phone_number[0].'
' : '');
                        $loans_places .= (isset($xml2->result->website[0]) ? l('website', $xml2->result->website[0]).'
' : '');
                        $loans_places .= '
';

                        //execute store into db function
                        $nid = db_insert('places')->fields($places)->execute();

                    }else{
                        $loans_places .= '
';
                        $loans_places .= ''.$db_inlist->Name.'
';
                        $loans_places .= $db_inlist->Address.'
';
                        $loans_places .= (isset($db_inlist->Phone) ? $db_inlist->Phone.'
' : '');
                        $loans_places .= (isset($db_inlist->Website) ? l('website', $db_inlist->Website).'
' : '');
                        $loans_places .= '
';
                }
            }
        }

    $loans_places .= '
';

return $loans_places;

You're currently escaping a bit too much...you only need to use the {} placeholders for table names. With an extra small change to protect you from SQL injection, your code should be something like:

$args = array(':id' => $l_ID);
$dbresult = db_query("SELECT * FROM {places} Where ID = :id", $args);


Are Drush and Phing redundant? I've installed JenkinsCI on our dev server to start automating our dev build and test process.   I'm using Jenkins with the Git Plugin and some Drush commands via a shell script.

When researching how to use Jenkins in my Drupal dev workflow, I came across a post about using Phing with Drush and Jenkins. So I looked at Phing and I can't see what it does that cannot be done by using Drush commands via a shell scripts.

I'm trying to decide if it makes sense for me to invest the time in learning how to use Phing.  I'm looking for some clarity as to what benefit I will gain by incorporating Phing vs. Drush commands via Shell script.

So my question is for those who use Phing with Drush and Jenkins: how is it that Drush/Drush-Make and Phing differ?  Why did you decide to start using Phing in your process?

Thanks

The answer is that they are certainly not redundant.

It's true that one can accomplish the same end result using a  bash script that includes drush commands (at least the building part).  But, if what we are looking to do is to integrate our process into a CI framework like JenkinsCI, then using something like phing (ant or capistrano could be substituted here) is the way to go.

With phing we can break up the build process into distinct segments that can report back to Jenkins in an intelligent way.

So for example.  Say that as part of my build process I use drush to enable two modules, node and shouldfail.  Then the build should fail.  But if all we do is tell JenkinsCI to run the following shell command, JenkinsCI will say that the build PASSED:

drush --quiet --yes @staging en node shouldfail

Clearly that's not right.  However if instead we use ant or phing to define the same process, we can also add some fail logic that Jenkins understands, and therefore fail as it should.  The following phing build script tries to do the same thing as the former command, but fails as we expect it to:

<project name="staging" default="enable modules" description="Jenkins Staging Build">

    <target name="enable modules">
      <exec  command="drush --quiet --yes @staging en node shouldfail" error='error' checkreturn="true">
      </exec>
      <loadfile  property="en.error" file="error" />
      <if>
        <contains string="${en.error}" substring="warning" />
        <then>
          <property name="en.fail" value="Could not enable all modules" />
        </then>
      </if>
      <fail if="en.fail" message="${en.fail}" />
    </target>

</project>

BTW ant and phing are almost identical.  The advantage for PHP developers in using phing is that they can more comfortably extend phing.

As for Drupal development and drush being as good as it is, I don't see too much value in extending phing, and think that running exec tasks would suffice to create a smart build template.

Well, in order to answer my question I ended up investing the time to figure out phing.  It's actually pretty intuitive and it doesn't take too long to figure out.


How to pass Views contextual filter via URL? I want to pass some values to my view via contextual filters in the URL. What GET naImes do I use? There seem to be no clue given, just this "The contextual filter values is provided by the URL".

If I have to construct that URL, how do I find out what GET var names do I need to pass so they are recognized?

Contextual filters aren't passed in separate variables, they are part of the path. If your view path is xxx/yyy then to have a filter value of nn the path would be xxx/yyy/nn.


getting a notice in reports for Commerce Paypal EC. IPN for Order ignored: I am using Commerce PayPal and specifically the submodule for Express Checkout.

When checking the reports, I see many different IPN connections happening. the last two, the user is marked as "anonymous" instead of user name. The first is "IPN Validated..." and the second is "IPN for Order 138 ignored: this operation was accommodated in the direct API response."

Is this normal? Is there something in my settings that needs to be changed so it isn't "ignored"?

OK, so in your case, it sounds like the IPN notification is being skipped because the order is already in the "complete" status.

To keep the IPN processing, you may need to keep the default "pending" status for such orders. That way, the IPN notification can mark the order as complete.


how to implement substring() in db_select statement I am porting a drupal 6 module to drupal 7. I came across this SQL query:

SELECT count(*) AS total FROM {counter} WHERE SUBSTRING(counter_date,1,10)= '%s'

How to implement the same query in db_select. db_select() will have substring() in its condition clause.

A couple quick greps suggest something like this...

$query->where('SUBSTRING(counter_date,1,10) = :arg', array(':arg' => $arg));

...should do it.


Entity Reference and nested arguments in Views My site has 3 nodes:

Program, which is a list of Course nodes.
Course, which contains basic information about a course you can take
Course Date, a specific instance of a Course. Each Course Date references one Course, and the titles are auto-generated.

The view I'm scratching my head over is

I need a view that loads on each Program node, showing all current Course Dates who's Entity Reference matches any Course in the current Program.

It would be a lot simpler if each Course was only in one Program, but they aren't.

I've tried Relation and found it too buggy for production. I've tried Reference and Entity Reference, and settled on the latter as it seems more featured.

Would it be possible to automate some kind of reverse field reference? Any tips welcome!

Actually Entity Reference does implement reverse pointers, so to speak.

On your program view, which I suppose has entity reference fields to course nodes, first set up a Relationship (under the 'Advanced' view section) that will link to the view the specific Course nodes that exist for the current program as entity references.

If you go to add a relationship, you'll get a dialog that looks like this:

Set it to filter the potential relationships to ones using 'Entity Reference' fields.
Select the 'Referenced entity' field that exists in the Program content type to point to its Courses (whatever you called it).  You can choose to change its name to 'Referenced course' or something short like that for later.  You can also limit the view to include only Programs that have course fields by checking that 'Require relationship' box!
Now all those course nodes are available in your view (you can add their fields to your view if you need to)
Next, add one more relationship.  This time look for the relationship that is a 'Referencing entity' (as opposed to 'Referenced entity') for your Course Date node.  That will provide a link to all Course Date nodes, which themselves reference the current Course node.  When setting up this second relationship, make sure you select the previous relationship to be used in the 'Relationship' dropdown.  After all, this reverse reference points to the course node of the current program, not to the current program itself, right?
Finally, you should now be able to add fields for course nodes and course date nodes that relate to your program, because of these two relationships.  Just make sure the fields you add, have the correct Relationship set from the relationship drop-down.  That way they will pull from the correct node.


Remove commerce item from cart I can add an order item from the cart by doing this :

\Drupal::service('commerce_cart.cart_manager')->getStorage('commerce_order_item')->create(array())

Is there a similar way to delete a product line from my cart ?

Orders have a removeItem method defined on their interface. You just need to pass the loaded order item to that method, and then delete the orderitem.

/**
 * Removes an order item.
 *
 * @param \Drupal\commerce_order\Entity\OrderItemInterface $order_item
 *   The order item.
 *
 * @return $this
 */
public function removeItem(OrderItemInterface $order_item);


set maximum length to image title I'm trying to figure out how I can limit the maximum length of an image title to 40.
I have enabled title from the image field in my content and it works fine except that it seems to take unlimited number of letters. I want to reduce the maximum length of image title to 40.
Does anyone have any idea how to do it?
Thanks

Something like this may work:

/**
 * Implements hook_field_widget_form_alter
 */
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'image' && $context['instance']['widget']['type'] == 'image_image' && !empty($context['instance']['settings']['title_field'])) {
    foreach (element_children($element) as $delta) {
      $element[$delta]['#process'][] = 'mymodule_image_field_widget_process';
    }
  }
}

/**
 * Image field process callback
 */
function mymodule_image_field_widget_process($element, &$form_state, $form) {
  // Set title maxlength, if accessible
  $maxlength = variable_get('imagefield_maxlength', 40);
  if ($element['title']['#access']) {
    $element['title']['#maxlength'] = $maxlength;
  }

  return $element;
}


How to process the result of a view? I'm working on a publication database, the result should be something like this: http://www.bmj.com/content/350/bmj.h2747 As you can see in authors list and in Author affiliations block, only unique workplaces are listed as footnotes of authors.

I'd like to figure out how this can be reproduced with views (or with other technique)? I created a content types for authors and can filter them for a given article in a view. But the result should be massively process: I have to filter the unique workplaces and assign them to authors in the display.

So as the title asks: How (and where - in the view?) can I process the result of this view?

Views can be great for some things, but sometimes it can add more complication then it is worth. Trying to achieve this in views seems like it could be one of those situations.

If you are familiar with coding, it might be easier to process the list of authors, grab the entity_reference from them, create an array from those where you don't repeat the values and then output the numbers associated with each value.

If looking to do this solely in views, you could use https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7 to grab the results and process them and then output the rows as desired.


Custom module 'managed_file' variable info keeps disappearing I have a custom module which allows a 'managed_file' upload in the settings/config page. This works fine and displays as expected after uploading (with the filename linked, and a "Remove" submit button) but the value of the field keeps disappearing after some time. What am I missing?

Here's the code from the custom module:

  $form['custom_managed_jpg'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_managed_jpg',
    '#title' => 'Custom Image (JPG)',
    '#default_value' => variable_get('custom_managed_jpg', ''),
    '#upload_location' => 'public://custom_directory/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg'),
    ),
    '#description' => t('This is a custom image (jpg format).'),
  );

It appears to be a problem with the file_load function. The variable is indeed saved, as I get a file ID when I dpm() the variable_get('custom_managed_jpg') (a number -- the fid). However, when I dpm() the result of file_load($fid) it is empty.

The strangest part is that this works as expected to start with, and the file will even remain between page loads and cache clears, but then after a few hours it just disappears as described above without any warning.

UPDATE:

It seems that the reason file_load doesn't return anything is that the directory (public://custom_directory/) is empty. At some point these files are being deleted from the directory but I have no idea why.

UPDATE2:

When I watch the file_managed table, I can see a new file added after uploading. The one difference between files uploaded here and those already in the table is that the status field is set to 0 instead of 1. I am guessing that could be part of the problem? How/where do I set the status to 1 programmatically?

Scott's code is right (and is nearly identical to what I had) but the final step I was missing is in the form's submit handler, where I needed to grab the file that was uploaded and mark it as permanent, and add a file usage to tell Drupal the file was in use. By default Drupal treats uploaded files as temporary and they are deleted from the database and filesystem after 6 hours (when cron runs).

Here's the submit handler code.

function MODULE_admin_settings_submit($form, &$form_state) {
  global $user;
  if (isset($form_state['values']['custom_managed_jpg']) && $form_state['values']['custom_managed_jpg']!="") {
    // Load the file via file.fid.
    $file = file_load($form_state['values']['custom_managed_jpg']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    // Record that the module (in this example, "custom module") is using the file.
    file_usage_add($file, 'custom_module', 'custom_managed_jpg', $user->uid);
  }
}


Taxonomy and views exposed filter I have a taxonomy reference link appearing on a content type.
I have a view showing all nodes tagged with certain terms in that taxonomy vocabulary.

On the view page I configured an exposed filter (select box), with options to filter the view by taxonomy term.

When I use the exposed filter I get a url like in following example:
../viewpagepath?tid=5

When I manually type a different 'tid' as url parameter the active filter option in the exposed filter changes to the corresponding term name.

I used the Taxonomy display module to change the Taxonomy page to the same view.
However, when I click on the taxonomy reference link on the content type, I can't get the url to look like this ../viewpagepath?tid=5 so that the right filter option is active.

How do I do this?

I see 2 options:

Changing the term reference link on the content type, so I get the same url pattern. (I can't use Pathauto because it doesn't accept a '?' in the pattern).
Changing the exposed filter url to match a pattern set in pathauto.

Wich one is best? Wich hooks or configuration do I use to get the right result?

I've solved a similar problem with drupal_get_path_alias() and hook_form_alter(). In my case I link from my content-type to the taxonomy page with the following:

<?php
// have a field with tags - in my content-type template I do
$terms = array();
foreach ($node->field_blog_post_tags['und'] as $key => $value) {
    $terms[] = '' . $value['taxonomy_term']->name . '';
}
print implode(', ', $terms);
?>

And to set the exposed filter I use hook_form_alter() in a custom module:

/**
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ('views_exposed_form' == $form_id) {
    // term-id and vocabulary are part of arguments
    $args = func_get_args();
    // select your filter
    if (isset($args[0]->vocabulary_machine_name) && 'YOUR_VOCABULARY' == $args[0]->vocabulary_machine_name) {
      // set the exposed filter with name 'YOUR_FILTER'
      $form_state['input']['YOUR_FILTER'] = $args[0]->tid;
    }
  }
}

Maybe it's helpful for you.


How to set all values of a field as body classes I want users to easily modify the layout of a node by selecting options in a 'Layout' field that the node contains. The field is a entityreference field referencing taxonomy terms.
(For example, the user can select term 'hide-images' and the body class 'hide-images' will be used in the css to hide images.)

I have found this code that sets the first value of a field as body class.
But how can I add all field values (taxonomy terms) as body classes?

/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$vars){
  // Check if on an article node page
  if($node = menu_get_object('node') && $node->type == 'article'){
    // Get field values
    if($term = field_get_items('node', $node, 'field_layout')){
      // Add first term value to body class
      $vars['classes_array'][] = drupal_html_class(reset($term));
     }
  }

}

Instead of reinventing the wheel, you could take a look at Display Suite.  DS has this functionality built in.

DS comes with a sub-module (DS extras) that has a feature that allows users to select a style right from the node edit page.

After enabling ds, ds_ui, ds_extras you can enable /admin/structure/ds/list/extras -> Other Tab -> View mode per node to use the feature.

Description of the feature:

  Change view modes for individual nodes. A new tab 'Display settings'
  will appear on the content create form. You can also pass the name of
  a view mode through the URL, eg node/x?v=full. If you install the Page
  manager module and override the node view, Page manager will win.

Update: If you still want to do it the way you started, you can just change this bit to use a foreach:

Change:

if($term = field_get_items('node', $node, 'field_layout')){
  $vars['classes_array'][] = drupal_html_class(reset($term));
}

To:

if ($term = field_get_items('node', $node, 'field_layout')) {
  foreach ($term as $item) {
    $vars['classes_array'][] = drupal_html_class($item['taxonomy_term']->name);
  }
}


Making text fields autocomplete in views exposed filters I want to make a text field auto complete in a views exposed form. I tried using the following code but nothing happens(I don't see that blue icon in the text field):

<?php
function nk_menu() {
    $items['nk/autocomplete'] = array(
        'page callback' => '_nk_autocomplete',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}
function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
        $form['title']['#autocomplete_path'] = 'nk/autocomplete';
        $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
        print_r($form); // to be sure that properties has been added to the form (they are added)
    }
}

function _nk_autocomplete($string) {
  // ...
}

Why doesn't it work? I know that there is a module for that, but I want to know why mine doesn't work?

Views change elements after form generation, so you should add own after build function:

function nk_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-my-page')) {
      $form['#after_build'][] = 'nk_views_mypage_exposed_after_build';
    }
}

function nk_views_mypage_exposed_after_build($form, &$form_state) {
  $form['title']['#autocomplete_path'] = 'nk/autocomplete';
  $form['title']['#default_value'] = 'abcd'; // this one also doesn't work
//  print_r($form); // I recommend to use dsm function of devel module, instead of print_r.
  return $form;
}


Allow only single product in Cart Is there any way to allow user only one product in cart. I used uc_restrict_qty but After that i can add more than one products also.

If the module uc_restrict_qty not working file your issue there. Alternatively You can achieve this with help of hook hook_uc_add_to_cart

hook_uc_add_to_cart($nid, $qty, $data)

  Performs extra processing when an item is added to the shopping cart.

Inside hook you can check your conditions, and prevent your new item to add.

uc_cart_get_contents() can used to get existing contents of cart. If it is greater than 1 you can do your logic here, either remove previous one and add the current one or remove the new item


Cannot log in to Drupal site I have problems with a Drupal 7 site. Sometimes, when I try to log in as non-admin user I am not able to login, despite typing in the correct email and password (I am using the Email Registration module). There is no issue with this module because from the very first day after I installed it, it worked well. However, in the last couple of days or week I am getting errors for when I try to login.

I logged in as admin and changed the password for the non-admin user, after doing that, I was again able to login on my site.

I got this error sometimes, but it is not frequent.

The red box you see is a means that the e-mail address you typed in did not match with any e-mail addresses registered on the site, or that the password was not recognised.  You should also be able to see a red message-box   further up on the same page with more information about the problem.  For example:

  Sorry, unrecognized username or password. Have you forgotten your password?

The most likely explanation for this error is that you misremembered the password.  This also explains why it starts working again after you login as admin and reset the password for the non-admin user.

However, I've noticed that you've definitively ruled out this explanation in your question. Fair enough, I just wanted you to make sure this is not what is happening.  I've run dozen of Drupal sites for many years (many of them with the Email registration module enabled) - and I've never seen this happen except when the credentials are mistyped.

If that is not what is happening, I have no good alternative explanation.

To progress with debugging, you may extract the {users}.pass field (hashed) from your database, and see if the hashed value changes between when you're able to log in, to when you're not.  If it is changed, then you have some rogue process (or user) that munges the pass field in your {users} database.  (If it is not changed, then this is very, very mysterious.)


How to Inject entity object in EntityForm We are trying to recreate https://www.drupal.org/project/menu_editor for Drupal 8. So our idea is to extend MenuForm and then override the form in our own way to achieve what menu_editor for Drupal 7 provides.

We created a custom module called menu_editor and there we created a route.

  entity.menu.power_edit_form:
  path: '/admin/structure/menu/manage/power_edit/{menu}'
  defaults:
    _form: '\Drupal\menu_editor\Form\MenuEditor'
    _title_callback: '\Drupal\menu_ui\Controller\MenuController::menuTitle'
  requirements:
    _permission: 'access content'

Inside MenuEditor, we extend MenuForm.

namespace Drupal\menu_editor\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\menu_link_content\MenuLinkContentStorageInterface;
use Drupal\menu_ui\MenuForm;
use Drupal\system\MenuInterface;

/**
 * Class MenuEditor.
 */
class MenuEditor extends MenuForm {

  var $menu;

  public function __construct(MenuLinkManagerInterface $menu_link_manager, MenuLinkTreeInterface $menu_tree, LinkGeneratorInterface $link_generator, MenuLinkContentStorageInterface $menu_link_content_storage)
 {
   // Trying to inject menu as suggested in https://drupal.stackexchange.com/questions/219431/entity-form-additional-arguments but not sure how we can get menu object over here
   $form_object = \Drupal::entityTypeManager()->getFormObject('menu', 'edit');
   $form_object->setEntity($this->menu);
   parent::__construct($menu_link_manager, $menu_tree, $link_generator, $menu_link_content_storage);
 }

 /**
  * {@inheritdoc}
  */
 public function getFormId() {
   return 'menu_editor';
 }

 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, MenuInterface $menu = NULL) {
   // Can get menu object over here but not sure how I can pass this in constructor.
   $this->menu = $menu;
 }

 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state) {

   parent::submitForm($form, $form_state);
 }

}

Whenever we are running this code, we get the following error.

  TypeError: Argument 1 passed to Drupal\Core\Entity\EntityForm::setEntity() must implement interface Drupal\Core\Entity\EntityInterface, null given

I do understand that using $this in the form will not help, since the constructor is called before, but I am not sure how to accomplish this.

Declare the entity form in the route via _entity_form instead of _form:

First add a form handler to the entity type:

mymodule.module

/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['menu']
    ->setFormClass('poweredit', 'Drupal\mymodule\MyMenuForm');
}

Then add the form handler to the route:

mymodule.routing.yml

entity.menu.power_edit_form:
  path: '/admin/structure/menu/manage/power_edit/{menu}'
  defaults:
    _entity_form: 'menu.poweredit'
    _title_callback: '\Drupal\menu_ui\Controller\MenuController::menuTitle'
  requirements:
    _entity_access: 'menu.update'

Now Drupal upcasts the route parameter to an entity and adds it to the form object when it is instantiated.

This is similar to content entities, only that config entities have no form modes. See How to utilize custom form modes to edit a user entity?


How can I alter methods in ContentTranslationHandler? I want to alter some of the methods here:
https://git.drupalcode.org/project/drupal/blob/8.8.x/core/modules/content_translation/src/ContentTranslationHandler.php

How can I alter just some of the methods?

Or can I override this class in any way?

There are mainly two ways

1- create a patch https://www.drupal.org/node/707484 then maybe you can apply it using composer patches.

2- override the method in your module by extending the class ContentTranslationHandler


How do I do this "join"? We have created a vocabulary with terms this way:

(main term A)
  |
  +-- subterm A1
  +-- subterm A2
  +-- ..
  \-- subterm A3

(main term B)
  |
  +-- subterm B1
  +-- subterm B2
  +-- ..
  \-- subterm B3

Easy right?

Then we've created "main terms" roles. Then we've used the taxonomy_access for those "main terms" roles. I.e. The rôle called main term A will only be allowed to create subterms of the main term A term.

Easy right?

Now we need reviewers. So we've "split" "main terms" roles in two:

"main terms A contributors"
"main terms A reviewers"
"main terms B contributors"
"main terms B reviewers"
...

And we've used the workbench module to give rights to contribute / or / review. The problem is that the rights given are not detailed enough: if you give "main terms reviewers" the right to "review", he/she is allowed to review all the "needs-review" nodes. Example: "main terms A reviewers" have the "review" right, so (like it is now) they have the right to review all "needs-review" nodes. We'd like them only to see/review only the nodes based on their roles: "main terms A reviewers" should only be allowed to review "main terms A needs-review" nodes. We could have used the workbench_access but this would implie create a section for each "main terms". This would kind of force us to duplicate all our "main terms" into "sections" then give "sections" right.

How would you do?

Maybe there's another possibility: the workbench tab is a view. So maybe it could be possible to add a filter based on the taxonomy access control, but it seems that taxonomy access control has no api, and we should have to create a manual join. Maybe there's a way to create a fully customized join based on the taxonomy access control? If so, may I ask how you would do this?

If you think I'm not on the right track, don't hesitate to give me your solution!

Thank you!

I think the easiest option is leave everything as you have it in terms of configuration and your taxonomy term values for main terms. The default Workbench (Moderation) logic isn't nested enough for you. So use it's supported hooks to extend the functionality to meet your needs.

Look at hook_workbench_moderation_access_filter()

/**
 * Allows modules to alter moderation access.
 *
 * @param &$access
 *   A boolean access declaration. Passed by reference.
 * @param $op
 *   The operation being performed. May be 'view', 'update', 'delete',
 *   'view revisions' or 'moderate'.
 * @param $node
 *   The node being acted upon.
 */
function hook_workbench_moderation_access_alter(&$access, $op, $node) {
  global $user;
  // If the node is marked private, only let its owner moderate it.
  if (empty($node->private) || $op != 'moderate') {
    return;
  }
  if ($user->uid != $node->uid) {
    $access = FALSE;
  }
}

By implementing this hook for the node access check, you can define the nested taxonomy check you're wishing Workbench_Moderation did for you. In order to find if some node has a value of a certain parent term you may find the Taxonomy Edge API module useful. Then again you might not need Taxonomy Edge.

I believe the Views workbench uses will also support this runtime check.


Generate a PDF of an admin page I was wondering if anyone knew of a way to generate a PDF of an admin page in Drupal. I've looked at a bunch of custom modules but they seem only to work on nodes, which I know are not used to generate admin items. I have a client I've given limited back-end access to that would like a "Create a PDF" button placed in one of the admin areas. Does anyone have any recommendations? Here are my specs:

Drupal version: 7.24
Modules tried: mpdf, print

Thanks! -Dave

Dear friend I suggest you if you only want provide a visual manual for your customer install pdf printer ( software that print result is pdf like foxit,nitro etc) then in each page ctrl+P (print ) and enjoy ( admin pages are not very much and not need put yourself in complex ways,It seems you want fast and short way to achive it ) :)


How can I prevent height/width attributes on images run through the theme system? My site runs now on Drupal 7.9.
On the release notes (4th position) it is reported the following note:

  Restored height/width attributes on images run through the theme system

That is exactly what I don't want, because my images get distorted.

How can I prevent height/width attributes on images run through the theme system?

History
In Drupal 6, populating width/height attributes caused a filesystem lookup (bad for back-end performance) for every image. This was fixed in #908282: Remove unnecessary I/O from theme_image() by removing the height/width attributes altogether in Drupal 7.

Images without height/width attributes are bad for front-end performance so work was done in Populate HTML image tags with dimension attributes (like D6 imagefield) without re-introducing I/O to add them back.

Answer
So you really want your images to have width/height but obviously not if they get distorted. The update functions for 7.9 were supposed to fix this, did you run update.php after upgrading to 7.9?

If you ran update.php then this might be a bug.


How to search the body of text by content type? Is it possible to create a view where the user enters a text to query, and the view will only display results for certain content types?

There is a search field called something like "Search: Search terms" which you can add as a filter criteria. Just expose it so the user can enter a search phrase.

Works only for indexed content, so make sure your index is at 100%.


Error messages appear in background page, not in dialog I have a form being displayed in a jQuery modal dialog. When the form is filled out incorrectly (ie a required field left blank) the error messages appear in the background page, not in the dialog overlay. This is not the beaviour I want and is confusing for users. How do I get drupal status messages to appear in the dialog box?

I am using Drupal 7 with jQuery 1.5.

Thanks.

To help those implement @Clive's suggestion you can do the following:

(function ($) {
  $(document).ready(function () {
    $("#dialog").dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        open: function() {
            $('.messages').prependTo('#dialog');
        }
    });
  });
})(jQuery);

Substitute #dialog with the name of the div containing your dialog's components.


Adding block to the specific content I want to have the same style of block for similar content type but the matter should be different.

For instance, I have a content type of hotel which has different fields in it and I have created a view for list of hotels. Now what I want to do is display the information of of some field from hotel(say Brochure as pdf) as a block when that particular hotel info is requested, rest as content itself.

I know one way of doing it is creating a custom block and restricting it to particular url. But it is too hectic. Is there a simple way of connecting the field from content to the block to that particular content display?

Personal observation: I have tried to place the block(say sidebar first) of content type in "block layouts". Though it shows up, no luck in placing it.

The easiest way is with a View.

Create a new view
Disable the Page that will be checked by default.
The view should take as argument the Node ID.
Also add a filter based on the content type
Then in the view, add the fields you want (File, PDF)
On the top (+ Add next to Master), you need to add a display as a block

Now, you go to /admin/structure/blocks and add the block. Filter it by Content Type.

:)

Views module - https://www.drupal.org/project/views


How do I add a custom class to a field based on another field value(boolean)? I have a Commerce product and there are two price fields. (Original price and Sale price). I would like to display original price as line-through text when sale price is available. Therefore I would like to add a custom class to a field based on another field value(boolean), I looked at this function, hook_entity_view_alter, but I don't know whether it will be good.

Anyone has idea how do I solve this?

I've never used the commerce module but that sounds possible, you need to create a module for the hook to be triggered from.

Then, with the devel module installed use dpm($build, $type) within the hook to see the correct names (I've put in dummy values in CAPS) and do something like:

function MYMODULE_entity_view_alter(&$build, $type){
  if ($type =='product') {
    if (isset($build['SALE_PRICE']['VALUE'])) {
                $build['PRICE']['attributes']['class'] = array('on-sale');
            }
        }
    }


How to implement a Views 3 exposed filter in block as a list of links, and update the view via ajax? I need to create a views exposed filter that is displayed as a list of links, and updates the view via Ajax.  I've tried using Better Exposed Filters and it will display the filter as links, but without ajax.  I've tried to figure out how to theme the default views select element (which is ajaxified) as a list of links, but haven't found a good way to go about this yet.  Any suggestions would be much appreciated.  Thanks!

Try this patch: https://drupal.org/node/1268150#comment-7393486, it's for better exposed filters and it's to make it work with AJAX.

As for the default views select element, try using an argument.


How do I find a node knowing its URL? I need to rename the node home-care/vids into home-care/product-solutions. The trouble is that I can't find home-care/vids in the dashboard of this relatively big site.

How can I find it?

I have even done a MySQL database search but results are not helpful for me.

The easiest way is almost always to visit the page you want to change, and hit the "Edit" button among the tabs.

However, sometimes this may not be practical for whatever reason. SQL-queries below:

D6

SELECT src FROM url_alias WHERE dst = 'home-care/vids';

D7

SELECT source FROM url_alias WHERE alias = 'home-care/vids';

You may in both version want to add AND language = if your site is multilingual.


clear boost cached pages as the content is changed I am using boost with Maximum Cache Lifetime = 1 Day and Maximum Cache Lifetime = 0 Sec

If i do update some content / banners, i have to clear caches at

  /admin/config/development/performance

Is this the only way? There is no way that changed nodes/frontPage cache will be automatically cleared instantly ? and all users will see new content instead of asking them to use Ctrl + f5.

any clues
thanks

You can use the Cache Expiration module to expire caches when content is updated.

The expire module provides the events that fire when content is updated and other caching modules hook into those events and clear their caches.

The boost module supports the expire module's events.

Once installed, you can configure the module at admin/config/system/expire.


Default value for the same field, different depending on content type I am building a website and have 3 content-types.

Type A
Type B
Type C

I built these content types one after another, and used existing field when creating the content-type field Field.

My question is, how do I set a default value for Field for each of my content-types ?
Right now when I set a default it is default for all my content-types.

I want to have

Type A -> Field = value 1
Type B -> Field = value 2
Type C -> Field = value 3

You can easily achieve you goal with the rules module, as @pico34 wrote in his answer, but use the trigger Before saving content instead of After saving new content.

Alternativey, if you need to do that programmatically, you can define your default values in just a few lines of code using hook_node_presave()

Example

/**
 * Implements hook_node_presave().
 */
function YOUR_MODULE_node_presave($node) {
  // set the value of field "field_somefield" in case of node type: a, b or c.
  if (in_array($node->type, array('a', 'b', 'c')) && empty($node->field_somefield[$node->language][0]['value'])) {
    switch ($node->type) {
      case 'a' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for A';
        break;
      case 'b' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for B';
        break;
      case 'c' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for C';
        break;
    }
  }
}


How to pass computed data from Theme preprocess functions to Twig templates? My general problem is this: I need to compute some data from PHP, usually using Drupal APIs, then pass computed values to a Twig template (in order to showing it).

For example: I have a template named node--dog.html.twig and inside this template I need to show the total count of Dogs I have inside the website. To do this I will compute from PHP the total count, using the Drupal::entityQuery API. But then I have to pass this computed value to the Twig template.

I tried to use a theme's preprocess function inside the file <my_theme>.theme:

function customtheme_preprocess_node__dog(&$variables) {
  //
}

From here I'm able to do all PHP computations, but I couldn't find any documentation explaining how to pass data to Twig views. Can I use the $variables object? Is there any drawbacks? Is there a better approach?

$variables is an array, not an object.

But yes, it's the one and only way to pass additional data to the template. Anything you put in there is available in the template then. $variables['hello'] = 'world'; can be printed with {{ hello }}.


Get arbitrary user entity with tokens Is there a way to retrieve an arbitrary user entity via tokens inside a node field?

For example:

Let's say I have a field name Source, which contains a reference to an external news publication.

I have a user on my site named "Jane Doe".

I want to be able to put something like this in the source field.  The example is a little fudged b/c I don't think Tokens has a "link" type token, but the question is more about getting data for an arbitrary user:

New York Times, citing [user:link:Jane Doe].

And have that rendered as

New York Times, citing Jane Doe.

What I have tried

I've attempted this in the node body field (using the token_filter module).

I can get data for the current user with, such as with the token [current-user:url].

But I haven't figured out how to get data for an arbitrary user.

I've tried:

[user:url:1]
[user:url 1]

There isn't a token that, given a user ID, would return data about that user account. current-user returns data about the currently logged-in user, while user returns data about the user account passed to the function (in Drupal 7, or the method in Drupal 8) that replaces tokens with their values: token_replace().

It would be possible, for a module, to implement a token that returns data about every user accounts. With such a module, for example, users:1:name could return the username for the user account #1, while users:2:name would do the same for the user #2.


Bulk generate hierarchical vocabularies I have a quite big website with restaurants. I'm saving their data (like coords, city, street, country etc.) with CCK fields.

Fields City and Country are connected with vocabularies (named Cities and Countries). What i'm trying to do is to somehow bulk save all the Cities terms as a child elements of a term from Cities taxonomy. So if i have a restaurant located in Barcelona, Spain, i wan't to save a Barcelona term (from Cities vocabulary) as a child element of Spain term (from Countries vocabulary).

Have you any ideas how can i make something like this ?
thanks in advance.

I recently created a hierarchical taxonomy on our main premium site using some data exported from our SQLServer and used Taxonomy CSV import/export to import the file. I used LibreOffice Calc to massage the data into place, then exported from LibreOffice to CSV. A Google Docs version of my data  is available, if you're interested.

Two things I remember doing:

I choose to import as a 'taxonomy_manager' file
Any term which will be used as a parent needs to appear at the top before any of its children appear.


Target individual items of a multi-value field in my page template I created one field for an image and In the field setting, I made allowed number of values to 2 (please find the attached screenshot

)

So my question is, how can I add both the images in a different div tag in my page template.

Or, how can I target first and second image in my page template.

There are many ways to achieve this. Given you use a custom or sub-theme you'd follow Twig Template naming conventions and create your own field--node--MYFIELDNAME.html.twig template. And then simply adjust the markup according your needs.

See Classy's field.html.twig for reference and its for-loop you simply can customize:

{% for item in items %}
  <div{{ attributes.addClass(classes, 'field__item') }}>
    {{ item.content }}
  </div>
{% endfor %}

To target the second item in a multi-value field inside page.html.twig use the following snippet (it starts to count with 0, so that 0 is the first and 1 is the second item).

{{ node.field_MYFIELD.1.value }}


How do I enable comments for forum like statuses module? i used this module  project statuses  (drupal 7)
i want that write comment for forum like above module.
how can i do assign statuses style to comments forum?

You cant, the statuses module has quite a different concept and doesn't have anything to do with content-types commenting(e.g drupal forum), but if your problem is just to make your forum comments look like statuses, you can simply achieve that via some styling or templating your forum comment tpl file (better approach). for the sake of Ajax, you can use Ajax Comments module, but its not so much stable yet.
if you still need further help don't hesitate to ask!


How to flag if a 'webform' exists on a page? I an fairly new to Drupal and have a custom module in which I need to write some PHP logic. It needs to insert a flag basically, on any page which contains a 'webform' of any kind.

I see the webform api page, but I don't see anything which would just tell me if a webform is on a page.

I have tried this if statement to insert my little flag - but it is showing on every page.  I assume because drupal calls every page a form?  so technically my code bit is flagging every page?

if (function_exists(form_id)) {
    $variables['s.event4'] = "event4";
  }

Any help?

This appears to be a preprocess function. If it's hook_preprocess_page(), you can do this:

function hook_preprocess_page(&$variables)
{
  if(isset($variables['node']) && $variables['node']->type == 'webform')
  {
    $variables['s.event4'] = "event4";
  }
}


drupalSettings object not showing for anonymous users. core/drupalSettings is added as a library dependency I'm stumped on this one. I’m having an issue where the drupalSettings object is empty when not logged in. Works fine when I am authenticated. - core/drupalSettings is in theme’s *.libraries.yml file.

I've tried

Cleared cache (1million times).
Triple checked the YAML indentation
Verified that the settings are being added when stepping through via Xdebug
The JS file that I'm adding is via ['# attached'] works great

What am I missing here? Where to start troubleshooting? I'll owe  if someone can help point me in the right direction.

themename.libraries.yml

views-load-more:
  js:
    js/views-load-more.js: {}
  dependencies:
    - core/drupalSettings

In my themename.theme

function themename_preprocess_views_view(&$variables) {
  if (!empty($variables["pager"])) {
    $view_selector = '.view-' . $variables["id"] . '.view-display-id-' . $variables["display_id"];
    $view_content_selector = $view_selector . ' .view-content';
    $view_pager_selector = $view_selector . ' .pager';

    $variables["view_array"]["#attached"]["library"][] = 'themename/views-load-more';
    $variables["view_array"]['#attached']['drupalSettings']['themename']['viewsLoadMore']['viewSelector'] = $view_selector;
    $variables["view_array"]['#attached']['drupalSettings']['themename']['viewsLoadMore']['viewContentSelector'] = $view_content_selector;
    $variables["view_array"]['#attached']['drupalSettings']['themename']['viewsLoadMore']['viewPagerSelector'] = $view_pager_selector;
  }
}

Note that the themename/views-load-morelibrary does get attached when anonymous (I can see the JS file within it).

And also note that this works perfectly when authenticated. This tells me that the drupalSettings dependency isn't working even though I'm declaring this.

How do I troubleshoot this?

Solved the issue... and the answer is weird...

within the html.html.twig file, we have a <div class="body-inner"> tag that wrapped the <js-bottom-placeholder token="{{ placeholder_token }}"> placeholder.

For whatever #drupalWTF reason, if this placeholder tag is wrapped inside of a div, drupalSettings will load an empty object. Once I moved it directly underneath the body tag, it worked fine.

Hope this helps someone!


How to add conditional HTML meta tag using drupal_add_html_head to force only IE9 into compatibility mode? Long story short: Some quite nice interative SVG map works fine on every major web browser thanks to svgweb. Except IE, of course. Every IE (8, 9, 10) needs a particular workaround. IE9 would only work when I force it into compatibility mode. Unfortunately I can't find a way to use drupal_add_html_head with #tag' => meta and #prefix and #suffix to only take effect in IE9. drupal_add_html_head works fine, but #prefix and #suffix discard it. So that doesn't work:

$meta_ie_render_engine = array(
  '#type' => 'html_tag',
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'X-UA-Compatible',
    'content' =>  'IE=7',
  ),
  '#weight' => '-99999',
  '#prefix' => '<!--[if IE 9]>',
  '#suffix' => '<![endif]-->',
);
drupal_add_html_head($meta_ie_render_engine, 'meta_ie_render_engine');

Is there another way to use drupal_add_html_head with tag => meta conditionally? Or another drupal-like alternative?

Had similar problem:

function detect_ie() {
    if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) {
        return true;
    }
    else {
        return false;
    }
}

above will detect if IE in general. You will need to change 'MSIE' accordingly (something  like 'MSIE9' but not sure if thats correct).

Then what i did was

if(detect_ie()) {
  $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
  'http-equiv' => 'X-UA-Compatible',
    'content' =>  'IE=EmulateIE7',
     ),
  );
drupal_add_html_head($element, 'IE_cr_ap');
}


Override templates for one view page or block I am trying to figure out if there is a way to override the base templates for one view.
I created a page with a view called 'Promotions'.
I need to override the views-view-field.html.twig, views-view-fields.html.twig, and views-view-unformatted.html.twig for just the one view/page.

I read about putting it into your custom theme's template folder in it's own folder that mimics the page name.
In my case, following the example it was views-view-fields--promotions--page.

The overrides work but they work for all the views (pages and blocks) that I created.
Can you narrow it down to just one view/page?

Yes.

The pattern will be something like views-view-promotions--display_name.html.twig

See https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.2.x

Also, I recommend you activate Twig debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates) to see actual suggestions.


minifying css in drupal and getting the original source css We have inherited a drupal 7 installation.  We have the source code. When we look on the front end there are series a of minified css files named like below. We are interested in getting the original source css files. I have no experience in drupal css minification. Does this kind of output look like out the box drupal minification. If so is there a location that specified the exact css that was used?

 <link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_hYCLW089C9S9sP3ZYkuG6R-Q5ZHbEhblZBFjwZ_bE_I.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_YYoEBheeHSoZ5EBVRncs-cuvNClW-5FNm_tmYaEdRwM.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_5-5L742ZPRdlG5Jq9Yz3AIRJ3MBxYr6H_bolFIoqd68.css" media="all" />

Each css file that we see on the front end is collection of multiple css files.

Yes that looks like Drupal's built in CSS aggregation.

The easiest solution would be to turn aggregation off temporarily. Then you'll see the original sources in the markup.

You can turn it off at the admin/config/development/performance page.


How do I get Drupal to use table prefixes so I can install multiple drupal installations in the same database schema? My webhost is pretty limited, and I only have one database user & schema. I would like to install multiple drupal installations on this database schema.

How do I tell each installation to prefix its tablenames with a given string?

In the settings.php file, a normal setup might look like

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

The only difference is that you add a 'prefix', like this:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => 'site1_',
  'collation' => 'utf8_general_ci',
);

Make the prefix different in each settings.php site, and you can have as many sites as you want within the same database.


Date module: detect if an end date was set I have a content type with a date field. It is setup to collect an end date (optional). The field type is Date (UNIX timestamp).

The field is to store "experience" as (from) January 2011 - (to) March 2012.

If I don't check the "show end date" when creating content, the end date is the same than the start date. But in my case, I sometimes need to collect an end date that would be the same than the start date (January 2011 - January 2011).

So how do I know if that "show end date" checkbox was checked?

Right now here is what I get when the end date is the same than the start date:

value (String, 10 characters ) 1443650400
value2 (String, 10 characters ) 1443650400

And this is what I get when the "show end date" was not checked:

value (String, 10 characters ) 1443650400
value2 (String, 10 characters ) 1443650400

I'm going to take a guess and assume you have the end-date defaulting to the start-date in the Date field, field-settings?

That way if they click the checkbox for Show End Date, they have to provide a value for it. otherwise it will be empty; essentially letting you know if the checkbox was checked or not.


How can I expose Drupal data to external applications? How can I expose data from my Drupal site via web services to external applications such as iPhone or Android?

One of the most popular solutions is the Services module. It takes a little bit of set-up and know-how but it's very flexible in what it can output and what formats you need it. It's the solution we used at Palantir.net to provide data to our DrupalCon Chicago Android and iOS apps.


Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() I tried a lot to get this warning solved, but end up with nothing. Can anyone look into this warning issue.

Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 175 of /var/www/html/std-build/httpdocs/includes/entity.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /var/www/html/std-build/httpdocs/includes/entity.inc).

This is related mostly to the issue in your code or bug in the module which you're using.

Basically you should validate your DrupalEntityControllerInterface implementation, and you should not patch your Drupal core as suggested by @vgoradiya since it's not a bug in Drupal core.

  Consensus seems to be that issues arise with bad data and should be corrected at the offending module level, not by adding a safeguard to DrupalDefaultEntityController that would mask deeper problems. Having an error here is a warning to developers that they are using the D7 APIs incorrectly. - @jessebeach

So the challenge should be to identify which module implements Entity API incorrectly.

See also:

array_flip() [function.array-flip] issue in DrupalDefaultEntityController / entity.inc which is not a bug, but closed as 'works as designed',
Entity API Tutorial,
How to create a new entity type
Entity API at Drupal Groups
Creating your own entities with Entity API

If you're developer of the module which causing the issue, please check the followings:

Make sure your array won't contain NULL values, otherwise use the following trick:

$arr = drupal_map_assoc($arr, function($v) { return (string) $v; });

Check the Examples module (entity_example) for Developers how to implement entities.
You're loading entities using the right $ids structure.
Use debugger or debug_backtrace() to debug the issue.


How do I programatically create a Bean 'instance' in code? I am trying to make a sort of hook_setup_beans() function (similar to hook_setup_blocks()) to create some bean instances by default when a user turns on a bean_example module I am making. This would be called from hook_install().

Is there a standard path for doing this?

I am playing with bean_create() and bean_save() right now.

Thanks

p.s. I also asked this at https://drupal.org/node/2173783

Creating bean instance programmatically.
https://drupal.org/node/1436186

<?php
  $bean = bean_create(array('type' => 'my_bean_type'));
  $bean->label = 'Administrative Label';
  $bean->title = 'Bean Title';
  $bean->delta = 'bean-machine-name';
  $bean->field_block_content = array(
    'en' => array(array(
      'value' => '
Text
',
      'format' => 'wysiwyg_editor',
    )),
  );
  $bean->save();
?>


Creating Image Captions using File Entity module The purpose is to create image captions to all images uploaded in Drupal.

What I did:

installed media 2.0 / file entity 2.0 alpha2
added a new field called 'captions' in the image file types:
admin/structure/file-types

Now I can add captions in the body field images.

I need the captions to be visible for other fields like image upload field.

How to exposed file_entity's fields in the content type form fields?

Exposing file_entity fields in forms

A simple solution to this issue is to change each upload image field's widget type from default 'Image' to 'Media file selector'. Thus throught Media all file fields can be edited.

An alternative solution is File Entity Inline (https://drupal.org/project/file_entity_inline) which exposes the file entity fields as form fields.

Displaying file_entity fields in pages

If file_entity fields are not displayed in the page, test first if they are exposed using Views (field image). If you want to display them in a simple page with image fields already created try to workaround by adding new theme suggestions / template: e.g. file--image.tpl.php

The theme suggestions provided by the File Entity module are:

file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}


Run callback after Views exposed filter AJAX I feel like I'm doing something really wrong here. I have a View block which has an exposed filter. Since it is in a block I have to use Ajax. I'm trying to run some JS on the views result but can't get anything to happen when the ajax call completes.

To try and keep this as simple as possible I have created a test.js file with only the following code:

(function ($) {
  $(document).ajaxComplete(function (e, xhr, settings) {
    console.log('test');
  });
})(jQuery);

I add this with my theme's template.php file but when I filter my view and the results update with ajax, this code does not seem to run. I can't work out why not.

EDIT: I managed to get this to work by moving the code inside my_view.tpl.php but I'd be keen to know why it doesn't work in an external file.

JS events need to be bound when the document is ready. Drupal handles this for you if you use behaviors:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $(document).once('mymodule-ajax').ajaxComplete(function (e, xhr, settings) {
      // ...
      });
    }
  }
})(jQuery);


How to add delete link to recent comments block? I'd like to add a delete link to the 'recent comments' block on my dashboard. How can I do that? Is it possible to edit the view aswell?

You can override the theme_comment_block(): You can find a good tutorial here: http://www.webomelette.com/theming-comment-block-drupal-7

I instead liked to just replicate the functionality in a Views block, and then styled the block to look the same way. I felt it gave me more control, and I try to avoid hacking up core blocks.


How do I set a visibility rule for the individual menu block items? Is there a way of setting visibility of menu items itself based on the URL?

With the Panels module, we can set visibility of the panel section based on the URL or other rule. How can I set that kind of rule for individual items of a menu block?

For example, the menu block has the following items: Item-1, Item-2, Item-3, Item-4. If the URL is node/,  display all items; if the URL is node/string-1,  display Item-1, Item-2, Item-3; if the URL is node/string-2, display Item-4, item-5, Item-6.

Step 1

Create 3 blocks:

Block 1 containing links pointing to all items like Item-1, Item-2, Item-3, Item-4, ... etc.
Block 2 containing links pointing to all items Item-1, Item-2 and Item-3.
Block 3 containing links pointing to all items Item-4, Item-5 and Item-6.

Step 2

Enable the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

Step 3

As per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown for the listed pages).

So create 3 Rules Components, each with a Rules Condition that performs a Text comparison with Parameter: Text: [site:current-page:path] and an appropriate Matching Text for the URLs like:

(NOT node/string-1 AND  node/string-2), to show Block 1.
node/string-1, to show Block 2.
node/string-2, to show Block 3.


Twig's slice filter behaves unusual for non English languages I have used slice filter to display few number of Japanese alphabets from a sentence.

{{ desc|length > 65 ? desc|slice(0, 65) ~ '...' : desc }}

But sometimes it slices very early when a Japanese full-stop appears and the preceding sentence has long length for full-stop to appear.

I have 3 patterns to show:

1) When I have following text to slice:

  何もほかけっしてその納得学というののために見なん。ちょうど今に話家はまるでその使用ませですくらいが出ているんがは反抗おっしゃれなけれでて、さらににはなっましましなん。主義にみでのはけっして前を余計でですた。

It slices the above thing as:

  何もほかけっしてその納得学というののために見なん。

2) For following string

  同時にネルソンさんに自覚文字当然発展のするでがたある馳何か相当がという実お話しませますたならで、この今もあなたか世の中鷹狩を使いこなすので、岡田さんの事に政府の私にもしご意見と云えて私宅にご記念になさいようにどうしてもご話の始めんたて、最も勢い発音へ云わましてならたのを立つないまし。

It slices to:

  同時にネルソンさんに自覚文字当然発展のするでがたある馳何か相当がという実お話しませますたならで、この今もあなたか世の中鷹狩を使いこ...

which is perfectly sliced to 65 alphabets.

3) For following string:

  教師でしかしネルソン君にまたはそれだけ聞いうのうたう。向さんもさっそく国家をしばした事べくですた。（また考を云っ以上でしょですたてたも間違っあるたらが、）そう好かあり相場を、スコットの冠詞じゃしでみに対して、主義の下宿は前の他まで知れ当る気に行かませて刺戟院叱らて来るですというお自分ないものん。

It slices to:

  教師でしかしネルソン君にまたはそれだけ聞いうのうたう。向さんもさっそく国家をしばした事べくですた。

Is there any way to solve it or any other solution to achieve this?

As the trim was enabled from both twig as well as display format, it was not working. So keeping the display format for that field to Default, it solved my issue.

For other users who might face such problem, just keep in mind to set only single trim (either from back end or front end side)


How to create a dynamic date format? I'm fairly new to Drupal and I'm struggling to find where and how I should approach the problem I'm describing below. I suspect I will have to dive in the code but that's ok I'm comfortable with PHP.

I have a content type "Event" with a "Date & Time" field called "Event Start Date". I've configured the Date format to be "l, F d, Y - h:i a", but it's not exactly what I'm looking for.

I need to add a condition to my date format so that it doesn't display :00 when the minutes are at 00.

For example

Tuesday, January 25, 2017 - 9:15 am
Tuesday, January 25, 2017 - 9:00 am

should display

Tuesday, January 25, 2017 - 9:15 am
Tuesday, January 25, 2017 - 9 am

How and where should I be doing this in code?

Preferably, I would like to be able to tell when to apply this rule.

I think the best solution is used custom field formatter for date type:

/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
      'mymodule_custom_datestamp' => array(
          'label' => t('Custom datestamp formatter'),
          'field types' => array('datestamp'),
      ),
      'mymodule_custom_date' => array(
          'label' => t('Custom date formatter'),
          'field types' => array('date', 'datetime'),
      ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'mymodule_custom_datestamp':
      foreach ($items as $delta => $item) {
        $tmp = (integer)$item['value'];
        $minutes = (integer)date('i', $tmp);
        if(empty($minutes)){ //you'll update only values with :00
          $element[$delta] = array('#markup' => date('l, F d, Y - h a', $tmp));
        }else{
          $element[$delta] = array('#markup' => date('l, F d, Y - h:i a', $tmp));
        }
      }
      break;
    case 'mymodule_custom_date':
          .....
          break;
  }

  return $element;
}

You can use it anywhere and It uses the least resources.