How to determine the priority of css files in info file for a theme? I have several css files in a theme info file. Suppose i have two definitions of h2 in different files? How to configured the files so I manage to get the h2 definion I want?

I edited the question as I do not get a solution yet. The question refered as an answer is problaby one of the reasons. So I first set the order of the files oke. They are now oke. Other changes are reflected.

So specific.... I now have two H2 definitions in 1 css file.

h2 {
    font-size: 19px;
}

and

.page-shop .view-header h2 {
    font-size: 100px !important;
}

But still the first is applied in the shop page..

Any suggestion?

For everybody who is reading this; I found my solution:

I'm using Sublime Text editor for css styling. As everything in the syntax had the good color I thought the file is build up good. But in some try and error I saw one line like below:

form-item ( font-size: 10em;}

Note that instead of openening with a { it is opening with a (

And because of this the rest of the css file is not processed well.

The CSS files are processed in order, so if your .info file looks like this:

stylesheets[all][] = css/foo.css
stylesheets[all][] = css/bar.css

Then the styles from foo.css will be included before those from bar.css. The same applies whether each CSS file is included separately, or whether they're aggregated.

If you're still unsure which rule will be applied at that point, you need to read up on CSS specificity, as Drupal doesn't affect it.


How to manage catalog display of images for Commerce 2 product variation I have created a custom product type and its variations are created with attribute 'Size'. If I create a new product with its multiple images, then the catalog view shows these multiple images instead of a single image.

Below is the Product type variation 'Manage display' settings.

In future anyone need the answer, The image fields's format to be set to 'Image delta'. If image delta value set to 0 then the first image will be displayed and if it is set to 1 then the second image is displayed and so on.

Delta appears for the fields that has multiple values and delta refers to the order by which it appears.


Selection of Nodes Based on Taxonomy Terms Percentages I am developing a huge Questions bank, where teachers submit questions,which actually are nodes,and the topic subjects are taxonomies..NOw at the end of the term, teachers generate question papers of 100 questions each, but based on percentages of topics,say if it mathematics paper, so 30 percent questions from algebra(a taxonomy term) 20% from SETS( Taxonomy terms)....so how can i get this done?i am currently using database level custom procedure, but it is hardly being maintained...any suggestions plz

With so many different possibilities that might fit your project and its needs, I'll try to address the forks in the road with how you could do this in drupal.

You most likely wont find any appropriate functionality for this task built into drupal or a contrib module but it is simple enough to implement yourself.

Option 1 Keep it in the database, but still in drupal.

Build queries using the Database API (most likely the static method as it'll be quicker to get going, instead of the dynamic method), depending on your creativity you can loop through each taxonomy term and execute a number of possible queries to get count() results based on timeframes as well as other criteria. You could also have a specific set of queries that you run on the taxonomy terms as a whole to get a view of the whole database table, instead of looping through each term. Whichever appeals to you, this list of common mysql queries has aggregates, statistics, comparison, frequencies and just about every other basic math centric query to get you started.

Option 2 Maintain your numbers in close to realtime in a node, variable or database table

This option is really if you'd prefer to do most of your work not just on the PHP side of things but in just PHP. The example above puts the burden on your SQL server but all of your logic still actually resides in the PHP (instead of stored procedures).

This would be my second choice of the two. Instead of running a lot of heavy queries on a regular interval, simply write some code to keep track of the total numbers of each taxonomy term as they are added or removed (you can use  a hook from the node API such as hook_node_presave() - any number of hooks to quickly sniff what taxonomy terms are being applied if you don't know where to do your addition and subtraction of the taxonomy terms as they are added or removed).

If you really want to hand this to drupal from your stored procedures...

Get ready to do a little battling with drupal depending on how light or heavy your code is. Queue API and batch API can help you with large background processes, otherwise you'll want to ensure things stay trim and quick if that means incremental updates to your taxonomy statistics or putting time constraints on your processes.

Good Luck!


hook_user_insert not working I am new to drupal.
When user register into my website I need to get the users details and passed to a thirty for server .
I am trying the following hook,

function compass_preprocess_user_insert(&$edit, $account, $category) {
  db_insert('test')
    ->fields(array(
      'accountid' => $account->uid,
    ))
    ->execute();
}

here compass-my theme name
Please help me...

hook_user_insert() can only be implemented in a module, not a theme. Themes are just for styling/marking up content that modules produce, they shouldn't contain advanced logic like that.

You'll need to add a custom module and implement the hook in there to continue.


Using oauth_common in a module to authenticate with a web service? I'm wanting to use my Drupal 7 site to communicate with an external API that must be authenticated via 3-legged OAuth.

It seems there's a lot of documentation around about using Drupal as the OAuth provider (Via the OAuth project), but very little about using its API to do things like authenticate a Drupal site with an external web service. There's an old complete tutorial, but this doesn't list any of the functions that oauth_common provides, nor even really any code with how to build an OAuth session with the module.

Any help? Moreover, is there a "Drupal Way" of creating OAuth sessions?

(If it helps, I'm doing stuff with Magento and using the examples here as a base.)

Have you ever try to use OAuth Connector. It allows us to create the comsumer/application/connection to Twitter, Facebook... or another Drupal website. For my own purpose. I used that for fetch the data from Drupal 6 Services 3 by using this module in Drupal 7 and some extra code and it worked fine.


How do I set a variable in the configuration file setting.php and use it from code? How do I set a variable in the configuration file setting.php and use it from code?

in settings.php:

$conf['yoursite_something'] = 5;

Then, in your code:

// Second argument is the default.
variable_get('yoursite_something', NULL);

Make sure to prefix the variables, either with the module you're using it in or with the site name.


How to translate mouse overs? I am using the field 'image' and have the 'alt' and 'title' options for the image. The 'title' shows on mouseover. How do I translate this? Or if it isn't translatable how can I show another field that is translatable as the mouse over?

The title mouse-over is translatable. I needed to enable the content type-> edit -> publishing options -> multilingual settings and it works.


"public://" is not resolved correctly to the full path In my script, public:// resolves to http://./sites/default/files/test.txt

This is the code I used to get the actual value for public://:

$path = file_create_url('public://test.txt');

$GLOBALS['base_url'] is also resolving to http://.

Any idea why the domain is missing from the public://?

Thanks

The reason there's no $base_url is because the script you're running isn't in a HTTP context; when Drupal bootstraps, unless you've specified a $base_url in settings.php, it retrieves this value from $_SERVER['HTTP_HOST'] which doesn't exist in the command line context.

To remedy this, you can set the $base_url in your settings.php or, if you're running Drush, use the --uri argument.

drush scr --uri="http://www.example.com" my_script.php


How to display comments and comments form on custom node pages I am new developing my first ever site in drupal. Along the line, due to the requirements of the project I had to create custom node pages (template files) instead of the default ones in drupal. For example my site has content type 'Article' and the template file for that is page--node--article.tpl.php. In page preprocess, I switch to the right page template with this code

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

Now, my problem is how to display comments and comments form.  The drupal print render($content['comments']); is not working. I have installed Devel and I can see the comments and comments_form variables in the back end under the Render tab but I do not know how to access and display comments on the front end either by using these variables or another means.

Please help.

EDIT
After digging into variables available on the page I was able to get the form to show using

print render($page['content']['system_main']['nodes'][$node->nid]['comments'])

but when I try to submit a comment an alert comes up saying OK and the comments  cannot be found when i check in the back end to approve. Any thoughts pls

Add your theme hook suggestion in Node preprocess hook instead of Page Preprocess

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

Now $content variable should be available for you.. Please remember Clear Cache


How to provide content type in module for Drupal 8? How do I write a module that provides a content type in Drupal 8?

For a module name my_module and a content type called awesome_page, the directory structure would look like:

my_module/

my_module.info.yml
config/install/

node.type.awesome_page.yml

And the file contents would be:

my_module.info.yml:

name: Awesome page content
type: module
description: 'Add awesome content type.'
core: 8.x
dependencies:
  - node

node.type.awesome_page.yml:

type: awesome_page
name: 'Awesome page'
description: 'Awesome pages are a little better than other pages.'
help: ''
new_revision: false
display_submitted: true
preview_mode: 1
status: true
langcode: en

For several other examples, find all modules in core that provide new content types: find . -iname "node.type*"


Modify content type output I'm trying build a custom page for my content type with Views. What I've done so far:

Created a grid display type template, I change columns to bootstrap columns;
Hooked up a a template for teaser node--tutorial--teaser.tpl.php in template.php file.

What I would like to do next:

Modify print render($content);
Arrange my node teaser fields in this order: image, title, summary, other fields.

However, title seems to be seprated from content and not avaible as a field in teaser display settings.

How can I modify content output to include title and modify it's markup? What's the best way of acomplishing what I need?

Thank you

EDIT: Thanks to everyone for suggesting DIsplay Suite, but really after trying it out it just makes things more confusing... I'd much much rather assign some variables in a php files and arrange them the way I want in a template file.

I can't say this is the best way, but may be it may help you.. So, my approach is like this:

function MYMODULE_preprocess_node(&$variables)
{
  if ($variables['teaser'] && $variables['type'] == 'TYPE') {
    $titleField['title'] = array(
        '#markup' => '<div>' . $variables['title'] . '</div>'
    );

    array_push($variables['content'], $titleField);
    ...
  }
}


Can not add content to panels Environment:

Drupal 7
Modules: Page manager, Devel generate, panels in-Place Editor, Panels, CTools, jquery-module

I defined a 3 column design but I can not add any content to any panel (superior, left side, middle column, right side...)

Any idea what it can be?

So it turned out to be a jquery version problem.

Here is how I sort it out.

I have installed the jQuery Update module with version 1.10 selected and I had to change it to version jQuery Version 1.7 and all the gotchas faded away.

I hope this help to anyone else!

(Module jquery_update)


Cannot export theme settings to the .info file I am using Drupal 7. After modifying a setting for my theme in the Appearance menu, I get the following alert message on my site's homepage:

The settings for this theme are currently served from a variable. You might want to export them to your .info file. This is optional and can be done the Drush command 'drush omega-export'.

However, when I try to run the drush omega-export command, it fails:

$ drush omega-export
The drush command 'omega-export' could not be found.  Run `drush           [error]
cache-clear drush` to clear the commandfile cache if you have installed
new extensions.
A Drupal installation directory could not be found                         [error]

This happens even if I run as root. I ran the drush cache-clear drush command successfully, but that unfortunately did not fix the issue. How do I fix this?

The "omega" theme is the base theme for my theme. It needed to be Enabled, but not set as the default. After enabling the theme, the drush omega-export command worked successfully.


How to implement a new drush topic? I just read the Drush Topic - A Wealth of Information article about the topic section in drush commands and I have added this topic to my drush commands:

  $items['docs-onlyone'] = array(
    'description' => 'Info about Only One.',
    'hidden' => TRUE,
    'topic' => TRUE,
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'callback' => 'drush_print_file',
    'callback arguments' => array(dirname(__FILE__) . '/README.txt'),
  );

The problem is that the only way to see the new topic in the topic list once I use the drush topic command is if I place my onlyone.drush.inc file inside the .drush folder.

Is this normal? I can't see the topic if I have my onlyone.drush.inc file inside my module folder.

Make sure that you have selected the Drupal site that your module is in (e.g. with an @alias, via --root and --uri, or cd /path/to/drupal/sites/default), and also ensure that the module is enabled. Otherwise, Drush will not find and load the file.


Field API versus custom code If I need to add custom fields only to user profiles, is it better to create a module that uses the field API, or a module that uses its own code to show the custom fields at a custom URL and to save the data in its own database table?

The field API doesn't implement the permissions necessary to decide which fields are visible to which users; is that a reason enough to implement custom code?

Implementing a custom Field API field is quite simply, there are already many tutorials and example modules available. One of the advantages is that it provides all the storage handling for you and it can provide handling for multiple values and so on.

Note that Field API provides the framework for field level access permissions but it doesn't implement it. Just like node_access. So that's not a reason against using it.

See http://drupal.org/project/field_permissions for a project that provides an implementation for that.


Why the menu items to edit a specific vocabulary and terms does not show up in administration tool bar? I created a new user with specific role and permissions to CRUD 1 content type and 1 taxonomy vocabular and terms. The thing is that the administration menu item does not show up for the taxonomy pages, logged in as that user i only see the Content tab > Add content > My content type

The user has permissions to adminiter vocabularies and taxonomies and edit/delete terms for its specific vocabulary. Has access to administration toolbar

If i put the URL directly i can edit a term, even create a new one for the specific vocabulary

Do i need to set up another permission?

I'm using admin_toolbar module

You need to add 2 more permissions as below

1) 'Use the administration pages and help' under System
2) 'Use the administration toolbar' under Toolbar


Setting Values for TableSelect checkboxes Is there anyway to set the default values for checkboxes? What im trying to do is set a specific value for each checkbox so it will delete the selected row in my db, however table select seems to just go off of its own value instead of the one I am trying to assign them with.

    function auto_form_records($form, &$form_state) {
//Table header
    $header = array(
        '',
        'First Name',
        'Last Name',
    );

//DB query
    $dbresult = db_query("SELECT * FROM {auto}");

        foreach ($dbresult as $dbrow) {

            $select_id[] = array(
            $dbrow->id
            );
            $rows[] = array(
            $dbrow->firstname,
            $dbrow->lastname,
            );
        }

//Table select Form
    $form['checkboxes'] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $rows,
        '#empty' => 'No Records were found.',
        '#default_value' => $select_id
    );

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

//Delete row in db.
    function auto_form_delete_row($form, &$form_state){
        $id = $form_state['values']['checkboxes'];
        db_delete('autoleads')
      ->condition('id', $id)
      ->execute();
    }

//Submission
    function auto_form_records_submit($form, &$form_state){
        $data = drupal_set_message(t(dvm($form_state)));
        //auto_form_delete_row($form, $form_state);
        return $data;
    }

I would think that me passing the string into default_value would atleast give me the values I am trying to pass through, but its not...

Any suggestions is appreciated.

You just need to add your id as the key for each item in your $rows array, e.g.:

foreach ($dbresult as $dbrow) {
  $rows[$dbrow->id] = array(
    $dbrow->firstname,
    $dbrow->lastname,
  );
}

Then in your submit handler run:

// Limit the checkbox ids to only those selected by the user
$selected = array_filter($form_state['values']['checkboxes']);

db_delete('autoleads')
  ->condition('id', $selected, 'IN')
  ->execute();

And you should be good to go :)

There's no need to use #default_value unless you want to pre-select some of the checkboxes for the user. If you do, just set #default_value to an array of the ids that you want selected initially.


Site off-line with correct data in settings.php I'm trying to set up a development folder for a Drupal6 already existing website.

Under htdocs/sites/<website>/settings.php I have the following line in order to connect to the drupal6 DB:

$db_url = 'mysql://root:<mysql_password>@localhost/<drupal_db_name>';

If I try to enter mysql using the same login data, I can do it without any problems, so I know this data is correct.

But I still keep getting the "Site off-line" message.

I've also tried using settings.php in the "default" folder under htdocs/sites/, but it didn't solve the problem.

Any suggestions of what could I try in order to fix or debug this?

UPDATE: I have not taken the site down through admin. I've taken the folder from a production server (where it's working correctly), and I've placed it into another server. I've also made the same thing with the DB.

You probably haven't installed and/or enabled the PHP MySQL extension (it's a requirement). You can check by creating a phpinfo() page and searching for 'mysql'. If it's not there, you need to install and enable it. You don't say what server you're using, but if it's Ubuntu or a similar Debian-based variant, you can do this:

$ sudo apt-get install php5-mysql
$ sudo /etc/init.d/apache2 restart

If you're on another platform, the steps will be a bit different, but you get the idea.


Trying to theme my user login/registration/password reset pages in Drupal 7, going bonkers What seems like it should be a very, very simple task -- theming the user login, registration, and password pages in Drupal 7 -- is turning out to be a Kafka-esque nightmare. I can't figure out what I'm doing wrong, and am wondering if I'm slowly regressing into a newt in the process.

So there's a ka-billion how-to posts all over the place about how to do this (all of the posts I've read seem to be derived from this page here), and a ka-trillion success stories, but sadly, I'm not one of them. Here's what I've done, and tell me, please, I beg of you, what idiotic thing I'm doing wrong:

Step 1:

I added the following code to my template.php file, making sure to replace "yourtheme" with the name of my theme:

<?php
function yourtheme_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'yourtheme_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_pass'
    ),
  );
  return $items;
}
?>

Step #2:

Then, below that code in the template.php file, I inserted this code, again, making sure to replace "yourtheme" with the name of my theme:

<?php
function yourtheme_preprocess_user_login(&$vars) {
  $vars['intro_text'] = t('This is my awesome login form');
}

function yourtheme_preprocess_user_register_form(&$vars) {
  $vars['intro_text'] = t('This is my super awesome reg form');
}

function yourtheme_preprocess_user_pass(&$vars) {
  $vars['intro_text'] = t('This is my super awesome request new password form');
}
?>

Step #3:

I created three new template files called user-login.tpl.php, user-register-form.tpl.php, and user-pass.tpl.php

Step #4:

I pasted the following code into each new template file:

<?php print render($intro_text); ?>

  <?php print drupal_render_children($form) ?>

I'm slightly confused by this:

"Save your template.php file to the theme's main directory. Save your .tpl.php files in the same place for the D6 examples, or, in the case of the D7 examples, to the directory you specify in the 'path' element of the $items array."

But that just means that I should save the .tpl.php files in my theme directory, correct? If so, I did this correctly.

Step #5:

Cleared the cache, moved around some elements...and...

Nothing. Is there anything I'm doing wrong? Thanks in advance for your help.

It is a simple module for Customize Drupal Login, Password and Register pages with background images.
https://www.drupal.org/project/simplelogin


Retrieve select option value in webform-mail.tpl.php (7.x-4.x-dev) I have a custom mail template in Webform so values can be in a table for copying/pasting into Excel.

I want the value of the select option fields instead of the key (doing manual entry for webform creators would be too tedious). I can't seem to get to those values.

Any help would be appreciated.

Here's my current code for webform-mail.tpl.php:

<?php
    print $node->title;
?>

<?php print ($email['html'] ? '
' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '
' : ''); ?>

<?php
foreach ($node->webform['components'] as $key => $component) {
    if (isset($submission->data[$key][0])) {
   $key_converted = ucwords(str_replace('_',' ', $node->webform['components'][$key]['form_key']));
    print '
'. $key_converted .'' . ($submission->data[$key][0]) . "
";
}
}
?>

For anyone else that runs across this:

<?php
print $node->title;
?>

<?php print ($email['html'] ? '
' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '
' : ''); ?>

<?php
foreach ($node->webform['components'] as $key => $component) {
   if (isset($submission->data[$key][0])) {
     $key_converted = ucwords(str_replace('_',' ', $node->webform['components'][$key]['form_key']));
     $submittedvalue = $submission->data[$key][0];

     if (isset($submittedvalue)) {
       print '
'. $key_converted .'	';
       if ($node->webform['components'][$key]['type'] != "select") {
           print $submittedvalue;
       }
       else {
        $selectlistitems = explode("|", $node->webform['components'][$key]['extra']['items']);
        if (is_numeric($submittedvalue)) {
                print $selectlistitems[$submittedvalue];
        }
        else {
                 print $submittedvalue;
        }
       }
       print '
';
       }
  }
}
?>


After upgrade from Drupal 6 to Drupal 7 search does not work Same server, upgrade went well and site is stable however it won't index content even after clicking on re-index. Crons are running just fine on server, checked on the MySQL database and all the tables related to search (search_dataset, search_index, search_total etc) are all empty. I have tried turning all modules off, emptying cache, turning search on off, nothing works.

I would really appreciate if anyone knew a way around this.

Kind Regards

Javier

Reindex the search data in config->search->setting and run cron again and again upto the index percentage reaches 100%.

This will solve your issue.

You can also do it via drush to get around limit on the number of items that get indexed per cron run.

$ drush help search-index

Index the remaining search items without wiping the index.
and/or

$ drush help search-reindex

Force the search index to be rebuilt.

Options:
 --immediate Rebuild the index immediately, instead of waiting for cron.


Unable to save term "Big Honor for Branford's Le Petit Café" I was trying to save term with name "Big Honor for Branford's Le Petit Café" using taxonomy_term_save function which throws me the following error

PDOException: in drupal_write_record() in common.inc

Is it some thing related to character encoding  ? should i have to convert the character? I am not sure how to do that.

Please find the code that throws the error,

$term_name  = new stdClass();
$term_name->name = urldecode("Big%20Honor%20for%20Branford%27s%20Le%20Petit%20Caf%E9");
$term_name->vid = 1;
taxonomy_term_save($term_name);

If we are using the exact "Big Honor for Branford's Le Petit Café" is a file then i could not get the error but, when url encoded and decoded again, we will have the same character set.

This code works perfectly for me:

$term = (object)array(
  'name' => "Big Honor for Branford's Le Petit Café",
  'vid' => 1
);

taxonomy_term_save($term);

No errors, and the term is saved as expected. So it looks like the issue is something to do with your server configuration. Without more details it's impossible to say what that problem might be though.

UPDATE

Turns out this a multibyte encoding issue. Wrapping the string in utf8_encode() will fix it:

$term_name->name = utf8_encode(urldecode("Big%20Honor%20for%20Branford%27s%20Le%20Petit%20Caf%E9"));


Views won't display unpublished nodes when explicitly told to My plan is to have a custom page view at blog/% so bloggers can see their own unpublished posts.

If I remove everything except these:

Filter criteria
Content: Type (= Blog entry)
Content: Published (No)

Contextual filters
Content: Author uid

I still can't see the unpublished nodes without making that user an admin. (IE: I log into uid 12 and go to blog/12 - see no nodes. Make uid 12 admin - see 1 unpublished node)

Edit: A look at the SQL shows for admin:

SELECT node.title AS node_title, node.nid AS nid, node.changed AS node_changed, node.created AS node_created
FROM node node
WHERE (( (node.uid = :node_uid ) )AND(( (node.type IN (:db_condition_placeholder_0)) AND (node.status = :db_condition_placeholder_1) )))
ORDER BY node_created DESC LIMIT 10 OFFSET 0

And for normal user:

SELECT node.title AS node_title, node.nid AS nid, node.changed AS node_changed, node.created AS node_created
FROM node node
WHERE (( (node.uid = :node_uid ) )AND(( (node.type IN (:db_condition_placeholder_0)) AND (node.status = :db_condition_placeholder_1) )))
AND ( EXISTS (
  SELECT na.nid AS nid
  FROM node_access na
  WHERE (( (na.gid = :db_condition_placeholder_2) AND (na.realm = :db_condition_placeholder_3) )OR( (na.gid = :db_condition_placeholder_4) AND (na.realm = :db_condition_placeholder_5) )OR( (na.gid = :db_condition_placeholder_6) AND (na.realm = :db_condition_placeholder_7) ))AND (na.grant_view >= :db_condition_placeholder_8) AND (node.nid = na.nid) ))
ORDER BY node_created DESC LIMIT 10 OFFSET 0

Obviously there's a massive amount more SQL for normal users than admins despite my not having put anything related to node_access in there. What is views automatically doing and how can I stop it?

Since drupal 7.15 drupal injects node_access conditions into queries - these can be disabled with the query tag DANGEROUS_ACCESS_CHECK_OPT_OUT but views' query tag entry doesn't accept uppercase tags (Yay)

The only solution to remove node_access checks is to disable query rewriting entirely in Other > Query Settings


How to use hook_views_data_alter to display select list on user reference field? I want to allow administrator to edit user reference field value on the fly when browsing entities list (view as table). In every row select list with user to choose should appear.

Current code:

function rpke_document_assign_views_data_alter(&$data) {
    $data['field_data_field_assignee']['applicant_chooser'] = array(
        'real field' => 'field_applicant_target_id',
        'field' => array(
            'title' => t('Applicant chooser'),
            'help' => t('Applicant chooser based on select list. Extends views_handler_field_user_name'),
            'handler' => 'rpke_field_handler_applicant_chooser',
        ),
    );
}

field_assignee is custom CCK field add to entity based on node.

When I try to add this field to a view I am getting error:

  Invalid column name 'field_applicant_target_id'.

You could checkout Editable Views which let's you create Views where the fields are editable directly. It works with Field API fields which it looks like your field is.


How can I draw a donut chart based on the number of specific fields on a form? Is there a module that can count results in a form, and then draw a donut chart like the following picture?

Note that I'm actually using content types and the Views module to create such forms. So I'm not using the commonly known Webform module to create them.

Yes it's possible to create such charts (which are called Donut Charts) similar to the sample in the Interactive Google Charts gallery (move your mouse pointer over any of the slices in that sample to see the special effects it comes with also). Such Donut chart is actually a Pie chart with a hole in the center, which can be created with the pieHole option.

Below are some more details to get you going ...

Option 1 (without using WebForm):

Use the Comparison of charting modules for potential alternatives to consider.

Some of the modules mentioned there:

Charts, which can be used to Create charts using Views ... as in these Charts previews and/or its demo site. The D7 version of it comes with a choice between 2 supported charting libraries to select from.
Chart, which can be used to Create charts using Views ... as in these Chart previews. It requires the (deprecated) Google Image Charts, and is expected to be upgraded in the near future to use another charting engine. Charting engines being considered are either of these JS libraries:

The JIT (Javascript InfoVis Toolkit).
The d3.js library.

Option 2 (Using WebForm):

There are actually 2 alternatives to pick from:

Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, use the Charts module to actually create the charts (module dependency).

Remarks

The license that comes with the charting library (engine) that is used in the selected Charting module, should be considered also. Some of the typical items to consider are:

Possible privacy concerns.
Flash based libraries (as they were also used in the D6 version of Charts) should be avoided if charts are to be displayed on mobile devices.
Google libraries require a working internet connection (not always available in local DEV environments ...).
Not all libraries are free of charge (some come with commercial licenses).

Disclosure: I'm a (co-) maintainer of Charts and Chart, and the author of that Comparison.


change save button text of a node to submit I am using drupal 7.10 I have a content type in which i want to change the save button text to submit.I tried various posts in this forum to no avail.i need help on this.Thanks in advance.

This is the complete $form['actions']['submit'] array the Node module uses for the form.

  $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#access' => variable_get('node_preview_' . $type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
      '#value' => t('SaveTest'),
      '#weight' => 5,
      '#submit' => array('node_form_submit'),
   );

You need to hook into the node form.

/**
 * Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['#node']) && $form_id == YOUR_NODE_TYPE . '_node_form') {
    $form['actions']['submit']['#value'] = t('YOUR_NEW_VALUE'),
  }
}


Error when uploading file through Drush on S3 volume I am using Amazon S3 volume to store the node's attachment.
I keep having the following message:

file_put_contents(public:///.htaccess): failed to open stream: "DrupalPublicStreamWrapper::stream_open" call failed file.inc:494                                                                                [warning]
WD security: Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your public:// directory which contains the following lines: # Turn off all options we don't need.                                 [error]
Options None
Options +FollowSymLinks.....

I tried chmod 777 on private (sites/default/files/private) public (sites/default/files) folders without any success.

Is it because amazon S3 and AWS/SDK are installed. It works weel anyway : my files are created on S3 volumes. But the message is annoying.

Any ideas ?

Thanks

It's all there really, it's a security warning and you can fix it by creating a .htaccess file at the root of sites/default/files. The actual content should be:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Additionally, the .htaccess of the temporary files directory and private files directory (if used) should include this command:

Deny from all

Read more in this security advisory.


How to fallback to default language when listing nodes in a view if no translation is available I have a list of projects, mostly in english, but some are translated in French.

When i visit the French version of my website, how can I list all projects that are translated in French and if no translation is available for a specific node, display the english counterpart.

Is that something possible in the view UI ? Or I'm guessing with a hook_query_alter.

Thanks,

Try the Alternative Language Module. There a lot of sub modules, but the base one will give you the functionality you are looking for.

  Allows a language to specify an alternative language. If a node
  translation for a specific language does not exist, Drupal will try to
  load the translation for the alternative language before throwing a
  404.

  This module is useful if you have multiple languages and only one
  language is typically translated. Rather than create all of the other
  translations and maintain those, the non-translated languages can load
  the node from the alternative language.

  For example, you have the following language configuration:

  / - US English - default
  /en-ca - Canada English - alternative language is US English
  /fr-ca - Canada French

  There is a node /contact, you will get three URL's:

  /contact - US English
  /en-ca/contact - Canada English
  /fr-ca/nous-joindre - Canada French

  There are only two versions of the
  node, US English and CA French. The CA English uses it's alternative
  language and loads the US English version so all three pages work and
  the URL's are correct.


Can't log in as admin Someone let us know about an error on our site. I logged in (as an admin). I was able to move the site to maintenance mode and then went through the steps to clear the cache on the site. Once I did that, I am no longer able to log in or even get to the log in page.  I went to our site: safefields.org/user and I get this error: safefields.org is currently unable to handle this request. HTTP ERROR 500  How can I fix any of this if I can't even log in?

When you type in safefields.org/user your site immediately redirects to the login page safefields.org/user/login which I believe indicates that your Drupal site is running but gives you a WSOD (white screen of death).
Usually that is because of a memory_limit constraint.
Things to investigate:

Try to use Drush to set the maintenance mode back to 0: drush vset maintenance_mode 0 this should get your site visible again
Check your settings.php and see if you have a memory_limit set there, increase to 512M or higher clear cache (either via Drush or empty cache tables directly in the database)
Check your php.ini file either in the root of your site's folder or in your public_html folder and increase it in size.
Google "Drupal 7 WSOD" as they say: add error reporting to your settings.php file to see what the errors are so you can search more effectively for what's causing your problem. https://www.drupal.org/node/158043

error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


sf Smallscreen menu button reverts to full desktop menu when scrolling down To prevent my Superfish Main Menu from stacking as screen size decreases  - and thus obscuring the content below it, I set sf-Smallscreen to change the Superfish Main Menu to an accordion when the screen size scales down to 990px. This accommodates tablets in portrait orientation, for example.

Problem: When you scroll down on a tablet, the accordion "Button" reverts to the Desktop rendering of the Main Menu, "stacking up" because it's too wide for the narrow screen.

Scroll back up and the Desktop Main Menu is replaced by the accordion.

Question: How can make the accordion button persist when scrolling down on a tablet-sized screen?

I can't say for sure without seeing your code, but I wonder if this is maybe because you have some Javascript that does an add/remove class or changes the structure of the menu in order to make sticky nav items take up less space when you scroll. This symptom could only be caused by Javascript detecting the scroll behaviour, and as far as I know, Superfish does not have this feature natively (though I could be wrong, I am not overly experienced with this specific module).

If this is the case, right click and inspect code, then look for things that change dynamically on scroll. Any names of classes that are added might give you a clue as to which module is causing this. It does sound like a conflict, though, and not Superfish itself.

If that is not helpful, do you have a dev site up that we can take a look at?

Good luck!


how to replace file with an empty file of the same name? My Set-Up:

When a user uploads a file, it first gets uploaded to a folder on my local server, and then gets moved to an amazon s3 server for storage.  Currently, when the file is moved to s3, the local file gets deleted.

What I would like to do:

Rather than delete the local file, I would like to replace the local file with a 0-byte file.  Reason:  so that if another user uploads a file with the same name, the system will know it needs to rename the second file.

My Question:

How can I replace a file ("myvideo.flv") with an empty file of the same name, so that "myvideo.flv" now contains 0 bytes?

To replace a file with a zero byte file use a combination of unlink() and touch():

unlink($file_path);
touch($file_path);

To move a file to a different folder use Drupal's file_move():

file_move($src_file_path, $dest_file_path);

To rename a file use rename():

rename($file_path);

All of the above make the assumption that your webserver user has read access over the source path, and write access to the destination path.

EDIT

Your original question asked about moving/renaming files as well, I'll leave the answer to those in just in case you're still wondering.


How do I verify a block can be shown in the current page? I created a normal block and configured it using the following settings.

I don't want to show the block on node/2 and node/3, for example. I want to get the block render, but verify first the block can be shown on the current page.

// 1 is the block ID.
$block = block_load('block', 1);
// I want to verify if the block can be shown on the current page before getting the renderable array.
$renderable_block = _block_get_renderable_array(_block_render_blocks(array($block)));

I can verify $block->pages contains the path for the current page, but I think there is a proper way to do that. I am sure there is a core function to which I can pass the block object and the current path.

What core function should I use to verify the block is visible in the current page?

With the help of the answer on this question, Here is a helper function to check block visibility in case someone needs it:

/**
 * Helper function to remove blocks from list who can not show in the current path:
 * based on , pages, user, roles ..
 * @see: block_block_list_alter().
 * @return mixed
 */
function _check_block_list_visibility_on_current_path(&$blocks) {
  global $user;

  // Build an array of roles for each block.
  $block_roles = array();

  $result = db_query('SELECT module, delta, rid FROM {block_role}');

  foreach ($result as $record) {
    $block_roles[$record->module][$record->delta][] = $record->rid;
  }

  foreach ($blocks as $key => $block) {

    // If a block has no roles associated, it is displayed for every role.
    // For blocks with roles associated, if none of the user's roles matches
    // the settings from this block, remove it from the block list.
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
      // No match.
      unset($blocks[$key]);
      continue;
    }

    // Use the user's block visibility setting, if necessary.
    if ($block->custom != BLOCK_CUSTOM_FIXED) {
      if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
        $enabled = $user->data['block'][$block->module][$block->delta];
      }
      else {
        $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
      }
    }
    else {
      $enabled = TRUE;
    }

    // Limited visibility blocks must list at least one page.
    if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
      $enabled = FALSE;
    }

    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }

    // Match path if necessary.
    if ($block->pages) {
      // Convert path to lowercase. This allows comparison of the same path
      // with different case. Ex: /Page, /page, /PAGE.
      $pages = drupal_strtolower($block->pages);
      if ($block->visibility < BLOCK_VISIBILITY_PHP) {
        // Convert the Drupal path to lowercase.
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
        // Compare the lowercase internal and lowercase path alias (if any).
        $page_match = drupal_match_path($path, $pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
        }
        // When $block->visibility has a value of 0
        // (BLOCK_VISIBILITY_NOTLISTED), the block is displayed on all pages
        // except those listed in $block->pages. When set to 1
        // (BLOCK_VISIBILITY_LISTED), it is displayed only on those pages
        // listed in $block->pages.
        $page_match = !($block->visibility xor $page_match);
      }
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
      else {
        $page_match = FALSE;
      }
    }
    else {
      $page_match = TRUE;
    }

    if (!$page_match) {
      unset($blocks[$key]);
    }
  }
}

Thank you No Sssweat for pointing me to right direction.


Admin view/edit content as user Is it possible to toggle an admin role to see and edit content as a specific user?

I've got a number of entityreferences with contextual filters that are URL dependent, and when I try to edit an entityform submission as admin, I can only see my own data view.

I think  you are looking for this module Masquerade.

  The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.

There is a module called Role Toggle to handle role toggle.

  This module gives you a page and a block to toggle (switch on and off) any role.


Forcefully logout user from website I have a site which contains many links on the pages.
Now I want to achieve the following:-

User logs in website with credential and visit one of the page in the site.
User right click on link and open the link in new tab.Now there are
two pages of website opens in user's browser in two tabs.
Currently Log Out option is visible on every page of the website.
Authenticated user click on log out option in the page opened in one
of the tab.
Log out redirects user to login page.
So as per these scenario ,there is one more page remains open in another
tab.
Now if the same user click on any of the link in the page then it
should redirect to login page

Please provide your valuable input to achieve this functionality.

Sounds as if you need the Redirect 403 to User Login module:

Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:
"Access denied! You must login to view this page."
Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.


Administrator's approval required after published node has been edited After editing, any published node needs administrator's approval like comments. How can I do this with Drupal 6?

Use the Rules module to create a rule that sets a node to unpublished when it is saved. You might also want to have a look at the Moderate module.


Printmail Form inside Colorbox I am actually trying to load the printmail form inside a colorbox. But when I am trying to build up a link like this:
Send as email

The colorbox opens, but returns "This content failed to load."
Someone got an idea how to workaround that?

You should use the colorbox-node instead of colorbox-load First check have you already installed the Colorbox and the Colorbox Node modules.

Then, your link would be similar to the following one.

Als E-Mail versenden


How to use EntityFieldQuery with dates? I need to select entities with specific dates.

How should the following be formatted. Do I need to parse 15-May-2010

Also how I get the error page.

function events2() {

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('type', 'event')
  ->propertyCondition('field_event_date', '15-May-2010', '=');

$result = $query->execute();

 return $result;

}

With Drupal 7 and Date module 2.2:

$query = new EntityFieldQuery;
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1) // Getting published nodes only.
->fieldCondition('field_dates', 'value2', date("Y-m-d"), '<') // end date before today
->execute();


Need a more specific price calculation rule in Drupal Commerce I have a price calculation rule like this:

Event: Calculating the sell price of a product

Conditions: Order contains products of particular product types AND User has roles

Actions: Multiply the unit price by some amount

Now, the problem is that when the cart contains products of the type that I selected as a condition AND the user has a specific role, the multiplication in the Action element is executed also on products of other product types. I only want to affect the prices of products with a specific type.

The cart can contain a mix of products of different types, but the rule should only affect the line items with the specific type.

How do I do that?

Depending on your multiplication factor (I suppose you want to give a discount), you might want to try Commerce discount which has support for discounts per order and discounts per product.

  Commerce Discount provides a new user interface for defining and
  managing product and order level discounts. Using just the core
  pricing system of Drupal Commerce requires knowledge of how to use the
  Rules UI, which is beyond the capabilities of most merchants.
  Additionally, the core system cannot support order level discounts or
  certain types of shipping / product discounts. This module addresses
  all of those things.

The role based discount condition is provided by Commerce discount extra.


How to prevent users from uploading the same file (image) multiple times? I have a content type, Image, which allows users to add an image using Drupal 7's built-in image field.  I would like to automatically prevent users from adding the exact same image (same filename, same size) if possible.  Is there any way to prevent duplicate file uploads?

In pseudo/quick code, this is how I would approach it.  In a custom module...

Create a table in the db, with two columns, fid and md5.
Each time you create a file, check if the md5() of whatever you consider unique is in that db, eg:

a.  select fid from TABLE where md5 = ab3783ea6c83bcd9383eef778

b.  if fid then oops, there already appears to be file blah blah blah

c.  otherwise
Store that file's fid and md5() in that table.

You could put all this logic in the validation hook when you are creating the image content.  You could even set up roles that are able to override it, etc.

Now, to the md5()ing of things.

Filename is easily changed and I don't think it is really sent to drupal anyway--but instead crafted there after the fact--so do you really want to use it?
Content of the file might be a better approach.

So, md5 could be populated with a quick md5_file(PATHTOFILE).

Now, let's say you wanted to have an option of doing this system wide or per user, eg, you don't want one user uploading multiple copies of one image or you want to have only one exact image uploaded systemwide.

Just add another column uid to the table above and check it as well, eg:

select fid from TABLE where md5 = ... and uid = $user->uid

Anyway, these are just my quick thoughts after the morning's first espresso here in D6land.  Maybe D7 has some of this already built into it and I am once again reinventing that wheel :)


Price Field Not Saving Programatically Price Field Type from the Commerce module package is not exportable for Feeds. So as a work-around, I saved my prices ('min price', 'hot price' and "deposit price') into  normal Float fields and just move the values to the Price Field Types  on-the-fly. And so here it is (set using Rules: After an item is saved of content type 'Property'):

$node->field_price_amount['und'][0]['value'] = [node:field-current-price-temp];
$node->field_hot_price_amount['und'][0]['value'] = [node-field-hot-price-temp];

etc.

and then applying the node_save($node) with $node->is_new set to FALSE.

All the other values are saving properly except for the field type defined by the Commerce module. No actual data saved to tables at all.

"$node->field_price" should be the right machine name I have defined for this field. But for some reason importing leads to error field_price_amount cannot be NULL. This is also weird. So I changed it to field_price_amount so it won't complain but still not saving despite no more errors in importing. (The db table is still named field_data_field_price but for some reason it is complaining as 'field_price_amount should not be null ).

Anyone have ideas?

Commerce price fields have a different data structure from standard fields.

i.e not:

$product->commerce_price[LANGUAGE_NONE][0]['value'] = 500;

but instead

$product->commerce_price[LANGUAGE_NONE][0]['amount'] = 500;
$product->commerce_price[LANGUAGE_NONE][0]['currency_code'] = 'USD';

or just:

$product->commerce_price[LANGUAGE_NONE][0] = array('amount' => 500, 'currency_code' => 'USD');

They also have a 'data' property for additional price component information.

More info: commerce_price_field_data_property_info


Restrict permission to custom modules I am using drupal 7, and I have created a custom module. This module consists of a form that can be used for adding records to the database. But I saw that the link to accessible to all the users, even anonymous users.

I want to restrict the access to this module and form from all the normal users; only the administrator users should access it.

I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.

How can I restrict the access to my custom module?

When you define the page the form is on via hook_menu(), you need to set the access rights via the "access callback" and "access arguments" settings.

The simplest way to do this is to provide an array containing a single permission value as the "access arguments" setting.


I can't edit Panel variants I think this may have happened when upgrading to Drupal 8.5.x, but I can no longer edit a panel variant.

I can add a new variant and seem to be offered the typical layout, content, etc., but nothing happens when I click a variant, and I don't have the typical menu selections (see screen shot).

I am logged in as User 1 with all permissions checked. There are no errors in the error log. I have the latest dev version of all the relevant modules (Panels, Ctools, etc.).

Any guidance would be greatly appreciated.

I had the same issue and I managed to solve it by finding the following issue/patch: https://www.drupal.org/project/page_manager/issues/2921404#comment-12526453


How to configure Facet Advanced Range? I'm lost on how to configure advanced ranges in Facet API displays. I see this page, which supposedly quotes from the README

  For example [100 200] will produce a range between 100 and 200.
  For example [100 *] will produce a range of "100 and above"

I've configured my ranges like this:

But the drop down menu appears like this:

It turns out the documentation is just a lie...

https://drupal.org/node/2126017

These values worked:

0-800
800-1000
1000-1200
...
1800-2000
2000-


How can I enable Global: PHP field I'm trying to add a PHP field to a view, but I cannot see how to activate it. Do I need a module?

I'm already using / viewing:

Global: View result counter
Global: Math expression (Math expression)
Global: Custom text (Custom text)

I'd like to know how I could add:

Global: PHP field

I think it exists because of Global:PHP field with SQL in output code.

Just install the Views PHP module and you can now add a "Global: PHP field" to your views that can include PHP code. Quote from its project page:

This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
Note: While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly
advisable to use regular handlers and plugins when available (or even
to create one yourself). Take note that filtering and sorting a view
using PHP always has a considerable perfomance impact.


Config sync directory outside of webroot causes open_basedir restriction warning Hello all and thank you for taking the time to help. In following this tutorial and many others like it, I've successfully moved the configuration sync directory outside of my webroot, both locally and on production. I can confirm that it's working using drush cex and drush cim in both locations.

Hopefully Helpful Info

Drupal 8.3.5
On production, I have the config directory set with 775 permissions (and export/import still worked with 755).
in settings.php, I have $config_directories[CONFIG_SYNC_DIRECTORY] = '../config/sync'
since it couldn't be created by Drupal, I created a .htaccess file for this directory on my own.
config is being version controlled, but due to how/where Drupal was installed, I'm having to maintain a separate git repo for this single directory, which doesn't bother me. Drush still seems to work with no complaints.

The Problem

Within the UI, I get the following status report errors:

Warning: is_writable(): open_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in config_requirements() (line 24 of core/modules/config/config.install).
Warning: file_exists(): open_basedir restriction in effect. File(../config/sync/.htaccess) is not within the allowed path(s): (/home/cathchar/www:/tmp) in file_save_htaccess() (line 367 of core/includes/file.inc).
Warning: file_exists(): open_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in file_save_htaccess() (line 374 of core/includes/file.inc).
Warning: is_dir(): open_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in system_requirements() (line 600 of core/modules/system/system.install).
Warning: is_dir(): open_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in system_requirements() (line 603 of core/modules/system/system.install).
(and below these) CONFIGURATION DIRECTORY: SYNC - The directory ../config/sync does not exist.

What I do/don't understand

I'm swimming in deeper waters here than I'm used to, but I sincerely want to understand errors like this and be able to get to bottom of issues. From what I understand, Drupal is warning me that my newly created /home/cathchar/config/sync directory is not in a path, namely /home/cathchar/www (the webroot) or the account root /tmp directory, that it can work with/write to. It's also warning me that that it doesn't see this directory as existing.

My question

The directory obviously exists, but what am I missing? PHP should have no problem with seeing outside of and jumping out of the webroot, correct? Do I have to inform Drupal somewhere else about a new path to work in? None of the tutorials/instructions I've read ever mention issues regarding directory access, paths, or open_basedir restrictions. The ones I encountered make it seem like adjusting settings.php and creating the non-webroot directory is really all it takes. I'm a bit stumped.

Any help that anyone could provide would be greatly appreciated!

PHP should have no problem with seeing outside of and jumping out of the webroot, correct?

Very much not! As the errors are telling you, your server config explicitly doesn't allow that to happen. You have PHP locked down to only be able to read from certain paths; /home/cathchar/config and/or /home/cathchar/config/sync don't belong to that list, so PHP can't read files from them.

  Do I have to inform Drupal somewhere else about a new path to work in?

No...Drupal doesn't need to be told about file system restrictions, it just consumes the environment it finds itself in, and invariably complains if it can't access what it's (implicitly) been told it can have access to.

This should ideally be solved in your vhost/FPM config by setting an open_basedir which includes all of the paths that PHP needs to be able to read from (separated by a ;).

  None of the tutorials/instructions I've read ever mention issues regarding directory access, paths, or open_basedir restrictions

The docs don't really try to cover every possible configuration scenario, it's probably assumed that if you're doing something more advanced like moving a folder out of the web root that you're happy configuring the rest of the server to allow it to happen.


Drupal 7 node body content missing from search results I am having an issue where my Drupal 7 Search (Custom search installed and enabled) isn't returning all of the results I'd expect it to.

Here is some background...

I'm running Drupal 7 on this site.
I have roughly 10 content types, but the search only returns 2 content types – work and blog.
I am using the core search module along with drupal custom search module.

The Issue:

When I perform a search I am presented with a selection of results from both work and blog content types. However, the issue is while the blog content type produces the expected results pulling from keywords in both the node titles as well as the nodes body content, the work content type only returns results where the keyword is found in the node title.

Attempted fixes:

I have confirmed that the site is 100% indexed. Just in case I have re-built the index.
I went to the Custom Search Module settings to confirm that -Any- is being used in the -Any content type- text field. In addition, in the Content exclusion area I've made sure both the blog and work content types were left unchecked.
I have confirmed that the Minimum word length to index is at 3. My searched words are above 5.
And lastly, two thoughts I didn't know played into the search results, but were worth looking into are the Manage Display settings for both content types under their Search index and Search result highlighting input tabs. Both of which seem to be identical. So I assume wth my limited knowledge of Drupal's configurations isn't really vital to this issue.

I'm still trying other suggestions found here in StackOverflow and will update this as I come across new options to try as attempted fixes.

If anyone has come across this matter and can lead their considerable knowledge on it, that too is always appreciated.

Thanks in advance!

Okay, so I was able to resolve this issue through a combination the following efforts.

Under both content types and added in new fields to search index and search results highlighting input.
Under Administrator/Configuration/Search and Metadata/Search Settings I turned off Simple CJK handling.
Under Custom Search Content Tab I used the default of -Any- and under the Exclusion options left all but my two desired content types checked.
Under Administrator/Configuration/Search and Metadata/Search Settings I clicked re-index site.
I then flushed all caches and ran cron until the site was once again 100% indexed.

After all that I performed my tests again and everything was coming up as expected. Hopefully this can help others later in their testing.


Remove tags from dependent term ref field when dependee is deactivated I have a check box acting as the dependee. When it is checked, it opens up a free-tagging term-reference field. So when A is checked, B appears and users can add tags:

A (checkbox): []
  B (tags): [________]

In the settings I have the following selected:

  "Reset the dependent to its default values when the form is submitted
  if the dependency is not triggered."

The default value for the term-ref field is blank. When the checkbox (dependee) is unchecked and the content saved, it should revert to the default value. However, all added terms remain.

Is there a way to remove all taxonomy terms in this scenario? I have multiple dependee/dependent fields in the content type, so it would have to act independently of other fields.

Fixed...
In the conditional fields settings I had used the following:

The dependent field is: visible

When the dependee: is checked

For some reason this does not revert the dependent to its default value if the dependee is deactivated on saving. Instead, I used these settings and it works:

The dependent field is: visible

When the dependee: is has value

(select the name of the checkbox)

This might be because I have used the label as the value for the checkboxes (instead of the default 0 & 1).


Handling anonymous orders in custom commerce module Drupal: 8.7.2
Commerce: 2.13

I have a custom module set up that adds the following functionality to Commerce:

It prevents the user from adding more than one item to their cart.  If they try to add a second item, it removes the first item from their cart and adds the second item.
When clicking "Add to Cart", it redirects the user to a confirmation page.
On that page is a button that links to the order's checkout page.

I am handling all of these via queries that use the user ID and order ID to pull the correct order/cart information.

This all works great for logged in users.  Most of our customers will be anonymous, though.  It does work for anonymous users, but my concern is that if multiple anonymous users are placing orders at the same time, their carts will get mixed up, because all anonymous users have a UID of 0.

How can I better differentiate between anonymous user's carts?  Is there a way to store their IP in the database, and then use that?

Here is my module's code:

commerce_custom.module (handles removing first item from cart, redirecting to confirmation page):

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_order\Entity\Order;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function commerce_custom_form_commerce_order_item_add_to_cart_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $form['actions']['submit']['#value']='Sponsor';
   $form['#validate'][] = 'commerce_custom_form_validate';
   $form['actions']['submit']['#submit'][] = 'commerce_custom_cart_alter_redirect';
}

function commerce_custom_form_validate(array &$form, FormStateInterface $form_state) {

    $user = \Drupal::currentUser()->id();
    $connection = \Drupal::database();
    $query = $connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft'", [':user' => $user]);
    $result = $query->fetchAll();
    //dpm($result);

    $cart_count = $result[0]->quantity;
    $order_id = $result[0]->order_id;

    if ($cart_count > 0 && $order_id) {
        $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($order_id);
        $items = $order->getItems();
        foreach($items as $item_key => $item) {
            $order->removeItem($item);
            $item->delete();
        }
    }
}

function commerce_custom_cart_alter_redirect(&$form, FormStateInterface $form_state) {
  $responce =  new RedirectResponse('/how-it-works');
  $responce->send();
}

ContinueCheckoutBlock.php (creates block with button linking to checkout page):

<?php

namespace Drupal\commerce_custom\Plugin\Block;
use Drupal\Core\Block\BlockBase;

class ContinueCheckoutBlock extends BlockBase {

   public function build() {

        $user = \Drupal::currentUser()->id();
        $connection = \Drupal::database();
        $query = $connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft'", [':user' => $user]);
        $result = $query->fetchAll();
        $order_id = $result[0]->order_id;

        return array(
            '#type' =>'markup',
            '#markup' => 'Continue',
        );
   }
}

Perhaps you could use PHP's session_id()?

  session_id() is used to get or set the session id for the current session.

Basically copied from this answer.

You may also find useful information here: Anonymous Personalization Without Leaving Drupal, which appears to be a topic from DrupalCon Seattle 2019.


Send email when order status is changed I need to send a message to the customer when I change the order status (e.g from pending to processing-completed-canceled). How can I do this with Rules?

Rules is definitely the way to do this.

Create a new rule...

Name: Order Status Update
Tags:
React on event: Commerce order > After updating an existing commerce order

Then, add an action. System > Send mail
Email "To" value. Use the [commerce-order:mail] token
Fill out subject and message. Then save.

Updated: To make sure you dont send an email everytime the order is updated, set the following rules...

Add condition: Data Comparison. Commerce-order:status = Completed
Add "AND".
Add condition: Data Comparison. Commerce-order-unchanged:status = Completed, but check NEGATE.

This avoids having to enable the PHP filter module.


Is it possible to change fieldset title if collapsed with #states I'm trying to use #states in form api to change the title of a fieldset based on his collapsed states.

so far here's my code :

$form['advanced'] = array(
  '#type' => 'fieldset',
  '#title' => t('Advanced search'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#attributes' => array('class' => array('search-advanced', 'clearfix')),
  '#states' => array(
    '#title' => array(
      array('fieldset#edit-advanced' => array('#collapsed' => 'Hide advanced search')),
    ),
  ),
);

I've tried different things, but without success.

Thanks a lot.

It is true that there were some issues with #states and fieldsets, such as #states can't hide/show fieldsets, but in your case the code doesn't work because #title is not an handled state, and #collapsed is not a handled state for the remote condition.

The list of the implemented states is given in drupal_process_states():

enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed

The states used for the remote conditions are the following:

empty
filled
checked
unchecked
expanded
collapsed
value

It would also be hard to implement that, as the state needs to be boolean, and the remove condition says the value of the state for the other form field.

For example, if foo is a select list, the state for a form field could be the following one.

'#states' => array(
  // Show the settings if 'bar' has been selected for 'foo'.
  'visible' => array(
    ':input[name="foo"]' => array('value' => 'bar'),
  ),
),

This state would make the form field visible when the value selected from the list is bar.


Where is the CCK autocomplete widget field php configuration code stored? I have run myself into a serious problem. I have a custom CCK datatype in Drupal6 in combination with an autocomplete widget on a text field. I have defined php code in the web configuration for the "allowed values list", but the code I wrote is faulty and uses up all memory (three nested foreach loops, returned array gets way too large, 2G mem limit reached).

Unfortunately, I cannot access the Drupal6 instance at all, as it seems the faulty php code is executed on all pages (not sure about this, but did reboot the server and still could not log in).

I guess it would be best just to delete the faulty PHP code for the Autocomplete widget from the backend, but I am unable to find it in the Postgres database. Can anyone give me a hint as to where in the database this code is stored?

Any other hint as to how to resolve this problem will be highly appreciated.


How to better search: replacing %20 with + When I search for "asus laptop type:product" the url is "search/node/asus%20laptop%20type%3Aproduct" but how to make it like "search/node/asus+laptop+type:product".
So how to repalce %20 with + and %3A with : on Drupal 7.
Thank you.

I don't know what you mean by "better search", as the search works as-is. However, I think the reason it works this way is because drupal_goto() eventually calls drupal_http_build_query(), which calls rawurlencode(). Drupal uses this for URL query parameters. The docs for the function say it returns:

a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

https://php.net/manual/en/function.rawurlencode.php
RFC 1738: https://tools.ietf.org/html/rfc1738
To change this, you could create your own module or function that does not does escape :. If you use an exposed view search form, it should already encode spaces as +.


Boost is not working properly I am using Drupal 7.
I have installed Boost module and configured properly as per the guidelines from Drupal.org site and other sources.
As per my knowledge to test whether boost is working or not we have to check html source code of any page because Boost module adds Boost tags in the html output generated by drupal.
When i check page source i don't find any boost tags.
I also have one doubt regarding the configuration, in .htaccess generation page there are three options

%{HTTP_HOST}
%{SERVER_NAME}
localhost

which one should i enable when i am configuring on the site like http://xyz.com/mydrupal
where mydrupal contains drupal setup and all the files

%{HTTP_HOST} is the default and it usually works. The other 2 options are there in case http_host doesn't work. Every hosting environment is different; that's why there are options.


Replacing an existing image via the admin interface Have access to a Drupal 6 admin and attempting to replace a single image via the admin interface. My understanding is that to just replace an existing image that I'll need to access the sever directly. Is there any way to edit (aka replace) an existing image via the admin interface?

Might be worth noting that one reason I want to replace the image, and not just upload a new one is due to the fact that the image is referenced via template, and not in a block, page, etc.

If the image is referenced via a template, there is no (easy) way to replace it via the CMS.  You will need access to the file system, like FTP access.

Otherwise, you could look at finding or writing a module that gave you full access to the filesystem via the Drupal CMS.  This would be.. difficult and dangerous.


hook_menu - setting a variable to use in page.tpl.php I know how to use hook_preprocess_page() to add/change variables for use in page.tpl.php. For nodes, you can use menu_get_object() to load the current node and process it from there.

How do I do this for a page I've created using hook_menu()? I've tried printing out all the $variables but there is nothing much I can identify this page with, apart from the 'theme_suggestions' which seems a bit flaky. Using arg(0) also seems like a hacky way to go.

Is there any way to set the page.tpl.php variable directly with hook_menu()? That would be ideal.

EDIT for clarification:

This is what I want to achieve:

function mymodule_menu() {

  $items['my-page'] = array(
    'title' => t('My Page'),
    'page callback' => 'mymodule_callback',
    'access callback' => TRUE,
    'page arguments' => array(),
    'page vars' => array('myvariable' => 'hello') // Obviously this doesn't work, but would be great
  );

}

function mymodule_preprocess_page(&$vars) {

  if($something === 'my-page'){ // What to do here???
     $vars['myvariable'] = 'hello';
  }

}

Basically I want something within hook_preprocess_page &$vars array to identify the route I have created with hook_menu. If I can define this somehow in hook_menu itself (or the callback) it would be even better.

I can use arg(0) but that doesn't account for any subpages, and I might want to change the route which means I need to change preprocess function too. Is there a better way?

Just as an option, you could use a specific page template for your path, and sub-paths.

/**
 * Implements hook_preprocess_page
**/
function HOOK_preprocess_page(&$variables) {
  // Optional logic to check path condition
  // e.g arg(), request_uri(), current_path() etc..
  $some_condition = FALSE;
  if(arg(0) == 'base' || $some_condition) {
    // Set single page--base.tpl.php template, for /base and /base/subpath
    // Note: this overrides theme_hook_suggestions[]
    $variables['theme_hook_suggestion'] = 'page__base';
    // Sample template variable
    $variables['foo'] = 'bar';
  }

}

Then, in your theme, you can copy page.tpl.php to page--base.tpl.php and add whatever page specific markup you need in the template.

You could also add logic and template variables to hook_preprocess_page.  They would be available in your custom template. They can also be added there for the default page.tpl.php template. In any case, you will need some condition check for the specific target path match there.

Some relevant API functions to check the URL path include:

arg
current_path
request_uri

Note: arg() is also used by core template_preprocess_page to set the theme suggestions.

  Uses the arg() function to generate a series of page template suggestions based on the current path.


How to add percentage column in views I use Views Aggregator Plus to calculate sum of a column.

----------------------
Item         Data
----------------------
A              20
B              30
C              50
----------------------
                100
----------------------

Then I want to add additional column for percentage.

-----------------------------------------
Item         Data         Percentage
-----------------------------------------
A              20
B              30
C              50
-----------------------------------------
                100
----------------------

I know Global:Math expression. But I don't know how to get the sum, the sum field is not available. Only [value], [value_1] and [value_2] available for A, B and C respectively.

Is there a way to add a percentage column?

Now this problem has been solved, after VAP add percentage function
http://cgit.drupalcode.org/views_aggregator/commit/?id=2539ac5

Now I can add additional column calculating the percentage (as an example below):


Next free value field I need a custom field whose default value will be a "next free" value calculated using a user-defined scope (selection of content types). But before I even try to bother coding, maybe someone knows of such a contributed module? My searches returned nothing.

I'd be reluctant to using Computed Field as I feel somewhat uncomfortable storing PHP code in database.

Perhaps you could just use a Serial field

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

  The allocation of serial numbers by this module is atomic. In other
  words, the serial values are unique even when multiple instances of
  the same content type / entity are created simultaneously.


I got duplicated modules after updating an installation. How to remove them? I have a site built using the Commerce Kickstart profile. Then there are enabled modules provided by the distribution at:

  profiles/commerce_kickstart/modules/contrit

and also there are modules which I added at:

  sites/all/modules

The distribution added some modules: colorbox, entity, etc. in its last version.

The problem is that I already had these modules at sites/all/modules.

The I got those modules duplicated at:

  profiles/commerce_kickstart/modules/contrit/colorbox

and

  site/all/modules/colorbox

I guess this is wrong. My question is which folder do I have to delete?

Here are the steps I would perform to address this question, in the specified order:

Download and unpack a fresh copy of the new Commerce Kickstart release.
Create a list of all your modules in your sites/all/modules folder, and identify all modules in there with the same name (module namespace) as in the new Kickstart release. The result should be a list of the duplicate modules that need to be resolved.
Use the Hacked! module to identify any hacks, patches, customizations, etc that might have been applied to any of these duplicate modules in the sites/all/modules folder.
Disable and uninstall the duplicate modules.
Backup and then delete the entire folder of each of the duplicate modules in the sites/all/modules (or move them to a folder outside your Drupal root directory).
Enable the fresh copy of the new Kickstart release. That inherently will also re-enable the vanilla version of the duplicate modules, as contained in the new Kickstart release.
Reply any hacks, patches, customizations, etc that are appropriate to be  re-applied (e.g. because upgrading to the new Kickstart release does not make them obsolete).
Should you run into weird problems because of some of the duplicate modules being moved to another directory, then download and enable the Registry Rebuild module (and/or related Drush RR command). That will probably resolve those problems.


Dependency injection or \Drupal class methods? Suppose I have an ExampleService  class and I need a service (current_user) to process my logic. So I have implemented my service like this.

The way 1: DI standard Drupal

namespace Drupal\example_service;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxy;

class ExampleService implements ContainerInjectionInterface {
    /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
    protected $currentUser;

    public function __construct(AccountProxy $current_user) {
        $this->currentUser = $current_user;
    }

    public static function create(ContainerInterface $container) {
        return new static(
          $container->get('current_user')
        );
    }
}

The way 2: Use global service

namespace Drupal\example_service;

class ExampleService {
    /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
    protected $currentUser;

    public function __construct(AccountProxy $current_user) {
        $this->currentUser = \Drupal::service('current_user');
    }
}

What is the difference between these methods?
What is better for performance?

In Drupal 8, you should always use dependency injection within the context of classes.

However, if you create a custom service, you don't have to manually implement the ContainerInjectionInterface.

Instead, you define your service and the arguments for the constructor within your module's example_service.services.yml file (read more about .services.yml files here and about service injection here):

services:
  example_service.my_service:
    class: Drupal\example_service\ExampleService
    arguments: ['@current_user']

And your service class like this:

<?php

namespace Drupal\example_service;

use Drupal\Core\Session\AccountProxyInterface;

/**
 * My Example service.
 */
class ExampleService {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Construct an example service instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   Account proxy for the currently logged-in user.
   */
  public function __construct(AccountProxyInterface $current_user) {
    $this->currentUser = $current_user;
  }

}

Then you can create an instance of your custom service either via dependency injection as well (within the scope of another class), or within your module/theme files by using:

/* @var $my_service \Drupal\example_service\ExampleService */
$my_service = \Drupal::service('example_service.my_service');


Drupal, menu links multilanguage I'm translating the site with my custom theme to another language. The problem is in menu links. On the original language they are fine, but with another one they are looks like "node/id". I've tried drupal_lookup_path with and without language, drupal_get_normal_path, drupal_get_path_alias but links are still the same.

I'm feeling like i've missed something in preference, but have no idea how to make links looks properly.

some code from my draw_menu function:

$items = get_menu_weight($menuName, $language->language);
foreach($items as $item) {
   $alias = drupal_lookup_path('alias',$item->link_path,$item->language);

...

    if ($item->link_path == "http://"){
    $drawItems .= '
'.$item->link_title.'';
   }else{
    if($alias == "/"){
        $drawItems .= '
link_title.'">'.$item->link_title.'';
    }else{
        $drawItems .= '
link_title.'">'.$item->link_title.'';
    }
   }

...

}

Thank you for your advises.

I don't know what get_menu_weight() returns (it is not in the standard Drupal API, is it?), so the following is the answer for a general case in Drupal 7.

In short, as long as the menu item is linked to a node, and if the node has at least one translation, the following code should work to get a path-alias of the node for all the translatable languages:

$hstpath = translation_path_get_translations('node/123');
array_walk($hstpath, function(&$v, $k){$v = drupal_get_path_alias($v,$k);});

gives an associated aray like:

Array(
  [en] => info/basic.html
  [fr] => info/basic.html
)

where both English (en) and French (fr) versions have the same path-alias of info/basic.html.

How to convert this path-string to a link to the node to view in the desired language depends on both your language-detection configuration and with which language environment you would like to display the node.

For example, if the URL with the path-alias is given the highest priority, then add the prefix of /fr/ to the French node (as long as French is not configured to be the default language with no path-prefix defined).  In addition, you may need to add base_path() at the head, if Drupal is not installed in the top directory of the website.

For a reference, a candidate answer to "Menu links not being translated" explains some basic for the Drupal menu with i18n.


Conditionals of a User Role I have a webform where there are conditional elements that are reliant on the user being a bona fide affiliate of our organisation. Both Anonymous and Authenticated users can use this form.

I currently have it using the CiviCRM elements to look for an existing contact in order to fulfill the conditional; however we have found that if we have had contact with the user (ie they previously were bona fide, or have submitted other forms in the past) then the conditional is fulfilled.

(Yes, that is kind of obvious.... we overlooked it)

I think I have three options;

Have a webform field, hidden, pertaining to the user role. this can then be used as a conditional.
Use a Workflow Rule to redirect users with particular roles to a different, but identical, webform. Then I would have two webforms each witht eh appropriate elements.
Completely remove the connection to CiviCRM for the webform and rely on our staff to filter the wheat from the chaff.

Option 1 is probably the most logical solution in my mind, but I can not find a way to poll Drupal for the user role.

I'd recommend using hook_form_alter and user_has_role in a custom module. It allows you to alter the form programmatically and perform logic in your hook function so you can access your user's role and modify your fields that way. For example, you could do something like:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='your_form') {
     global $user;
     if (user_has_role(your_rid)){
       // add the extra field you need here
     }
  }
}

there are many examples on how to modify/add fields in the hook docs link above, plus you can google more tutorials on that.


Set the "from" header in the email to be in the format "Full Name" How can I change the from header in the email sent from Drupal to be in the format "Fullname" <email@address.com>?

I managed to do it on a Drupal 6 site at one point in the past, but I no longer have access to that site, and I don't remember how to do it.

You can use hook_mail_alter() to change the "from" email address of any email sent out from your site. The email address used needs to conform to the RFC standard, which it does is your question's title. But user names can be tricky and might contain illegal characters. There's a comment on the D6 docs that provides a code sample for properly formatting the email address. Your code would look something like...

function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <email@address.com>';
}

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the $message variable from the code sample above.


How to Get Custom Field Label Translation I'm using Internationalization module and in my custom entity type, I have my custom field. Since this entity is going to be usable for all enabled languages, I have added translation to my custom field's label.

In node.tpl.php file in my custom template, I am calling this field values like this:

$field = field_info_instance('node', 'field_custom', 'custom_entity');

And I render the field's label like this:

echo t($field['label']);

However, even though I've added translation for the label, it remains same string for all languages. I'm surely missing something here, how can I implement this?

Thanks in advance.

You cannot use variables in t() function, it accepts only strings and placeholders with an array.

The i18n module has Field Translation module shipped with it, be sure you have enabled it as well.

There is also a good information on the following link about getting title fields translated as well.

Drupal 7 – Translate the title field label of content types


How do I access my fields in a .tpl file I have a file views-view--MyView--block-2.tpl.php

there is no $fields variable, it doesn't exist.

if I do a foreach($view->field as $v=>$f)  and print both $v will show me all my fields in that view and display

created
title
field_op_author_nid
field_main_image_fid
field_teaser_value
comment_count

but $f is always empty.

How do I access my fields?

[EDIT]
Ok, let me clarify. the .tpl file I have renders just fine. the markup I have in that file shows up. The issue is that I cannot access the fields I set up in the view and displaye. I tried changing the filename to include -fields- and I indeed did get the $fields variable. This looks to be exactly the same as the $view variable that I had before, which I don't know how to get data out of. I can see the fields I need in there but the var_dump($fields( or $ view)) is about 20 pages long and every example I have seen has been just using $fields["fieldname"], which does not work.

Am I just maybe doing this wrong entirely? What is the best way to set these up, is it to have multiple tpl files, one for each field and row?

I THINK you need to be using views-view-fields--myview--block-2.tpl.php to access $fields.


Access By Term(abt) is not work in SOLR search Drupal 7 I'm using Access By Term contrib module which is used for show the node when the node term reference and the user term reference is equal. I can get this, Also in solr search, Filter tab setting I have enabled the Node access checkbox. However when I'm searching the particular node title with other user credentials, actuallay the other user cannot be able to search those nodes. Still solr search resulting a node. I want to restrict this??? Is there any way??

I have found a solution. If the Solr server want to obey node access means, we must index the Status and Author field to the server. I have done this, now the node access is perfectly worked even with the search also.


How to remove unused tables in the database in Drupal 7 Is there an easy way to detect tables that are no longer used by my Drupal installation? I find it annoying that tables from previously used modules remain. I'll simply drop them using phpMyAdmin if not, but its a bit of a pain, and involves backing it up for obvious reasons! ;)

I think Schema will tell you that.
If a module leaves tables after uninstall, that's a bug, and you should open an issue.


Views Slideshow alternating blank screens with content items Views Slideshow with JQuery Cycle had been working successfully for a long time, displaying a cycling set of 8 photos with cross-dissolve transitions. Now it's displaying a blank screen between each content item, for the same duration specified for those items in Views>Slideshow>Settings. All content is being displayed, nothing skipped, and transition is correct. But it acts as if a blank item is alternating with the intended content. I tried going back to earlier versions of Views and JQuery but there was no improvement in this problem.

Suggestions on why this might happen and how to fix? Thanks.

I found that the problem disappeared when I disabled the module "devel_themer." I began to suspect it only after looking at the dynamic code in Firebug, which showed the images trying to cycle and to cross-dissolve by animating transparency. I saw a lot of modified code referring to this module name, and figured that since it's not the native code that should be seen here, it would be worth trying the disable and see what happens. Problem apparently solved.


Automatic creation of users I have a big problem. I don't know why, but every day are created users in my site. It's not a normal registration because I have disabled the block for login/registration in my site. The users' status is locked and they are many.

What can I do?

Disabling block is pointless. You need to truly disable registration itself. Go to Administration » Configuration » People and under Who can register accounts? select Administrators only. If that's not enough, make sure you have all security updates installed.

Note: exact path to this setting may be a bit different in Drupal 6 or 8, but you should be able to find it easily enough.


Custom module with custom node type, error Trying to get property of non-object en comment_node_type_delete() I'm quite new with Drupal 7 development, after researching and following some tutorials I was able to create my custom module that defines a new node type with some fields, but now I have a problem when I uninstall it, the hook_uninstall runs almost fine(the node type, the contents from my custom node, and the node fields), except that display this error after the uninstall:

  Notice: Trying to get property of non-object en
  comment_node_type_delete() (línea 344 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module). Notice:
  Trying to get property of non-object en comment_node_type_delete()
  (línea 355 de
  /opt/lampp/htdocs/drupal/modules/comment/comment.module).

This is from mymodule.install:

function mynode_uninstall() {

    $ournewtype = 'mynode';
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => $ournewtype));
    $nodeids = array();
    foreach ($result as $row) {
        $nodeids[] = $row->nid;
    }
    node_delete_multiple($nodeids);
    node_type_delete($ournewtype);
    field_purge_batch(500);
    drupal_flush_all_caches();
}

I believe the problem is that it's expecting an object, and you are passing a string. Try changing this:

node_type_delete($ournewtype);

To this:

$node_type = node_type_load($ournewtype);
node_type_delete($node_type);

One other thing, instead of this:

$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
    $nodeids[] = $row->nid;
}

You can simplify it by using this:

$nodeids = db_query($sql, array(':type' => $ournewtype))->fetchCol();