View to display user points and the reason for the points Using user points module, the users of my site are successfully being assigned points for any content they post or revisions they make and so on. Now when a user logs in, i want the user to be able to see his points and the reason for the points being assigned. The view output would be something like this:

1.Blog Pic A, Blog Title A, Blog TeaserA  (and then)  Points

2.Blog Pic B, Blog Title B, Blog TeaserB  (and then)                     Points

Here then user gets points for their blog uploads. How can i create a view showing the above result. I tried but was not successful. I created a view of user points with Contextual filter  Userpoints Transactions: User and fields as  Userpoints Transactions: Points (Points) . However i am not getting any fields as content:body and so on. I understand i have to add a relationship but i am a bit confused here. I tried adding the relationship  Userpoints Transactions: Entity ID  but the  i get an error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userpoints_txn.nid' in 'on clause'. What is this. How can i create the view for the above shown usecase. It seems a simple solution. What am i missing?

Edit: I tried different views but none are showing what i need. Would appreciate if someone can export a view, or at least, and preferable, guide me so that i also understand where i am going wrong.

I have userpoints active on one of my sites, and the display you are looking for is integrated with the module.

Look at the user account, there should be a tab (Points) (/user/$uid/points).

To create your own page, introduce a required relationship to the users table, then a contextual filter using that relationship on user:uid. When the configuration screen comes up, under 'When the filter is not in the URL' provide a default value > UID from currently logged in user. This should get your view working.

Note: The relationship must be created first, then it is available for the contextual filter.

Edit: Step by step.

Add new view: (/admin/structure/views/add)

In the 'Add View' screen, enter view name, and choose to Show 'Userpoints Transactions' of type 'all'. I chose a Table format to show fields. The rest is adjustable later.

Click 'Continue and Edit' to go to the edit screen.
Add a relationship for 'Userpoints Transactions:User'. Check 'Required' and 'Apply all displays'. This will bring the users table into the view.
Create a contextual filter on 'users:uid' using the relationship you just created. Configure the default value provided as 'UID from logged in user', and Apply.
Add whatever fields you wish and format the view.

This is the export:

$view = new view();
$view->name = 'users_points';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'userpoints_txn';
$view->human_name = 'Users Points';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Users Points';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Userpoints Transactions: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'userpoints_txn';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Field: Userpoints Transactions: Description */
$handler->display->display_options['fields']['description']['id'] = 'description';
$handler->display->display_options['fields']['description']['table'] = 'userpoints_txn';
$handler->display->display_options['fields']['description']['field'] = 'description';
/* Field: Userpoints Transactions: Points */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints_txn';
$handler->display->display_options['fields']['points']['field'] = 'points';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'users-points';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';

Second Edit:

The descriptions shown in the screen print you showed me are not stored in the database, but are generated on the fly when the page is requested.

Here is how you complete the view.

First, install and activate the Views PHP module.

Second, go into userpoints.views.inc and change 'field' => 'nid'; on line 435 to 'base field' => 'nid';. Then insert the following code after line 466:

$data['userpoints_txn']['txn_id'] = array(
      'title' => t('Transaction ID'),
      'help' => t('The transaction ID for the points allocation.'),
      'field' => array(
          'handler' => 'views_handler_field',
      ),
      'filter' => array(
          'handler' => 'views_handler_filter_string',
      ),
      'sort' => array(
          'handler' => 'views_handler_sort',
      ),
  );

This will make the Transaction ID accessible to views. (The necessary changes are included in a patch file linked at the end of this answer.)

Save your view in its current form to clear its temporary cache, then go to /admin/config/development/performance and clear your caches.

Return to your view, and add 'Userpoints Transactions:Transaction ID' as a field, and set it as excluded from the display.

Then add another field. In the 'Add Field' screen, filter on Global, and select 'Global:PHP'.

To configure the field, Create a label of your choosing, and in the Output box add the following:

<?php
$transaction = userpoints_transaction_load($row->txn_id);
$value = userpoints_create_description($transaction);
echo $value;
?>

Note: Do not place anything in the Value box! It is used for another purpose.

Save your view, and you are good to go.

BTW. The changes necessary in userpoints.views.inc are in a patch attached to the Features Request issue I opened on D.O.


Webform for each item in a view I have a view of events and I want each event to have a "Register" button that brings up a webform form for the event. Obviously the filled out form should be saved so that I can tell who signed up for which event. I'm pretty new to Drupal so I'm not sure what the best approach is to associate each event with a webform.

I think first you have to attach the webform to the content type(under webform settings) and then you can use this module https://www.drupal.org/project/webform_default_fields to add fields to the web form.
cheers


How do I change the comment sort order? I am trying to work out how to change the order of a flat list of comments in Drupal 7. It seems that comments are listed in chronological order with the oldest appearing at the top and newer ones appearing further down. Is there some way of reversing this order so that the most recent comments appear at the top and older ones at the bottom?

There is a module called sort_comments but there is no official release version (only dev).  The constraints of the project I am working on does not allow the use of non-production ready modules.

Project constraints also prevent the use of any custom modules.  Only allowed to customize at theme layer (e.g. can create custom theme).

You could use Comment goodness it has a stable D7 release.

  Provides comment sorting, comment form placement and comment form
  configuration settings.


What to do when saving nodes one-by-one and bulk resaving give different results I'm using the Location Taxonomize module with the Address Field module to create a vocabulary of node locations.

I want to re-create the locations from scratch, and I have a term reference field attached to the node.  This term reference field contains a reference to the automatically generated Location Taxonomize vocabulary.

The problem is, after I delete the vocabulary and term reference field and then re-create them, I cannot use VBO to re-save my nodes to automatically generate the Location Taxonomize terms and fill in the term reference fields.  Instead, I have to save the nodes one-by-one, but there are 30,000+ nodes.

In other words: saving nodes individually works fine, but saving nodes in bulk does nothing.

The relevant code from Location Taxonomize Address Field submodule looks like this:

function location_taxonomize_af_element_submitted($form, &$form_state) {
  $lang = 'und';
  // Act on values
  $fields = $form_state['temporary']['addressfields'];
  $items = array();
  foreach ($fields as $field) {
    $deltas = $form_state['values'][$field][$lang];
    foreach ($deltas as $delta => $values) {
      // Don't process 'add more'.
      if (is_numeric($delta)) {
        // Add the Administrative Area name, if possible
        if (isset($form[$field][$lang][$delta]['locality_block']['administrative_area']['#options'])) {
          $options = $form[$field][$lang][$delta]['locality_block']['administrative_area']['#options'];
          $values['administrative_area_name'] = $options[$values['administrative_area']];
        }
        // Add the country name
        $values['country_name'] = location_taxonomize_get_country_name($values['country']);
        $items[] = $values;
      }
    }
  }
  // taxonomize
  if (!empty($items)) {
    location_taxonomize_taxonomize($items, $form, $form_state);
  }
}

As far as I can tell, this code is added by a submit handler, so when the nodes are re-saved using VBO, the submit handler is not called (I could be wrong about this; I am in over my head in this part of Drupal).  What I want to do is force this bit of code to be called with VBO-- I know how to make a Rules action in code, but for nodes, that gives me the variable $node, not $form.  Is there some way to go from $node to $form to run this code?  Or, is there some way to re-save a node in a bulk operation as if it were saved individually?

You are correct that function is attached to the actual edit form when using the field, and therefore is bypassed during a VBO node save. This allows the function to be attached to any entity type that has the field (there are other ways to do this, but this approach was almost certainly easier than other options).

You can get from a node to a form using drupal_get_form() and providing the node as the form_state:

$form = drupal_get_form('YOUR_NODE_TYPE . '_node_form', $node);

Note: I have not tested that solution in your use-case.


Unable to get CKEditor to work using Drupal 7 I've installed the Wysiwyg module for Drupal 7, as well as the latest CKEditor, configured the settings, and yet it refuses to appear! I've gotten other editors to work but they're not as good.

I'm the only one using the site so I don't have to configure permissions right?

I would have thought this would be one of the simpler things to do in Drupal!

Any help greatly appreciated.

Here are the steps that worked for me on Drupal 7.7

Instal the WYSIWYG module and enable
Download the latest CKEditor and unzip it in sites/all/libraries
Go to configuration => wysiwyg and choose the editor for the input format (use it on the full HTML or PHP)
Now you can edit and there you can choose under buttons and plugins what buttons appear
When you create a content type don't forget to set the correct text format

btw a while back I had a problem where the WYSIWYG used the background from my site. I had to change the CSS settings, below buttons and plugins, and set it to use editor default.


What is the correct workflow for updating a high traffic site? I launched a site based upon Drupal 7.14 with at least 100 simultaneous users accessing the site at all times.

From the Devel module, I see that every page is generating about 200 to 400 Mysql requests.

First question: Is that a lot with 5 customs blocks per page?

With the full caching system for anonymous user, the site is running smoothly.

I had to make two updates. For that, I put the site in maintenance mode, made my modifications and uploading new files, flushed the cache and put the site live again.
The first update did not generate any issues. But the second one, my MySQL server crashed due to a huge amount of simultaneous requests.

So how to avoid the flushing of all pages and updating properly JS, CSS and templates files?
What's is the correct workflow? Because after the maintenance, if 10 users request a non-cached page, it's more likely that the server won't be able to handle the load.

Does Drupal automatically regenerate the page cache if a JS, CSS or template associated file has been changed? So, is no flushing needed? The page would be correctly regenerated according to the cache configuration?

Here the server specifications:

ProLiant DL360 G5
CPU Intel Xeon 5133 (dual core) 2GHz
RAM 2×512Mb DDR2

Drush and command line are for rescue here:

1) To clear cache selectivelly, just run drush cc and drush will provide you with different options to select from, so you can clear everything or just theme registry, js/css, views, pages, etc.

2) To regenerate script use this bash script: http://dropbucket.org/node/241. It reads your sitemap.xml and revisits all pages, warming up cache.

3) Additionally, consider using Drush Entity Cache Loader http://drupal.org/project/drush_ecl, it doesn't generate page cache for you, but warms up content cache, so when authorized user loads the page, nodes and other entities are loaded from cache instead of being generated on the fly.


How do you output taxonomy terms and the fields thats attached to it? I have the following issue where I want to output a list of taxonomy terms and the fields it contains. I have a list of taxonomy terms as US States and each term has a field called city. How can I display the State and City in Drupal 7 Views 3?

I added the field All taxonomy terms and I dont' see any option to display its fields in anyway.

You just need to add these 2 fields to your view (and remove the "all taxonomy terms" field you've already added):

 Taxonomy term: Name

 Taxonomy term: City

Your precise field names may vary.

I was able to do a test view like this and State and City display OK.

I'm not doing any fancy relationships or anything with the view. If you don't see these fields as options, it may be we have different modules, but I'm also Drupal 7 views 3.


Adding block in view tabs I have tabs created using views and has contextual filter of group parent(Group ID from URL). I created a block that has a contextual filter of GID. In the block layout, I placed the block in the content region, select Group from URL to Group ID: and specify path to be shown--that is links of my tabs.

My goal is that whenever I access each tab links, the block content will be shown according to group ID from the URL.

Given example:

Group-A(GID=1)
Group-B(GID=2)
http://localhost/tab/1/dogs
http://localhost/tab/2/dogs

Problem:

My tab view with contextual filter is working but block is not showing up. How can I properly configure the block view setting to be consistent according to the GID?

See photo below for my block settings:

In your view, change the contextual filter to the following:
change:
Hide view
by
Provide default value
In Type, select the option that applies.


How to get the user ID from the last profile page? So, I have a user's profile page where there is a Message button. When I click the message button it should redirect me to a custom page with a form in it. How can I get the user ID from the profile page I visited in order to know where to send the message?

The easiest way would be to add the user id as a ref argument to the form url in your message button, on the user profile page:

<a href="/path/to/custom/form?userid=<?php print arg(1); ?>">go to custom form

Then, on your custom form:

$args = drupal_get_query_parameters();
$userid = (isset($args['userid']) ? $args['userid'] : false);


E-mail results from page callback I have a menu hook and page callback which takes several arguments to generate some table data in a page, the page makes heavy use of entityfield_query and some other modules.

I need to be able to e-mail the contents of this page based on a set of periodic dates. What's the best way to achieve this?

I realise that the css will all have to be added to the page but if I could get the structure into an e-mail that would be a start.

You can use drupal_mail() together with hook_mail() to send email.

See also the Examples for Developers.


URL Alias Preventing a Pattern on Vocabulary I am trying to setup a replacement pattern with URL Alias on a vocabulary called 'Media Categories' using the pattern 'media/[term:name]'.  However whenever I try and generate the aliases this vocabulary is left unchanged.  I have tried changing the pattern to something else like 'edia/[term:name]' and that works, it seems as though it is reserving the 'media/[term:name]' somewhere.

I have tried flushing the cache, deleting the vocabulary and terms and adding them again, however I have still had no success.  The only option I have had so far is to manually enter the url alias.

Has anyone come up against something like this before?  All I can think of is that 'media/[term:name]' is reserved somewhere...

Ok thanks to Digital Fire, I started checking for other alias conflicts, which I found in my defined views.  The problem I had initially was that the URL alias was working with views, however clicking on the link / taxonomy term took you too the default drupal view.

So in order to get the term with an alias working with view's I realised that in the view path use the original link to the taxonomy term instead of the url alias.

Hopefully that makes sense and might help someone else out.


Why does the favicon sometimes not show up and generate "page not found" errors, and other times does show up As the question implies, on occasion Drupal's log is showing that the favicon is not found. Indeed, it does not show in the browser tab or address bar. At other times, even within the same surfing session, it does show up.

Why does it do this and how can I prevent it so that the favicon will always show?

I am using version Drupal 7.22. with a custom subtheme and an admin theme (Stark).

My favicon is set in the subtheme theme configuration at sites/default/files/images/favicon.ico and that is located there as I have checked via FTP.

The log shows the browser is looking in example.com/favicon.ico.

The custom subtheme I use has <link rel="shortcut icon" href="http://example.com/sites/default/files/images/favicon.ico"; type="image/vnd.microsoft.icon" /> in the source code and the admin theme (Stark) uses <link type="image/vnd.microsoft.icon" href="http://example.com/misc/favicon.ico"; rel="shortcut icon"> and this file also exists in that location (not actually using example.com, of course).

Drupal is using clean URLs.

The web server is Apache on Debian Linux.

Thank you.

Some browsers search for favicon under http://example.com/favicon.ico without checking. But they are minority now.

Most respect:

<link rel="icon" href="http://example.com/img/icon.png">

as described by W3C.

If your site tries to use <link> approach but fails on some pages, like admin pages rendered using different template, and you do not have favicon.ico in default location, you will get exactly described effects.

If browser is looking for  http://example.com/favicon.ico when you have proper <link rel="shortcut icon"> it is a browser problem, not yours. It means browser (or at least that part of it's code) is outdated, unless it looked under correct URI first and got another error, but then you would see two errors in log, one for right place, second for outdated one. In Mozilla's queue there is a number of reports about improper favicon detection by FireFox - in example this one. It shows how even modern browsers can sometimes fall back to old methods.


What is the purpose of the config/install directory? I was trying to use omega theme and found lot of files under omega/config/install. E.g. block.block.omega_account_menu.yml, block.block.omega_branding.yml, omega.layout.omega_default.yml. I wonder what are the functionalities of these files and how are they being used. Is there any guide to follow? How can I create another one and how can I use it?

The config/install directory contains the default configuration of a theme/module. Its purpose is explained in Include default configuration in your Drupal 8 module, which says:

  In Drupal 7 default configuration for modules such as content types, field configuration, views, etc. required custom PHP code to install and keep updated. In Drupal 8, these are stored with the configuration system in plain text YAML files.

  For example the configuration management system takes care of creating and managing content types. You can ship a content type with your module by creating a properly named and structured configuration file.

Then, it adds:

  You can include default configuration for other things like block placement, views, text formats, editor configuration, user roles, etc. with your module the same way.

Drupal core itself uses files like block.block.bartik_powered.yml, or block.block.seven_messages.yml.

I didn't find a description of the content, but if you look at the content of those files, you can understand what you need to put.

langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - seven
id: seven_messages
theme: seven
region: highlighted
weight: 0
provider: null
plugin: system_messages_block
settings:
  id: system_messages_block
  label: 'Status messages'
  provider: system
  label_display: '0'
visibility: {  }

Note that the file declares its dependency from the System module because that is the module implementing the block plugin (plugin: system_messages_block).


How to refresh new migrations in Drupal 8 migration module? When writing Drupal 8 migrate processes I only can refresh new migration processes if I reinstall the custom migration module. drush cr doesn't work.

Explanation:

I have one module, ie: cm_migrations, which have 2 migrations:

cm_users
cm_tags

With drush ms I see:

Group: beer     Status  Total  Imported  Unprocessed  Last imported
 cm_users        Idle    3      3         0            2016-02-09 16:56:25
 cm_tags         Idle    4      0         4

I write a new migrate process:

cm_beers

I execute drush cr; drush ms and I see the same table as previous.

Only when I uninstall and install cm_migrations I can see the three migration processes:

Group: beer     Status  Total  Imported  Unprocessed  Last imported
 cm_users        Idle    3      3         0            2016-02-09 16:56:25
 cm_tags         Idle    4      0         4
 cm_beers        Idle    4      0         4

Any clue about  how can I refresh the migration processes without reinstall the module?

Thanks

I found this worked for me

  drush config-import --partial --source=modules/custom/migrate_module/config/install/


Question related to page-user.tpl.php Is there a way to tell when we are in the /user/1/edit page vs in the /user/1 page when inside the template file page-user.tpl.php?

Are there any of the $variables that I can check?

I think I would rather check this, than create a nearly identical template file called page-user-edit.tpl.php. Or is there a better way?

Check for arg(2) to differentiate both paths. Arg() function docs.

In case user/1 arg(2) will be Null

Incase user/1/edit arg(2) will be 'edit'


Drush: --yes-if-newer behavior with pm-download? I'm writing an Acquia Cloud Hook where I install Registry Rebuild. In the interest of performance, I'd like to only install it if it's not already at the latest version. In other words, --yes unless it's already the current version.

Is there a simple way to do this in current Drush or shell?

I'm afraid there is no easy way: as the command version isn't stored in any file, there is nothing to compare with. If you really want to do it, you can download the command and run a diff with the version you have, and install it if it differs, but I doubt the efficiency of such a check compared to install it in any case


Domain Access Login Redirect for main domain and subdomain I have created three sites namely one.example.com, two.example.com, three.example.com using domain access. Here one.example.com is the main site which can create n number of subdomains. I want to redirect the admin of one.example.com to the dashboard and the other two to their respective content listing page. I'm using rules to redirect the admin of one.example.com to the dashboard. But when i login from the two.example.com, it also redirect to the dashboard which returns a "Access denied" page. How to set login redirect separately for subdomains. Please Help. I'm struck!

I solved this issue by creating two different roles and by adding a condition for "User has roles". So admin for one.example.com and sub-admin for two.example.com and three.example.com. Currently it works greats according to the condition. But is there any way to set the rules for same role with different actions?


Drush not "seeing" Drupal installation I have a drupal installation running in a vagrant virtual machine.  This works fine, but when I try to use Drush on this site I get very peculiar behavior.  The modules that are listed when I run "drush pm-list" are all from a non-existent Drupal 8 installation.  I have tried setting --root= and --uri= but to no avail.  Drush simply ignores my real Drupal 7 installation and instead outputs non-existent modules from a non-existent installation??

Try running drush from inside the VM.

First, use vagrant ssh to get inside.

Then, change directory to the docroot:

cd /vagrant/docroot/

You should be able to run Drush commands from there.

In theory, if you know how to set up Drush aliases, you won't need to do that, but this method is a useful shortcut.

Let me know if it works -- and good luck!


Creating content regarding to node address arguments Say it I have such node alias:
example.com/content/my-fancy-page/

If user enters to node above, he will see default page content of my fancy page.
After some process I will redirect him to this:
example.com/content/my-fancy-page/tt3741/
or this
example.com/content/my-fancy-page/tt3802/

Regarding to user's selection he will see the "tt3741" or "tt3802" content that resides inside database. Is it possible to do this with hooking etc. When I try "example.com/content/some-old-page/foobar" in my old website I get 404 error. So is it nt possible?
Is it possible to cache these three addresses seperately with Boost module? Or Boost only caches "/my-fancy-page/"

Path aliases must be exact, thus if you want my-fancy-page/tt3741 to work you need to create an alias for it. If you link to the node path node/6 then node/6/tt341 will work. This has to do with how hook_menu works vs how path aliases work.

If you wish to hack around how path aliases work you can try out the PURL's Path Extensions feature http://drupal.org/project/purl or use hook_url_inbound_alter() to get the correct node given the unique alias.

Boost will work as long as each URL is unique (same as drupal's core cache). Good luck.


After Creating A new User inside RULES, I can not access to UID In my rule, I have an action that is "create new entity" with "user" bundle.

every thing works fine a new user create with provided information (user and email)

it's variable name is new_user

in next action, I unblock the new user and it works correctly.

but in next action when I tried to debug "new user" via devel action, It seems it doesn't collect the information of new user

I have attached the devel result. I see no UID and no other information from new user.
Also send welcome messages actions don't work and no email is sent to new created user.

Please tell me what my mistakes are.

Thanks a lot

Use the action to save the entity. The user only gets the UID when saved, not when created.


How do I find out what controls access to a page? I'm surprised by finding that I can't access [some-path] on my site, and I don't know what to do?

Where do I begin searching? What is the fundamental most level to start from?

For Drupal 6 and 7, the basic access check details are stored in the table menu_router.

To find out the relevant details, try a query like

SELECT path, access_callback, page_callback FROM menu_router WHERE path LIKE '%user%';

Lets look at three examples returned by that query on a local site of mine:

| path                | access_callback  | access_arguments   | page_callback
| user                | 1                | a:0:{}             | user_page
| user/%/edit/account | user_edit_access | a:1:{i:0;i:1;}     | drupal_get_form
| user/%/display      | user_access      | "administer users" | ds_contextual_page_tab

The data above has been manipulated slight for brevity.

First: user. userhas an access callback of  1, which means it will always pass. This is not, as one might think, to allow everyone access, but usually rather because the access decisions for this particular path are complicated enough to require more than a regular permission. Because of that, we need to look at the next column, which is page_callback. This tells us which function is called to actually handle the page, and page_arguments, in this case empty, could contain any arguments passed to the same function. In this case, there are no arguments, so we can't learn any more here. One needs to start reading the code of user_page() to figure out more.

Second: user/%/edit/account. This path has a standard access_callback, which means that user_edit_access is called, and if it returns TRUE, we'll be given access. One needs to read that function to find more details.

Third:  user/%/display. This one is the easiest. user_access simply checks if the user has been assigned the permission that is passed in from access_arguments, so in this case administer users. If that permission has been checked for the users role, access will be granted. User 1 automatically gets to bypass such checks.


Do I need to delete uploaded files if I only want to parse them I'm building an upload form for uploading files which are only parsed, and don't need to stay on the server.

I have this code:

$validators = array('file_validate_extensions' => array('xml'));
$file = file_save_upload('file', $validators);

After which I parse the file.

As I understand it, it saves in tmp by default. Now if I don't do anything else but parse that file, will Drupal or the OS discard the temporary file automatically or do I need to do something else in my code to achieve that?

According to the docs for file_save_upload() the file will be registered as a temporary file, so that it will be deleted anyway, assuming you have cron running on a regular basis.

  "The file will be added to the {file_managed} table as a temporary file. Temporary files are periodically cleaned. To make the file a permanent file, assign the status and use file_save() to save the changes."


Managed file: the file used in the field may not be referenced I am having some issues with the managed_file type. Whenever I try to edit and save a form that has a managed_file element in it an error occurs: The file  used in the Picture field may not be referenced.

This is the code I'm using:

function foo_form ($form, &$form_state, $foo) {
  ...
  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Picture'),
    '#default_value' => (isset($foo->file->fid) ? $banner->foo->fid : ''),
    '#upload_location' => variable_get('foo_upload_location'),
  );

  if (isset($foo->file)) {
    $form['current_file'] = array(
      '#type' => 'hidden',
      '#value' => $foo->file->fid,
    );
  }
  ...
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  return $form;
 }

function foo_form_submit ($form, &$form_state) {
  $foo = (object)$form_state['values'];

  $current_file_set = isset($form_state['values']['current_file']);

  if ($form_state['values']['file'] != 0 && !$current_file_set) {
    // Load the file uploaded in the form.
    $file = file_load($form_state['values']['file']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);

    $foo->file = $file->fid;
  } else if ($form_state['values']['file'] != 0 && $current_file_set) {

    // If we are uploading a different picture, delete the old one and save the
    // new one. If not, don't do anything.
    if ($form_state['values']['current_file'] != $form_state['values']['file']) {
      file_delete(file_load($form_state['values']['current_file']));
      // Load the file uploaded in the form.
      $file = file_load($form_state['values']['file']);

      $file->status = FILE_STATUS_PERMANENT;

      file_save($file);

      $foo->file = $file->fid;
    }
  } else {
    file_delete(file_load($form_state['values']['current_file']));
    $foo->file = null;
  }

  ...
}

I traced the error back to the file_managed_file_validate function in modules/file/file.module but don't know anything about the file references.

The solution is to add a call to file_usage_add after the file is saved. This call adds a reference to the file in the database. The file_managed_file_validate function will spot the reference and won't trigger the error.

file_usage_add($file, 'foo', 'foo', $foo->id);

This isn't documented in the Form API under the managed_file example.

This issue is being discussed on the Drupal documentation issues: link


How do I organize webforms in admin panel I want to customize the Webforms Admin view.
Place all the related webforms in a groups and control who can access the groups.

For example I have many departments. I create a group to each department and allow group members to access  the webforms and not other departments.

Can anybody direct me how to achieve this?

How many Webforms do you have? I have worked on huge sites, and I have never had enough forms to even fill one page.

As for filtering, you can already go to /admin/content and filter by Content type = webform, or just go to /admin/content/webform.

If you need even more control over filtering, then you need to create a custom administrative View. With that, you can add filters for whatever you need, and pagination.

Group level access permissions are more difficult, but not impossible. Start here: https://www.drupal.org/project/permissions_per_webform. If that is not what you need, then look at the many other  modules available for controlling access/permissions.

Last, I think your question was voted down because of several things. First, it is not helpful to make general negative comments like "not well organized". Second, this is not the place to make demands for new features. Third, is the fact that you don't seem to have done even basic searches for the functionality you need.

Last, is your presumption that webforms need to be changed to suit your use-case. Drupal is very powerful because it is modular. Just because you need a certain set of features does not mean that those very specific features would be helpful to anyone else. You should be able to build the functionality you need, but the key word here is "build". Drupal gives you the power to add a GPS to a lawnmower, but that doesn't mean you can demand that every lawnmower sold has a GPS.


drush "The drush command 'self-update' could not be found." I'm trying to figure out why many drush commands aren't working.

drush theme list also reports:

  The drush command 'theme list' could not be found.  Run drush
  cache-clear drush to clear the commandfile cache if you have
  installed new extensions.

I'm mildly certain I installed drush via brew install drush.

Any tips?

self-update was removed a while ago. I'm not sure what the official replacement is, but a simple git pull; composer install does the job for me with the latest version (run it in the drush lib folder, probably in /usr/local/Cellar if it was brewed).

theme list (and theme) don't appear in the list of available commands (although self-update does, ironically). Maybe you're looking for

drush pm-list --type=theme


How to exclude current page from Views results when "taxonomy term ID (with depth)" is set? I have a Views block that has the intention to display all nodes that share the same parent term.

For example:

Queensland

Cairns
Brisbane
Gold Coast
Port Douglas

If I'm on the Cairns page, then it will show all the children of Queensland. The problem with this is, I need to exclude Cairns, as I'm already on this page.

I already tried the solution from "How to list similar products using views in Commerce Kickstart?", but it didn't work. I had an issue where the query preview wouldn't even show, even though I entered the term ID to attempt to get the query.

Any ideas why this would happen?

Notes:

I already entered the term ID to update the preview, but it didn't show anything. If I take the nid filter out, then it works fine, with the caveat that it shows the current page in the results.
I notice something weird where checking exclude in the nid contextual filter shows all the results including Cairns, yet when I uncheck it, then all the results disappear. Is there a reason this would happen?

Query Preview will not be show when you add contextual filters.

You will need to add 'nid/termid' in "Preview with contextual filters:"

In short, Contextual filters will take nodeid/termid from URL.


Views: how can I cleanly add a row of arbitrary text within a collection of fields? I have a view that displays fields.  I want to add a text-based explanation as one of the rows in the view.  The display looks like this:

Field A (Picture)
Text 1: A row that contains explanatory text that appears regardless of whether there is any data below or not
Field B (Data- may or may not be present)
Field C (Data- may or may not be present)
Field D (Data- may or may not be present)
Field E (Data- may or may not be present)

What I'm currently doing to implement Text 1 is adding a field that will definitely always be available (user ID, etc.) and rewriting it to show the text I want to display.  This does what I want but it feels like an ugly hack.  Is there a better way to do this?

In Fields, select Global from the Group Dropdown and then you can select Custom Text and set it up pretty much anyway you'd like; at least in Drupal 6 and Views 3 anyway.


Override page.html.twig with custom module template I want to override the page.html.twig template from a custom module. I know how to create a suggestion, but I would like it to find the template file in my custom module.
function promo_accc_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'page__promo__accc';
}

I'm not sure what I would need to do from here to get Drupal to look in /custom/modules/promo_accc/templates.

drupal_get_path('module',$module_name)  function will return the path to your custom module so:
function promo_accc_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    $suggestions[] = drupal_get_path('module','promo_accc').'/templates/page__promo__accc';
}

for more info about the drupal_get_path() function: https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_get_path/8.7.x


How do I save data into a custom table on form submit? Number of columns in my custom table is huge. How do i insert data in custom table on form submit in Drupal 8?
I want to use something similar to drupal_write_record('table_name', $form_state['values']); in Drupal8.

As per the change record, drupal_write_record has been removed, with the new advice being:

  Developers should use \Drupal::database()->merge(), the Entity API or one of the provided services, like key value.

As you're using a custom table, you'll need the first method. An example from that change record:

\Drupal::database()->merge('example_deleted_entity_statistics')
  ->key(array('type' => $type, 'id' => $id))
  ->fields(array('count' => $count))
  ->execute();

As always, inject the database service if possible, rather than requesting it from \Drupal.


How to (reliably) add jQuery plugin to Drupal This question has been asked, but not really answered. It is NOT as simple as has been suggested in

This response

If it were, there would be no reason to have a module like
jquery_plugin

Simply putting a line in the theme info file like

scripts[] = js/jquery.scrollme.js

Does not work. In the case above, the script does actually show up on the rendered page, but the function(s) within it result in "undefined".

In the case of scrollme.js, are there dependencies that need to be included?

I fought this thing with hoverintent for a day or two, and finally just punted and added the module "hoverintent".  And incidentally, the fact that the hoverintent module exists suggests strongly that one can not simply throw the hoverintent.js code into a directory and load it with a script from the theme info file.

Any experienced direction would be really appreciated!

You embedded your module the right way. The error stems probably from the fact, that ScrollMe needs jQuery 1.8 minimum, whereas Drupal 7 only ships with 1.4.

You have many options of updating your jQuery version in Drupal.


Drupal 7 Ajax Form, add elements dynamically to a fieldset I have the following form:

  $form['#tree'] = TRUE;

  $tasks = array(
    'Julia',
    'John',
  );

  foreach ($tasks as $task_key => $task) {

    $form['task_fieldset'][$task_key] = array(
      '#type' => 'fieldset',
      '#title' => $task,
      '#prefix' => '
',
      '#suffix' => '
',
    );

    if (empty($form_state['num_todos'][$task_key])) {
      $form_state['num_todos'][$task_key] = 1;
    }

    for ($i = 0; $i < $form_state['num_todos'][$task_key]; $i++) {
      $form['task_fieldset'][$task_key]['todo'][$i] = array(
        '#type' => 'textfield',
        '#title' => t('Todo'),
      );
    }

    $form['task_fieldset'][$task_key]['add_todo'] = array(
      '#type' => 'submit',
      '#name' => 'add_todo_' . $task_key,
      '#value' => t('Add more'),
      '#submit' => array('custom_mod_example_ajax_collection_add_todo'),
      '#ajax' => array(
        'callback' => 'custom_mod_example_ajax_collection_callback',
        'wrapper' => 'task-' . $task_key . '-fieldset-wrapper',
      ),
    );

  }

  return $form;

These are the callbacks:

function custom_mod_example_ajax_collection_callback($form, $form_state) {
  $name = $form_state['triggering_element']['#name'];

  $task_key = (int) substr($name, strpos($name, "_") + 1);

  return $form['task_fieldset'][$task_key];
}

function custom_mod_example_ajax_collection_add_todo($form, &$form_state) {
  $name = $form_state['triggering_element']['#name'];

  $task_key = (int) substr($name, strpos($name, "_") + 1);

  $form_state['num_todos'][$task_key]++;
  $form_state['rebuild'] = TRUE;
}

And the form looks like this: http://imgur.com/a/ZJ0ky
The problem is that when I click on "Add more" on John fieldset, it changes to Julia. What have I done wrong?

It works as expected when I try Add more on Julia, however.

The problem was in the AJAX callback, and specifically the code line:

$task_key = (int) substr($name, strpos($name, "_") + 1);

The buttons are named add_todo_key, and the code above returns todo_key, and not the key.

It was solved simply by using strrpos, which find the position of the LAST occurrence of a substring, rather than strpos that finds the first.


Add help text to checkbox options on node form How can I add help text to each option on checkbox option on drupal node form. I do not want to add this from UI while adding values for the field. Using hook_form_alter I do not believe we have option to add description to options of a checkbox field.

Example: "which game you want to play" is the checkbox field.

which game you want to play?

[] cricket

-- cricket is awesome.

[] football

-- football is more than awesome.

I tried to do this first by overriding checkboxes theme hook theme_checkboxes($var) with preprocess hook template_preprocess_checkboxes($var) but there was not any option to set #suffix property to individual checkbox, Then i figured out that theme_checkboxes theme hook call the theme_checkbox hook for individual checkbox then i tried to override theme_checkbox($var) with template_preprocess_checkbox($var) but that also didn't worked, I was able to set #suffix and #field_suffix property on individual checkbox but that was not rendering because individual checkbox's #processed property was already set to True, I tried by setting that false but no success :(

I tried by setting pre_render callback and process callback but too didn't worked, May be i was making some mistake.

This is preprocess hook for checkboxes theme hook:

function template_preprocess_checkboxes($variables) {
  $variables['element']['element_name']['#printed'] = FALSE;
  $variables['element']['element_name']['#processed'] = FALSE;
  $variables['element']['element_name']['#suffix'] = 'This is help text';
  $variables['element']['element_name']['#pre_render'][] = 'mymodule_checkbox';

  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'][] = 'form-checkboxes';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
}

function mymodule_checkbox($var){
  $var['element']['#suffix'] = 'this is help text added by pre render callback';
}

Then i tried the same with template_preprocess_checkbox($var)

function template_preprocess_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';

  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  if ($variables['element']['#parents'][0] == 'parent_field_name') {
    $variables['element']['#attributes']['#processed'] = FALSE;
    $variables['element']['#attributes']['#field_suffix'] = t('This is simple help text');
    $variables['element']['#suffix'] = 'another suffix';
  }

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

Can someone help me too on this?


Can't disable or enable any module I recently moved a project from one server to another. the server is running on nginx.

I noticed some issues like that I cant upload any picture to ckeditor using imce module (I can upload images via filefield) then while trying to fix this issue I encountered this problem that I cant enable or disable any module.

It's like when I check/uncheck a module and hit submit on module's list page, it refreshes but nothing change afterwards.

the other thing is Im running another website on this server with the same version of drupal and it just works fine, I wonder what could be wrong? is it a server issue or a drupal problem?

I'd really appreciate any help and tips.

Well I tried alot of approaches, the last thing that I would think of was the solution, it was because clean-url ,  I just enabled it in server and it start working just fine again.


Updating a modified image file across entities using it I have a content type named "Affiliate" which has among others a field storing a logotype image. The image is then displayed in a ticker (jCarousel) using a dedicated image style.

After I created one node and attached a logotype to it, I made several copies of that node, differing in text, but sharing same image. I was aware of situations where a logotype has to change but thought that solution would be "scalable" due to the fact that the image reference is shared. Now - kaboom! - the image has to be replaced with a new version. I thought I'd get away if I replaced the original image on the server and then deleted the derivative styled copies from the styles directory to make Drupal recreate them afresh. No go.

The problem is that the new image is used but with old dimensions (both in the node display and ticker), which causes distortions. I have to relink the node with the image, one by one to make it notice the new dimensions. Is the size of the original image stored somewhere in the node? What is the sneakiest way to go in such situations?

The image width and height are stored in the field tables (field_data_FIELD_NAME/field_revision_FIELD_NAME), in the FIELD_NAME_height and FIELD_NAME_width columns.

If you know the file id (fid) of the file you need to change the data for, and the width and height of your new image, you can just run the following queries against the database:

UPDATE field_data_FIELD_NAME
SET FIELD_NAME_width = WIDTH, FIELD_NAME_HEIGHT = HEIGHT
WHERE FIELD_NAME_fid = FID

UPDATE field_revision_FIELD_NAME
SET FIELD_NAME_width = WIDTH, FIELD_NAME_HEIGHT = HEIGHT
WHERE FIELD_NAME_fid = FID


Photo-swipe is not loading in my website I'm using drupal -7 with mobile_jquery(https://drupal.org/project/mobile_jquery) as theme

and PhotoSwipe .

The PhotoSwipe is not working in the gallery page.When we click on the thumbnail ,the image will not load first time and show the blank screen with below message

  undefined

and we can see path of the image in the address-bar.When we refresh the page the PS will work.But something missing ...
website: http://www.w3qatar.info/aldarmobi .

properties >> please click on any property and you can find more images >> Click on any image to see the PS.

I don't know what is the reason for this.Please help me to solve this issue.

Please suggest me any other image gallery module which works on ios,android devices.

I am using the Juicebox module in my Drupal 7 site for swiping.  With my iPhone 4, it is working super. I have tried other solutions, without luck.  The free version of Juicebox allows you to place 50 pics in a box.


How to reuse object between Drupal Behaviors? We have a JS file (basic-page.js) that has the following Drupal Behavior. In this, we created what we believe is considered a Drupal object (need help with correct term) that contains a function that can be called. In the latest request, we need the ability to reuse the same code from the Drupal Behavior in another Drupal Behavior.

How could we reuse the code? Currently the article.js is not able to use the code from basic-page.js, no errors or warnings are given.

basic-page.js (where Drupal object resides)

(function($) {
  'use strict';
  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

  Drupal.behaviors.customName = {
    attach: function(context, setting).once('customName').each(function() {
      /* behavior runs here */
      var func1 = Drupal.customObj;
      var results = func1.function1($('body'));
      //process results
    });
  };
})(jQuery);

article.js (where we want to reuse Drupal.customObj.function1)

(function($) {
  'use strict';

  Drupal.behaviors.articleResults = {
    attach: function(context, setting).once('articleResults').each(function() {
      /* behavior runs here */
      var customObj = Drupal.customObj;
      var results = customObj.function1($('body'));
      //process results
    });
  };
})(jQuery);

I'll focus on the inclusion first, then describe what Clive was referring to, while mentioning that your JS is not valid:

For your use case you should add a common library to your module/theme that extends the Drupal object. (You don't even have to extend the Drupal object, but can create an own one, if you prefer.)

Then use dependencies to make sure the object is available in your basic page JS, as well as in your article JS.

Example

In your *.libraries.yml

mymodule/common:
  js:
    js/mymodule-common.js: {}
  dependencies:
    - core/drupal
    - core/jquery

mymodule/page:
  js:
    js/mymodule-page.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

mymodule/article:
  js:
    js/mymodule-article.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

You can then split your JS to the three separate files containing your code. The dependencies section makes sure the scripts your library depends on are loaded before.

Now to the scripts itself:

mymodule-common.js

(function($) {
  'use strict';

  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

})(jQuery);

mymodule-page.js

(function($) {
  'use strict';

  Drupal.behaviors.customName = {
    attach: function(context, setting) {
      $('body').once('customName').each(function() {
        var func1 = Drupal.customObj;
        var results = func1.function1($('body'));
        //process results
      });
    }
  };

})(jQuery);

And similar in your mymodule-article.js.

And here the promised feedback to the comment of Clive: Compare the attach property in the last example. It expects a callable that will be executed every time a page/ajax load finished. Within its body you can then do your magic.

References:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Webform : how to count and live display results Update

webform_get_submission_count isn't precise enough (we need to count into submissions)

but

<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  if ($node->type == 'webform') {
    $count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
    $atelier_1 = "sources" ;
    $sql = "SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE \"".$atelier_1."\" ;";
    $count_atel_1 = db_result(db_query($sql));
  }
}
echo $sql;
echo $count_atel_1;
?>

This webform has been submitted <?php print $count ?> times.

looks ok

end update-------------------

We'd like to use a webform so that our students should register on some workshops.

The webform works great. Now we'd like to display live the number of students that are already register in on of the workshops so that the other should know if there remains some possibilities of registration (each workshop can only accept 20 students at the same time)

I'm trying with that that doesn't work ($atelier_1 = "sources" ;) is the name of one workshop :

<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  if ($node->type == 'webform') {
    $count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
    $atelier_1 = "sources" ;
    $count_atel_1 = db_result(db_query('SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE %d', $atelier_1');
  }
}

echo $count_atel_1;
?>

Any help or suggestion welcome

I looked through the Drupal document from drupalcontrib.org and i saw that there is webform_get_submission_count function to get a count of the total number of submissions for a node. I think you can use that function instead by create a new one.


How do I add a link to the category in menu? Now this might be a dumb question, but it's not obvious. Seriously. I have a menu with node/ID links as paths, but I also need one link to the category in the menu. I know that pasting in absolute urls or slugs is not a good idea. But how do I do it otherwise?

Have you tried a root link, one beginning with a slash? such as /taxonomy/term/34


Disable the message shown when a node is created I'm using Rules to redirect the user to a different page after a node has been created.

Is there an easy way to suppress the sticky "XXXXX has been created" message?

It's node_form_submit that is creating those messages. You could pretty easily use hook_form_alter on the node form and use your own version of node_form_submit instead. All you would need to do, would be to copy the function and add an user_access('whatever') check before that message is created.

Alternatively, you could in preprocess_page function, check which messages is being served, and remove unwanted ones, but that would be a bit more tricky. Should be possible with some regex. On the other hand, this method would be a bit more upgrade friendly, since you could remain using the node_form_submit function and would get future changes if any.


how to use panels on custome front page I have created a custom page in Drupal 6 and named it page-node-1.tpl.php.
I want to create a panel drag and drop on this page. But when I create a panel it will assign a different name to the panel page. How can I create a panel page for my page-node-1.tpl.php?

I'm new to Drupal, thanks in advance.

The correct way to set a page using Panels (I'm assuming Panels 3) in Drupal would be to go to the Panels interface and click "Add custom page". You can give that page any path you want such as /home - the path doesn't actually matter. Then, from the admin options: Administer -> Site Configuration -> Site information you can change your default front page. Input the path that you used when creating your new panel.

This will give you a new custom panels page that will show up as the default front page at www.yoursite.com

This video will walk you through the process step by step.


How to programmatically create a node on user registration with the user as author? I want to create a single node of content type XYZ for each user upon registration.

I tried to use hook_user_insert() (hook_entity_insert()), but this doesn't work because when I set the nid to the uid, the uid is still 0 (anonymous user), and the node needs to be assigned to the newly created account. (NOTE: This was my misunderstanding, see below.)

I want to create the nodes upon account creation because each user should have only one node of this content type.

In Drupal 7, I managed to do this in Rules using a rule set in which I saved the user account and then created the new node.  Since Rules isn't in beta for Drupal 8 yet, I am trying to do this programmatically.

Here is the code I am using:

function MYMODULE_user_insert(Drupal\Core\Entity\EntityInterface $entity) {
  $user = \Drupal::currentUser();
  $profile = Node::create(['type' => 'userprofilenode']);
  $profile->set('uid', $user->id());
  $profile->enforceIsNew();
  $profile->save();

As noted in 4k4's answer, $entity already has a UID.  The problem is that I mistakenly introduced the current user, which is 0 (anonymous).

In an insert hook the user is already saved and should have an user id. So creating a node and assigning it to the new user as author should be no problem:

/**
 * Implements hook_ENTITY_TYPE_insert() for user entities.
 *
 * Adds a first node for a new user
 */
function mymodule_user_insert(\Drupal\user\UserInterface $user) {
  \Drupal\node\Entity\Node::create([
    'type' => 'XYZ',
    'title' => 'First node for user #' . $user->id(),
    'uid' => $user->id(),
  ])->save();
}


Best way to modify views output with a custom function? I have view with a block display that shows user profile info and the user's points (from user point module). I want to show the "point level" which is a text string based on the number of points the user has.

How do I add that to the block?

I already have a custom function that returns a text string based on the number of points.

I don't want to use views_PHP anymore because it prevents caching of the block.

Should I use hook_block_view_alter()?

I would much prefer a solution that I would allow Views to the render the text you want directly, so technically, I'm not going to answer your question here.

My suggestion is that you add a new formatter, that you use to directly render the user points as a text string instead. This allows your level to work correctly with all of core, not just one particular block. You can then just add user points twice to the View, with different formatters.

I haven't given the particular code below a proper test, as I don't use user points anywhere, but it's copied and cleaned up from live project where I use do something similar, so I know that it works.

/**
 * Implements hook_field_formatter_info().
 */
function user_level_field_formatter_info() {
  return array(
  'user_level' => array (
      'label' => t('User level'),
      'field types' => array('user_points'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function user_level_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $user_level = 'green';

  switch ($items[0]) {
    case > 5000:
      $user_level = 'veteran';
    case > 2500:
      $user_level = 'experienced';
  }

  return array(0 => array('#markup' => $user_level));
}

The code above assumes that user points is a real field on the user. If that is not the case, then you can add a new text field on the user, set 'field types' to array('text') instead, and in the formatter grab the number of user points directly from user points, with say a user_load($uid), instead of from $items[0] as I do. You will probably also hide the textfield from user_edit with a hook_form_alter.


How to change form_set_error() message in captcha module I need to reset the default error message in the captcha module when you enter the wrong answer.

captcha.module line 616

form_set_error('captcha_response', t('The answer you entered for the CAPTCHA was not correct.'));

I'm not quite sure where this needs to be done. Preprocess function?

Thanks,
Josh

Check out String Overrides module. It allows you to override any translatable string (anything that uses t()) and is very convenient for overriding some text that is shipped with other modules.

If you want to do it without installing new modules - uncomment and edit this in the settings.php file (line ~458):

# $conf['locale_custom_strings_en'][''] = array(
#   'forum'      => 'Discussion board',
#   '@count min' => '@count minutes',
# );


How do I use Xdebug? I have enabled Xdebug in my PHP installation and tried it with Drupal 7. I am interested in profiling, which function runs how many times and where are called (whole tree). There are php.ini settings:

zend_extension="D:\xampp\php\ext\php_xdebug.dll"
xdebug.remote_enable=1
xdebug.remote_port="9000"
xdebug.profiler_enable=1
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir="D:\xampp\tmp"
xdebug.profiler_trigger=on
xdebug.profiler_append=on
xdebug.max_nesting_level=1000

In Drupal 7 it generates cachegrind.out.XXX file, which i was able to open in PHPstorm, or in wincachegrind.

But in Drupal 8, it generates aprox. 400MB file and when i try to open it (PHPstorm or wincachegrind), it throws errors. These are different Incorrect profiler snapshot format, incorrect function parameters, ...

Have someone successfully profiled Drupal 8 functions with Xdebug? Is there some special setting, which I am missing? I wonder, that in Drupal 7 it worked smoothly. Or if you have better tool for this purpose, I would be happy, if you could post it here.

I use windows and PHP 5.6. That is why I choose xdebug and asked this question. Xhprof is not for PHP 5.6 and Tideways for windows is "crap"...

The format shouldn't dependent on the Drupal version, most likely you're running Drupal 7 and 8 on different PHP version which may use different Xdebug.

Since XDebug 2.3, the format of cachegrind files changed and WinCacheGrind does not support this new Callgrind format yet.

So you should use XHProf, or different software which may support it, depending on your operating system.

See also: Missing function names when opening CacheGrind file in WinCacheGrind.


entity_load_multiple returns empty array although an eitity lives in the database? I am trying to debug something related to an issue I am facing. The bottom line is that entity load is not returning the peroper values for some reason. For example:

$cids = array(119570363);
$comments = comment_load_multiple($cids);
dpm($comments);

return an empty array although the comment with id=119570363 exists in the database. I traced entity load function the the comment controller which inherits the load method from DrupalDefaultEntityController.While looking at the method I failed to notice anything that would cause this. Perhaps I am missing something. Are there implicit conditions on the load? Also, I tried with both $reset = FALSE and $reset = TRUE .

comment_load_multiple will only load a comment if the node and the user linked to the comment both exist.

You can see this in the code for CommentController::buildQuery where it does an INNER JOIN on both the node and user tables. Note that if you trace through the execution of comment_load_multiple you have to pass in the RESET argument (or clear the caches before hand) otherwise you will get the cached result, and will never make it into CommentController::buildQuery.

Now the reason CommentController::buildQuery does an INNER JOIN rather than a LEFT JOIN (and the reason I didn't add this as an answer straight away) is that you are not supposed to be in a situation where you have a comment that does not have a node or a user.

You can see this because:

The code for comment_save clearly expects the associated node and user to be set ;
The comment module implements hook_node_delete, and always ensures that comments are deleted when a node is deleted ;
The comment  module implements hook_user_delete, and always ensures that comments are deleted when a user is deleted.

So the problem you are seeing suggests your database is somewhat inconsistent. This could happen if you deleted nodes or users without using the proper API, though it could happen for other reasons (eg. sometimes when dumping and re-saving MySql database you might loose the entry for the anonymous user - it has id 0, and must be in the database users table).

Another note: If this is the only issue affecting the loading then you can get the comments that won't load by doing an SQL query:

SELECT cid
FROM comment
LEFT JOIN node ON node.nid = comment.nid
LEFT JOIN users ON users.uid = comment.uid
WHERE (node.nid IS NULL)
      OR (users.uid IS NULL)


AJAX SettingsCommand Usage Class Documentation: SettingsCommand

I'm trying to figure out how to use this Ajax Command correctly. I must be confused from the documentation, so I'm hoping someone can shed some light where I'm mistaken.

__construct(array $settings, $merge = FALSE)

  array $settings: An array of key/value pairs of JavaScript settings.
  bool $merge: Whether the settings should be merged into the global drupalSettings.

Given the array already in drupalSettings: ['drupalSettings']['myData'] = [1,2,3,4,5];
And the following ajaxCallback I would like to replace the 'myData' array with [2, 4]:

    namespace Drupal\settings_controller_test\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\SettingsCommand;

    class SettingsControllerTestForm extends FormBase
    {
        public function getFormId() { return 'settings_controller_test_form'; }

        public function buildForm(array $form, FormStateInterface $form_state)
        {
            $form['invoker'] = [
                '#type' => 'submit',
                '#value' => t('Invoke Callback'),
                '#ajax' => [
                    'callback' => [$this, 'ajaxCallback']
                    ]
                ];

            $form['#attached']['drupalSettings']['myData'] = [1,2,3,4,5];
            $form['#attached']['library'][] = 'settings_controller_test/test';
            return $form;
        }

        public function ajaxCallback(array &$form, FormStateInterface $form_state)
        {
            $response = new AjaxResponse();

            #clear old myData settings
            $response->addCommand(new SettingsCommand(['myData' => []], TRUE));

            #add new data for myData settings
            $response->addCommand(new SettingsCommand(['myData' => [2,4]], TRUE));

            return $response;
        }

        public function validateForm(array &$form, FormStateInterface $form_state){}
        public function submitForm(array &$form, FormStateInterface $form_state){}
    }

I'm testing the state of 'myData' in JavaScript using the following:

(function ($, Drupal, drupalSettings) {
    Drupal.behaviors.myBehaviour = {
      attach: function (context) {
        //output: [1, 2, 3, 4, 5]
        console.log(drupalSettings.myData);

        $(document).once().ajaxComplete(function(event, xhr, settings) {
          //output: [2, 4, 3, 4, 5]
          console.log(drupalSettings.myData);
        });

      }
    };
  })(jQuery, Drupal, drupalSettings);

UPDATE: The attempt to clear the myData array fails. Then when I attempt to set myData = [2,4] with merge set as TRUE the leading two elements change to 2,4 and the remaining elements in the array are still there.
NOTE: If I change: $response->addCommand(new SettingsCommand(['myData' => [2,4]], TRUE)); to $response->addCommand(new SettingsCommand(['myData' => [2,4]], FALSE)); the myData array remains completely unchanged [1,2,3,4,5]

Yes you need one more command to set the data back to nothing before you can overide it from trial and error the "merge" FALSE does nothing.
so ...

// $response = new AjaxResponse();
// If want to replace you need to empty the array first.
$response->addCommand(new SettingsCommand([
  'MyData' => [],
], TRUE));
// then add new ones.
$response->addCommand(new SettingsCommand([
  'MyData' => [
    'New' => 'New values'
  ],
], TRUE));

See my New full example:  https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21SettingsCommand.php/class/SettingsCommand/8.6.x#comment-64379


How do I use an array with an 'IN' condition on EntityFieldQuery::entityCondition? I read that entityCondition should take an array, and I've constructed an array according to examples I've seen on the web. But no dice. I get the error below. If I use a string, the error goes away.

Here's my code:

$query = new EntityFieldQuery();
$types = array('commerce_product', 'produce_share');
$query->entityCondition('entity_type', $types, 'IN');
$result = $query->execute();

And here's the error:

Warning: Illegal offset type in isset or empty in entity_get_info() (line 7690 of /**/includes/common.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1573 of /**/includes/bootstrap.inc).
EntityFieldQueryException: Entity  has no base table. in EntityFieldQuery->propertyQuery() (line 1209 of /**/includes/entity.inc).

Correct me if I'm wrong, but aren't commerce_product and product_share bundles not entity_type's (both of entity_type node)?

I think you may want:

// The types we're looking for.
$types = array('commerce_product', 'produce_share');

// Build the query.
$query = new EntityFieldQuery()

  // Looking for nodes.
  ->entityCondition('entity_type', 'node')

  // With the specific bundles.
  ->entityConditiion('bundle', $types, 'IN');

// Run the query.
$result = $query->execute();

https://www.drupal.org/node/1343708


Prevent drupal from adding a favicon from default directory in custom theme I want Drupal to look for a favicon in a specific directory dynamically. This is mainly because I'm using the domain access module and I'd like the favicon based off the subdomain that is being used. For example if the url is

example.url.com

I want drupal to look for the favicon in

sites/all/themes/mytheme/example/favicon.ico

If the subdomain is example2 I want it to look for the favicon here

sites/all/themes/mytheme/examples2/favicon.ico

I think I have a handle of how to grab the url and base the location on that but right after I have added the favicon, drupal adds it's own. For example I see this in the header

<link rel="shortcut icon" href="sites/all/themes/mytheme/examples2/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="http://example.url.com/misc/favicon.ico" type="image/vnd.microsoft.icon">

I've accomplished adding my own favicon but it doesn't matter since it is added before anything else. I'm currently using preprocess_html to do this

function mytheme_preprocess_html(&$variables) {
    $favicon = 'sites/all/themes/mytheme/example/favicon.ico';
    $type = 'image/x-icon';
    drupal_add_html_head_link(array('rel' => 'shortcut icon', 'href' => drupal_strip_dangerous_protocols($favicon), 'type' => $type));
}

(It does not yet have the logic to grab the url) I'm assuming that it is at the top based on the term preprocess. Is there a way to give it weight? Or is there another function I should be using?

I found a solution. in Appearance>Mytheme>Settings, there is an option to uncheck shortcut settings.

After unchecking that option the link provided in mytheme_preprocess_html was able to display the favicon unopposed.


Send notification E-Mail to x when x’s content is commented How to notify an author of a node, when her content is commented by another user on Drupal 7?

Use Rules module. Create the following Rule:

Event: after saving a new comment. You will probably want to restrict this by content type as well.
Add action: send mail. Arguments:

To: switch to data selection and choose comment:node:author:mail
Subject: whatever you want, for example "A comment has been posted to your blog post"
Add the message
Condition: NOT comment:node:author:uid and comment:author:uid so that the user does not receive emails for his own comments.

Here's how to insert the name of the node author:

Formatted username:

Dear [comment:node:author:name], [...]

Specific field (e.g. if you have first and last name fields and you want to use only first name):

Dear [comment:node:author:field-first-name], [...]


Undefined index: method in drupal_prepare_form() I am getting this strange notice

  Undefined index: method in drupal_prepare_form()

in my Drupal 7 application but only on production server. It is really weird, on my development PC I have PHP 5.4.6 and on my server I have 5.3.3 and this is probably the only difference. I cannot get this error on my dev PC, so I really don't have any idea what is wrong and how to repair this.

I couldn't find anything good on the web, only that it could be connected with localization modules.

thanks!

I hope, this can be useful, to you

http://drupal.org/node/1024298

Probably, there is new patch introduced, please go through the blog above.


How to import context module export -drupal 7 I have created a Context using the Context module for use with a custom module.

Is it possible to export a context and then import it with my custom module? And if so, where does the data from the export need to go in my module?

Way1: Using Features module

I would recommend you to use features module to export your configurations like context, it will automatically pull the context configurations in code.

Way2: Using custom module

If for some reasons you want to do it in custom code then

Use context export module to export your context. This module will let you the configuration code for context.
Then create a plugin using hook_ctools_plugin_api and hook_context_default_contexts. Refernce link

Sample Implementation for hook_ctools_plugin_api.

This will let Drupal aware of the context export plugin using ctools API.

Sample Implementation for hook_context_default_contexts.

Create file as _context.inc inside your
Add the implementation of hook_context_default_contexts on _context.inc file. As in this example code.


How Can I add a Hierarchical taxonomy Select in views filters and when editing content in Drupal 7 I have created a taxonomy vocabulary called Cars makes  and models  with a structure similar to this:

    -Car Make
    ----Car model
    -----------Year

I want to give the customer, options  to sort them in a View , like many cars sites do:
 a customer choose first the Car make, and automatically models from this make shows in a second level list.
But I want also to use this functionality in the (add content )page,  so when customer  try to sell a car, he will not need to scroll a very large list with makes and  models in the same field.
I cannot use Hierarchical Select. As many topics in this site suggest, because it doesn’t work for exposed filters in Views, with  Drupal 7:
http://drupal.org/node/1170192

I have spent hours and days, trying to fix this issue without any success, my options are very limited:

Turn back to Drupal 6, Just  to use HS with Views exposed filters.
(not a brilliant idea)
Use other CMS like Joomla, in fact there  is
many  Joomla plugins offering this functionality:
http://extensions.joomla.org/extensions/vertical-markets/vehicles ,
but then I will lose all the power of Drupal taxonomy.
Add autocomplete functionality to the views filter and Use
Autocomplete term widget , in the (create content page) , but this
is not very user-friendly method for no experimented users. More,
Autocomplete term widget will allow the creation of new terms, and
I do not want users to accidentally create new terms when they enter
an incorrect model  or make  in the field. Maybe I can correct this
using Content Taxonomy
module(http://drupal.org/project/content_taxonomy), which can deny
the creation of new terms. But this is not a global solution to my
problem.

Is there a module or any JavaScript or PHP snippet  to fix this ?

Response is late but I think(/hope) accurate. You can use the "Simple hierarchical select" http://drupal.org/project/shs. With the help of this module you can make use of the hierarchical select functionality both through views->exposed filters and of course when adding content.

  The widget is available in node forms and as Views exposed filter.


Using LIKE in db_query in D7 I have a query like this in Drupal 6:

$sql = 'SELECT sid, score FROM search_index WHERE word LIKE "%%%s%%"';
$result = db_query($sql,$search_term);

And it worked fine, but now I'm upgrading to Drupal 7.

I read up and this is supposed to work, but it's not:

$sql = 'SELECT sid, score FROM search_index WHERE word LIKE "%:term"';
$result = db_query($sql,array(':term'=>$search_term));

Does anyone know what I'm doing wrong?

Try this.

 $sql = 'SELECT sid, score FROM {search_index} WHERE word LIKE :term';
 $result = db_query($sql, array(':term' => '%' . db_like($search_term)));


Hide a view if less than N results I wonder if it's possible to hide a view (as block view) if it has less than X results.

You could in a template preprocess function easily detect the number of results (rows) that a view has and set the output to an empty string if that is the case.

To get this to work, you might need to do a bit of work in template, as Views always adds some wrapping HTML that you probably don't want if the view is empty.

I would probably be easiest to do in the template_preprocess_views_view() preprocess function. You can consult the views interface to get hints about templates.


Check for field values to be unique when storing into the DB I have a content type "Research assignment" which has several fields including the field "field_user" and "field_project".

I want to remove any old research assignments having the same user and project fields as newly stored research assignment, before storing a new assignment in the DB.

This could be happily implemented by an UNIQUE SQL constraint, but it seems that the Drupal way is to use fields, not direct access to DB. What could you advise: to do this with fields or to revert to plain SQL?

Also, could you show how to use transactions in this case? I don't want anyone to see a research assignment deleted just before it is inserted again with probably other fields.

When you use fields GUI to add fields to a content type, it is correct that the GUI do not let you set the UNIQUE constraint.

However, the fields created in this way is stored in the SQL database. They're in a table named field_data_ followed by the machine name of the field.  So it is possible to add the UNIQUE constraint to any field after it has been created by means of an SQL ALTER TABLE statement, e.g.:

ALTER TABLE `field_data_field_user` ADD UNIQUE (
  `field_user_value`
)

As long as you only do this to fields that you've created yourself, I do not see any problems.

However, it is also possible to create the content type yourself as an entity, using the Drupal Schema API.  If you've business logic that isn't part of the fields repertoire (such as deletion of an old research assignment before inserting a new one), it is probably better to use the Schema API istead of fields to create the content type.  This is still not plain SQL (the Schema API expects you to declare the database tables in a structured array, and Drupal DB API is using PDO-like objects to interact with the database), but it has the same power and flexibility as plain SQL.

Note that declaring the user and project fields unique will not get the old assignment automatically deleted before the new is inserted.  All this constraint does is to reject operations that does not satisfy the contraint.

To use transactions in Drupal, you just call $txn = db_transaction(); in your own module. The transaction will remain open for as long as the variable $txn remains in scope. When $txn is destroyed, the transaction will be committed.


Displaying a standard picture when user has not uploaded a picture I am using the following code.

if ($logged_in) {
  $user = user_load($user->uid);
  print theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $user->picture->uri));
}

It displays the user's picture.

How should I modify it so that so that when the user has NOT uploaded or has deleted his picture a standard "no photo" picture is displayed instead as in:

$no_avi = "http://example.com/sites/default/files/nophoto.jpg";
echo("<img src=\"$no_avi\" />");

The User Picture Field module does not provide this capability.

Basing on the code used by template_preprocess_user_picture(), I would suggest the following code.

if (!empty($user->picture)) {
  if (is_numeric($user->picture)) {
    $account->picture = file_load($user->picture);
  }
  if (!empty($user->picture->uri)) {
    $filepath = $user->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}
if (isset($filepath)) {
  $alt = t("@user's picture", array('@user' => format_username($account)));
  if (module_exists('image') && file_valid_uri($filepath)) {
    $user_picture = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
  else {
    $user_picture = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
}

If you didn't need to use a specific style, but you could use the one set in Drupal settings, the code would simply be the following one.

$user_picture = theme('user_picture', array('account' => $user));

Keep in mind that there are some places where Drupal already shows the user's picture. If you just need to change the image style used for the user's picture, that is possible from Drupal settings (see this other answer). If you need to show the user's picture in a page where Drupal doesn't show them, I would set the default image style for the user's picture in Drupal's admin settings, and use the following code.

$user_picture = theme('user_picture', array('account' => $user));


Drupal commerce price markup field I need to calculate product sell price as gross price * markup (i.e. 1.4) Gross price is stored in field_data_commerce_price table (standard commerce price field). Markup value should be associated with every single product, so I can manage it with views using filters and VBO. I have many product types, so maually created markup field is not a good solution.

Is there any out-of-the-box solution?

and if not:

What is the best way to add new product field using API? (should be added by default for all product types)

If you need a per product price modificator, your best solution is to have a field with this information, you can probably use a normal numeric field for this purpose.

You've got many examples on how to create a field using the API, for example, drupal commerce itself adds a price field every time a product type is generated by using hook_modules_enabled hook.

/**
 * Implements hook_modules_enabled().
 */
function commerce_product_modules_enabled($modules) {
  commerce_product_configure_product_fields($modules);
}

Then in this function

function commerce_product_configure_product_fields($modules = NULL) {
(...)
      // Loop through and configure the product types defined by the module.
      foreach ($product_types as $type => $product_type) {
        commerce_product_configure_product_type($type);
      }

Next

/**
 * Ensures a base price field is present on a product type bundle.
 */
function commerce_product_configure_product_type($type) {
  commerce_price_create_instance('commerce_price', 'commerce_product', $type, t('Price'), 0, 'calculated_sell_price');
}

And finally

function commerce_price_create_instance($field_name, $entity_type, $bundle, $label, $weight = 0, $calculation = FALSE, $display = array()) {
  // Look for or add the specified price field to the requested entity bundle.
  commerce_activate_field($field_name);
  field_cache_clear();

  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle);

  if (empty($field)) {
    $field = array(
      'field_name' => $field_name,
      'type' => 'commerce_price',
      'cardinality' => 1,
      'entity_types' => array($entity_type),
      'translatable' => FALSE,
      'locked' => TRUE,
    );
    $field = field_create_field($field);
  }

  if (empty($instance)) {
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,

      'label' => $label,
      'required' => TRUE,
      'settings' => array(),

      // Because this widget is locked, we need it to use the full price widget
      // since the currency option can't be adjusted at the moment.
      'widget' => array(
        'type' => 'commerce_price_full',
        'weight' => $weight,
        'settings' => array(
          'currency_code' => 'default',
        ),
      ),

      'display' => array(),
    );

    $entity_info = entity_get_info($entity_type);

    // Spoof the default view mode and node teaser so its display type is set.
    $entity_info['view modes'] += array(
      'default' => array(),
      'node_teaser' => array(),
    );

    foreach ($entity_info['view modes'] as $view_mode => $data) {
      $instance['display'][$view_mode] = $display + array(
        'label' => 'hidden',
        'type' => 'commerce_price_formatted_amount',
        'settings' => array(
          'calculation' => $calculation,
        ),
        'weight' => $weight,
      );
    }

    field_create_instance($instance);
  }
}

So you in summary can use hook_modules_enabled to react and loop the product types and create your field and instance. Another examples of this procedure can be found in commerce recurring, commerce discount, commerce coupon and more.


How to find the number of clicks on a flash banner? There is a flash banner in a Drupal website. I want to know number of clicks on that flash banner.

My Question: Is there such option in Drupal (in Joomla there is one).

I would recommend using Google analytics and attach a click event to the banner. using a module would introduce unnecessary overheads


How to do integrate javascript in drupal way I want to integrate this Flex Slider code to drupal but without success. Please help.
here is the code

if($('#homeSlider').length > 0) {

    var hIndex = 0;
    var $hCap = $('#homeSlider').find('.captions').children('li'), $hSlides, $hPrev, $hNext;

    $('#homeSlider').flexslider({
        animation: 'slide',
        animationLoop: true,
        slideshow: true,
        slideshowSpeed: 7000,
        smoothHeight: false,

        controlsContainer: $('#homeSlider').find('.thumbs'),
        keyboard: true,
        controlNav: false,
        start: function(e){

            $hPrev = $('#homeSlider').find('.flex-prev');
            $hNext = $('#homeSlider').find('.flex-next');
            $hSlides = $('#homeSlider').find('.slides').children('li');

            $hPrev.append('');
            $hNext.append('');

            $hPrev = $hPrev.find('img');
            $hNext = $hNext.find('img');

        },
        before: function(e){

            $hCap.eq(hIndex).fadeOut(200);

            var prev = hIndex - 1 < 0 ? e.count-1 : hIndex - 1;
            var next = hIndex + 1 > e.count-1 ? 0 : hIndex + 1;

            hIndex = e.data('flexslider').animatingTo;
            $hCap.eq(hIndex).fadeIn(500);

            changeThumbs(prev, next);

        }
    });

    function changeThumbs(prev, next){
        $hPrev.prop('src', $hSlides.eq(prev).data('thumb'));
        $hNext.prop('src', $hSlides.eq(next+2).data('thumb'));
    }

}

The Managing JavaScript in Drupal 7 guide provides the information to add JavaScript to Drupal. The techniques presented there apply to both themes and (custom) modules:

Add a scripts[] = somescript.js to your module or theme's .info file
Use drupal_add_js() in your module or theme's code
Use the #attached['js'] property in a From API or renderable array.
Note that Drupal already include jQuery, jQuery UI and a bunch of other libraries so you don't, and shouldn't, add them yourself. Instead you should use drupal_add_library() or the #attached['library'] property.

The Working with CSS guide provides the information to add CSS to Drupal. Again, the techniques presented there apply to both themes and (custom) modules. With an exception: addition of style sheets from an .info files only works for a theme and not a module.

Add stylesheets[all][] = somestylesheet.css to a theme's .info file.
Use drupal_add_css() from module or theme's code.
Use #attached[css] property in a From API or renderable array.


Undefined variable: nid I put this code in Rules Action PHP Evaluation. What I want is getting the field_price's value, changing it for negative and returning it for Rule. With this I will be able to charge points because in Rules (Drupal 7) it is impossible to put "-" before data-selector (in this case, field_price's value) and make it negative to charge these points instead of adding them.

<?php
if (arg(0) == 'node') {
   $nid = arg(1);
}
   $node = node_load($nid);
   $value = $node->field_price['und'][0]['value'];
   return $value;
?>

The reason you're getting the error "Undefined variable: nid" in some cases is obvious. You're only assigning a value to $nid if the following is TRUE: arg(0) == 'node'. If arg(0) is something else, $nid never becomes defined, causing the error.

Since it doesn't make sense to use $nid unless it is defined, you can get rid of error by moving the construct where you use the value of $nid inside the if-test, like this:

<?php
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid);
  $value = $node->field_price['und'][0]['value'];
  return $value;
}
else {
  return FALSE;
}
?>

Note that this will return the value stored in the field field_price if arg(0) is equal to the string 'node', and return FALSE otherwise.

You write:

  What I want is getting the field_price's value, changing it for negative and returning it for Rule.

Please note that your original code does not do that.  Nor does mine.  I just told you how to fix the bug. The business logic is still up to you.

Please also note that this has nothing to do with Drupal - it is Programming 101.


How do I change the "Read More" text I have to say I feel embarrassed but after several hours of unsuccessful trials and fruitless research I am resigned to ask for help to the community.

6 months ago I have changed the Read More text link to More information. Now I am asked to roll back to Read More and I can't find out how I made it the first time. I am sure I did not override any function in the theme and almost sure I did write any PHP code.

I believe I have done something with the internationalization module because I have now both strings Read more and More information in the buit-in interface textgroup.

So how can I map the Read more link text to a given entry in the built-in interface?

Thank you!

OK, if you did it with code you probably edited settings.php and did something like:

$conf['locale_custom_strings_en'][''] = array(
  'Read More' => 'More information',
);

You would have to remove that line from the array.

There are a billion ways to do it via code, though, To be safe, you should search for the string "More Information" in all of the sites/ files to be safe.

If you didn't do it with code, there is a decent chance you used the String Overrides module, and did it via the UI.  If so, delete that entry.

If this is related to a view, then you should poke through the settings for that view (don't forget the master and all additional displays).  Look for a link field, and check the "Text to display" option.

If not, poke around the field settings for your content types, eg admin/structure/types/manage/page/fields, and see if you set it there.


Add menu item programmatically Drupal 6 I am trying to add a menu item to a custom menu programmatically in Drupal 6 and have almost gotten it but ran into a weird problem. I can add the item to the menu using the code: drupal_execute('menu_edit_item', $item_array, 'add', NULL, array('menu_name' => $menu_name));
drupal_flush_all_caches();
This somewhat works, but for the link to actually show up in the menu I have to either save the page twice, or save the page and clear the cache from Admin > Performance. Does anyone know why I need to flush the caches twice, or is there a better way to do this? Let me know if you need any more information, I included what I thought was relevant but I may have left something out.

To add menu items use hook_menu():

  This hook enables modules to register paths in order to define how URL
  requests are handled. Paths may be registered for URL handling only,
  or they can register a link to be placed in a menu (usually the
  Navigation menu).

example:

function YOUR_MODULE_NAME_menu() {
  $items['a/b/c'] = array(
    'title' => 'Example menu',
    'page callback' => 'example_callback',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'your-custom-menu-name',
  );
  return $items;

}

To learn more about hooks see here


How to fix "This display does not have a source for contextual filters" I've set up a view to produce a block of content nodes based on taxonomy. I have the filter criteria to include Has Taxonomy term (not empty). Then under advanced I added a contextual filter 'Has Taxonomy Term ID'.

But when I set it up (or edit it) there is a message:

  This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'.

And that type (has taxonomy term ID) comes under 'provide default value'.

I don't mind all of this, but this particular example has 3 taxonomy terms that are quite similar:

Virtual meetings
Virtual classroom
Virtual seminar rooms

These block views are pulled onto a panel page, again based on taxonomy. But on each of the 3 pages there are 3 listings, instead of one!

Can anyone think of what I might be doing wrong here?

I am using Drupal 7 and Views 7.x-3.3.

This is frustrating.  AFAIK

"Content Pane" displays do not have context passed to them ever.
Views have "master" displays that do get context passed.

The "master" display is essentially the view's defaults.  To see it, there is an option here:  admin/structure/views/settings/basic
(or just delete all other displays)

To add a view's "master" display to a panel, you need to see it first:
http:///admin/structure/panels/settings

Now go back to the panel, add content, select "views" instead of "view panes" to see your view.


Search user by field value using Drupal Search Api I have a set of users with field_first_name and field_last_name, and i want to create a user search using the search api, to search for users using those fields, but it doesn't seems to be working.

Here is my code:

$query = Index::load('default_index')
      ->query(array(
          'offset' => 0,
          'limit'  => 12,
      ))
      ->keys($text)
      ->addCondition('search_api_datasource', 'entity:user')
      ->execute();

It's not fetching any of my users per name. I am missing something?

On the first hand, can you check if your content is being indexed properly ?
If yes, then I would recommend using the default search box provided by drupal, and see if you get results.

Assuming you are using search api solr module.